Use CSS-in-JS libraries like styled-components and Emotion with the Next.js App Router.
CSS-in-JS lets you write CSS directly in your JavaScript or TypeScript files, typically co-located with the component that uses it.
Many CSS-in-JS libraries that rely on runtime JavaScript are not compatible with React Server Components. You can only use CSS-in-JS in Client Components. Check your library’s documentation for Server Component support.
To use styled-components with the App Router, you need to set up a client-side style registry. This collects styles generated during a render and flushes them into the <head> of the document.
lib/registry.tsx
'use client'import React, { useState } from 'react'import { useServerInsertedHTML } from 'next/navigation'import { ServerStyleSheet, StyleSheetManager } from 'styled-components'export default function StyledComponentsRegistry({ children,}: { children: React.ReactNode}) { // Only create stylesheet once with lazy initial state const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet()) useServerInsertedHTML(() => { const styles = styledComponentsStyleSheet.getStyleElement() styledComponentsStyleSheet.instance.clearTag() return <>{styles}</> }) if (typeof window !== 'undefined') return <>{children}</> return ( <StyleSheetManager sheet={styledComponentsStyleSheet.instance}> {children} </StyleSheetManager> )}
Wrap your root layout’s children with the registry: