Server-rendered CSS injection
A CSS-in-JS library gathers rules while rendering and must emit them into the document head.
Next.js 16+ · Hook
useServerInsertedHTML registers a server-rendering callback that emits collected HTML, commonly CSS-in-JS styles, before dependent content. Use it with a style registry in a Client Component.
Import useServerInsertedHTML from next/navigation in a Client Component and provide a callback that returns the HTML to insert. A style registry can collect rules during server rendering; the callback extracts and flushes them so they are emitted in the document head before content that uses them.
useServerInsertedHTML(callback)| Name | Type | Description |
|---|---|---|
callback | () => React.ReactNode | A callback returning the HTML elements or fragment to insert during server rendering. |
Not explicitly specified on the documentation page.
'use client'
import { useServerInsertedHTML } from 'next/navigation'
import { useState } from 'react'
export default function StyleRegistry({ children }: { children: React.ReactNode }) {
const [styles] = useState(() => new Set<string>())
useServerInsertedHTML(() => {
const elements = [...styles].map((css) => <style key={css}>{css}</style>)
styles.clear()
return <>{elements}</>
})
return <>{children}</>
}This client registry collects styles during rendering, emits them through the insertion callback, then clears the collected entries.
A CSS-in-JS library gathers rules while rendering and must emit them into the document head.
A registry needs to hand generated style elements to Next.js before dependent markup is delivered.
A component must extract and clear per-render style state during App Router server rendering.
It is a hook from next/navigation that accepts a callback for HTML insertion during server rendering. The callback is used to emit collected styles before rendered content that depends on them.
Follow-up: How would you prevent duplicate style output? Extract the registry contents once in the callback and flush or clear the registry immediately afterward.
Create a style registry, collect rules while rendering, and register a callback with useServerInsertedHTML. The callback returns the generated style elements, which Next.js inserts into the head during server rendering.
Follow-up: Why is a Client Component commonly used around the registry? The documented CSS-in-JS pattern uses a Client Component to own the registry while the server-rendered output receives the extracted styles.
The callback should return the styles extracted from the registry and then flush that registry. This places style rules before content that may use them and avoids retaining already-emitted rules.
Follow-up: What should be checked when styles are missing? Verify that the registry surrounds the rendered tree and that the CSS-in-JS library is configured for the App Router pattern.
next/navigationStyleRegistrycreateStyleRegistrystyled-jsxstyled-components