Overview
Server-side rendering (SSR) is the process of rendering React components on the server and sending the fully-rendered HTML to the client. This improves initial page load performance and SEO. Material UI was designed from the ground up to support server-side rendering. The key requirement is providing the page with the required CSS to prevent the flash of unstyled content (FOUC).How It Works
To implement SSR with Material UI:- Create a fresh Emotion cache instance on every request
- Render the React tree with the server-side collector
- Extract the critical CSS
- Pass the CSS and HTML to the client
- On the client side, inject the CSS again before removing the server-injected CSS
Express.js Setup
Here’s a complete example using Express.js and Emotion.Shared Emotion Cache
Create a cache factory that works on both server and client:Theme Configuration
Create a theme shared between client and server:Server Implementation
Implement the Express server with SSR:Client Hydration
Hydrate the server-rendered content on the client:Next.js Integration
Next.js provides built-in SSR support. Material UI offers the@mui/material-nextjs package for seamless integration.
Installation
App Router (Next.js 13+)
For the App Router, useAppRouterCacheProvider:
Theme with CSS Variables
Leverage CSS variables for color schemes:Color Scheme Script
TheInitColorSchemeScript component prevents color scheme flashing:
CSS Layer Support
TheenableCssLayer option wraps Material UI styles in a CSS layer:
Key Concepts
Emotion Cache
The cache configuration must be identical on server and client. Thekey property determines the class name prefix:
Critical CSS Extraction
Emotion’sextractCriticalToChunks identifies which styles are needed for the rendered HTML:
Hydration
UseReactDOM.hydrateRoot() instead of ReactDOM.createRoot() to attach event listeners to server-rendered markup:
Examples
Reference implementations:Troubleshooting
Styles Not Loading
Ensure the Emotion cache key matches between server and client. Mismatched keys cause hydration errors.Flash of Unstyled Content
Verify the CSS is being injected in the server HTML. Check the response HTML for<style> tags with the correct cache key.
Hydration Mismatch
The server and client trees must be identical. Common causes:- Different theme configuration
- Conditional rendering based on browser APIs
- Missing
suppressHydrationWarningon<html>