SSR for Styles: Avoiding the 'Flash'
Server-side rendering for styles sends a fully styled page on the first load, preventing the dreaded "flash of unstyled content" (FOUC). This is crucial for CSS-in-JS libraries. The footgun is assuming it works automatically without proper setup.
WHY IT EXISTS: Client-side rendered apps often load HTML first, then fetch and apply CSS via JavaScript. This delay causes a "flash of unstyled content" (FOUC), where users see a raw, unstyled page for a moment. This provides a poor user experience and can negatively impact perceived performance.
THE MENTAL MODEL: Think of it like pre-packaging a gift. Instead of sending an empty box (the HTML) and then separately sending the wrapping paper (the CSS), you wrap the gift on the server and send the complete, styled package to the user. The browser can display it correctly the moment it arrives.
HOW IT WORKS: During a server-side render, as your components are turned into an HTML string, a special registry collects all the CSS rules generated by your CSS-in-JS library. Before sending the final HTML to the browser, the framework (like Next.js) takes these collected styles and injects them into a <style> tag within the document's <head>. The browser then receives the HTML and the exact CSS needed to render it, all at once.
WHEN TO USE IT: This is a default and necessary pattern when using CSS-in-JS libraries in a server-rendered application like Next.js. It's not optional if you want a good user experience. It ensures a fast First Contentful Paint (FCP) that is also correctly styled.
WHEN NOT TO USE IT: You don't need to worry about this specific mechanism if you are using only static CSS files (e.g., global stylesheets or CSS Modules). In that case, the build process typically handles creating and linking the necessary CSS bundles. The problem is specific to styles generated dynamically at runtime on the server.
ONE CANONICAL EXAMPLE: In Next.js with the App Router, you might use a CSS-in-JS library like Emotion. To make it work with SSR, you create a custom component that extracts the generated styles from a cache on the server and renders them into the root layout. This ensures the styles are present in the initial server-sent HTML, preventing FOUC. Without this setup, the styles would only be applied on the client after hydration, causing a flash.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.