Registry / web-framework / emotion-server

emotion-server

JSON →
library11.0.0jsnpmunverified

@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.

npm install emotion-server
INSTALL
IMPORT
SIG · EMOTION-SERVER
E
emotion-server
web-frameworkjavascriptv11.0.0
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

extractCritical
✓ import { extractCritical } from '@emotion/server';
✗ const { extractCritical } = require('@emotion/server');
This is the primary function for extracting critical CSS from a rendered React string. While CommonJS `require` can sometimes work via transpilation, direct ESM `import` is the standard for modern Node.js and bundled environments.
renderStylesToNodeStream
✓ import { renderStylesToNodeStream } from '@emotion/server';
✗ const { renderStylesToNodeStream } = require('@emotion/server');
Used for React 18+ streaming SSR to inject styles into a Node.js stream. Requires careful integration with `ReactDOMServer.renderToNodeStream` or `renderToPipeableStream`.
CacheProvider
✓ import { CacheProvider } from '@emotion/react';
✗ import { CacheProvider } from '@emotion/core';
Essential for providing an Emotion cache to your React tree during SSR. Emotion v11 renamed `@emotion/core` to `@emotion/react`. Incorrect package or missing `CacheProvider` leads to errors.
createCache
✓ import createCache from '@emotion/cache';
✗ import { createCache } from '@emotion/cache'; // If default export const createCache = require('@emotion/cache'); // Missing .default for default export
`createCache` is a default export from `@emotion/cache` and is used to instantiate a new Emotion cache for each server request. Since Emotion v11, the `key` option is mandatory when creating a custom cache.

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);
Debug
Known issues
breakingMigrating from Emotion v10 to v11 involves significant breaking changes, including package renames (e.g., `@emotion/core` to `@emotion/react`), and a mandatory `key` option when initializing Emotion's cache via `createCache`. Ensure all Emotion-related packages are upgraded to compatible v11 versions.
fix
Review Emotion's v11 migration guide. Update package names and ensure `createCache({ key: 'your-app-key' })` is used. Use the Emotion ESLint plugin with codemods to automate some renames.
affects: >=11.0.0
gotchaIncorrect or missing `CacheProvider` setup on the server or a mismatch between server and client-side generated styles can lead to hydration errors (e.g., UI differences or style re-insertion). Each server render should typically use a new `EmotionCache` instance.
fix
Always wrap your top-level component with `<CacheProvider value={cache}>` during SSR. Ensure a unique cache instance is created for each request on the server. On the client, ensure proper hydration logic is in place, often by calling `hydrate(ids)` if using `extractCritical`.
affects: >=11.0.0
gotchaEmotion's 'default approach' for SSR (without explicit critical extraction) can interfere with `:nth-child` or similar selectors due to style tags being inserted directly into the markup. The advanced approach using `extractCritical` or `createEmotionServer` avoids this.
fix
If experiencing issues with complex selectors, switch to the 'advanced approach' using `extractCritical` with `CacheProvider` on the server and ensure the extracted styles are correctly injected into the `<head>` of your HTML document.
affects: >=10.0.0
deprecatedThe `renderStylesToString` function from `@emotion/server` is largely superseded by `extractCritical` for comprehensive critical CSS extraction and `renderStylesToNodeStream` for React 18 streaming. While it still works, `extractCritical` provides more control over the extracted CSS and IDs.
fix
Prefer `extractCritical` for most SSR scenarios where you render to a string and need to inject styles. For React 18 streaming, use `renderStylesToNodeStream` in conjunction with React's streaming APIs.
affects: <=11.0.0
gotchaIntegrating Emotion with React 18's streaming SSR (`renderToPipeableStream`) is significantly more complex than traditional `renderToString`. `emotion-server` provides `renderStylesToNodeStream`, but advanced setups often require custom transform streams or specific framework integrations.
fix
Consult detailed documentation or framework-specific guides (e.g., Next.js, Gatsby) for React 18 streaming SSR with Emotion. The `renderStylesToNodeStream` should be piped after React's stream.
affects: >=11.0.0
Errors
Common errors & fixes
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Client-side React is trying to hydrate a DOM tree that differs from the server-rendered HTML, often due to mismatched Emotion styles, incorrect cache setup, or missing `hydrate` call.
fix
Ensure the same Emotion cache key and configuration are used on both server and client. Verify that `CacheProvider` wraps your application during SSR. If using `extractCritical`, ensure the extracted `ids` are passed to the client and `hydrate(ids)` is called.
ReferenceError: navigator is not defined
This typically occurs when `createCache` from `@emotion/cache` is invoked directly in a Node.js (server) environment without providing a suitable `container` or `stylisPlugins` option if browser-specific APIs are implicitly accessed.
fix
Ensure `createCache` is called with the `key` option and potentially a custom `container` or `stylisPlugins` if non-browser defaults are an issue. Creating a cache per request on the server also helps isolate styles.
TypeError: Cannot read properties of undefined (reading 'sheet')
This error often indicates that the Emotion cache instance or the `CacheProvider` is not correctly set up or accessible within the React component tree during SSR.
fix
Double-check that `createCache` is correctly called, and the resulting `cache` object is passed to `<CacheProvider value={cache}>` wrapping your application on the server. Verify that all Emotion-related packages are compatible versions.
Error: @emotion/react's CacheProvider was not found.
The Emotion context, provided by `CacheProvider`, is missing from the component tree, preventing Emotion components from accessing the necessary cache.
fix
Ensure that your entire application, especially the root component being rendered server-side, is wrapped within `<CacheProvider value={cache}>` where `cache` is an instance created by `createCache`.
Upgrade
Version history
11.0.0latest on npm
Audit
Dependencies
@emotion/reactrequiredProvides the React context and `CacheProvider` essential for Emotion's SSR and style injection. Emotion v11 renamed `@emotion/core` to `@emotion/react`.
@emotion/cacherequiredRequired for creating and managing the Emotion style cache, which is fundamental to server-side style extraction.
Agent activity
8 hits · last 30 days
node
8
Resources
emotion-server — npm install emotion-server · libregistry