Emotion Server-Side Rendering Utilities

11.0.0 · active · verified Sun Apr 19

@emotion/server is a critical package within the Emotion CSS-in-JS ecosystem, primarily designed to facilitate efficient server-side rendering (SSR) of styled React applications. Its core functionality involves extracting and inlining only the 'critical CSS' required for the initial page load, thereby preventing flashes of unstyled content (FOUC) and improving perceived performance. The package is part of the Emotion v11 stable release, which introduced significant TypeScript improvements and internal shifts to React Hooks. Emotion maintains a consistent, modular release cadence across its packages, with frequent patch updates and coordinated minor/major versions. A key differentiator is its deep integration with the `@emotion/react` and `@emotion/cache` packages, providing robust and performant solutions for complex SSR setups, including support for React's streaming APIs, though this often requires more advanced configurations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `emotion-server`'s `extractCritical` function with React's `renderToString` to extract and inline critical CSS during server-side rendering, ensuring proper `CacheProvider` setup for Emotion v11.

import ReactDOMServer from 'react-dom/server';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { extractCritical } from '@emotion/server';
import { css } from '@emotion/react';

// A simple Emotion-styled React component
const MyStyledComponent = () => (
  <div
    css={css`
      color: hotpink;
      background-color: lightblue;
      padding: 1rem;
      border-radius: 8px;
      &:hover {
        color: white;
      }
    `}
  >
    Hello from Emotion SSR!
  </div>
);

// Create a new Emotion cache for the server request
// The 'key' option is mandatory since Emotion v11
const cache = createCache({ key: 'my-app' });

// Render the component to a string and extract critical CSS
const { html, css: criticalCss, ids } = extractCritical(
  ReactDOMServer.renderToString(
    <CacheProvider value={cache}>
      <MyStyledComponent />
    </CacheProvider>
  )
);

console.log('--- Critical CSS ---');
console.log(criticalCss);
console.log('\n--- Rendered HTML ---');
console.log(`<style data-emotion="${cache.key}-${ids.join(' ')}">${criticalCss}</style>${html}`);

// In a real application, 'criticalCss' would be injected into the <head> of the HTML document.
// The 'ids' should also be passed to the client for proper hydration.
// Example of how to integrate into a full HTML document (simplified):
const fullHtml = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Emotion SSR Example</title>
    <style data-emotion="${cache.key}-${ids.join(' ')}">${criticalCss}</style>
  </head>
  <body>
    <div id="root">${html}</div>
    <script>
      // On the client, hydrate with the same cache key and potentially call emotion/css hydrate function
      // import { hydrate } from '@emotion/css';
      // import createCache from '@emotion/cache';
      // const cache = createCache({ key: 'my-app' });
      // hydrate(${JSON.stringify(ids)});
      // ReactDOMClient.hydrateRoot(document.getElementById('root'), <CacheProvider value={cache}><MyStyledComponent /></CacheProvider>);
    </script>
  </body>
  </html>
`;
console.log('\n--- Full HTML Structure (simplified) ---');
console.log(fullHtml);

view raw JSON →