Why styled-components uses Client Component at top level
A Client Component is used at the top level of the tree for the style registry because it is more efficient to extract CSS rules this way. It avoids re-generating styles on subsequent server renders and prevents them from being sent in the Server Component payload.
CSS-in-JS configuration is a three-step opt-in process
Configuring CSS-in-JS in the app directory involves three steps: 1) Create a style registry to collect all CSS rules in a render, 2) Use the useServerInsertedHTML hook to inject rules before any content that might use them, 3) Create a Client Component that wraps the app with the style registry during initial server-side rendering.
CSS-in-JS libraries supported in App Router Client Components
The following CSS-in-JS libraries are supported in Client Components in the app directory: ant-design, chakra-ui, @fluentui/react-components, kuma-ui, @mui/material, @mui/joy, pandacss, styled-jsx, styled-components, stylex, tamagui, tss-react, and vanilla-extract. The emotion library is currently working on support.
CSS-in-JS requires React 18 concurrent rendering support
Using CSS-in-JS with newer React features like Server Components and Streaming requires library authors to support the latest version of React, including concurrent rendering.
styled-jsx App Router setup - registry component
For styled-jsx v5.1.0 in Client Components, create a registry component with 'use client' directive. Import useState from React, useServerInsertedHTML from 'next/navigation', and StyleRegistry and createStyleRegistry from 'styled-jsx'. Use lazy initial state to create the registry once: const [jsxStyleRegistry] = useState(() => createStyleRegistry()). Call useServerInsertedHTML to get styles with jsxStyleRegistry.styles(), flush with jsxStyleRegistry.flush(), and return the styles. Wrap children with <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>.
styled-jsx App Router - root layout integration
Import the styled-jsx registry component into the root layout and wrap the children: <StyledJsxRegistry>{children}</StyledJsxRegistry> inside the html and body tags.
styled-components App Router setup - next.config.js
Enable styled-components in next.config.js by setting module.exports = { compiler: { styledComponents: true } }.
styled-components App Router setup - registry component
For styled-components v6 or newer in Client Components, create a registry component with 'use client' directive. Import useState from React, useServerInsertedHTML from 'next/navigation', and ServerStyleSheet and StyleSheetManager from 'styled-components'. Use lazy initial state: const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet()). In useServerInsertedHTML, call styledComponentsStyleSheet.getStyleElement() to get styles and styledComponentsStyleSheet.instance.clearTag() to clear. On server-side only (if (typeof window === 'undefined')), wrap children with <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>{children}</StyleSheetManager>.
styled-components App Router - server rendering behavior
During server rendering with styled-components, styles are extracted to a global registry and flushed to the <head> of HTML. This ensures style rules are placed before any content that uses them. During streaming, styles from each chunk are collected and appended to existing styles. After client-side hydration is complete, styled-components takes over and injects any further dynamic styles.
JSON-LD validation tools
Validate and test structured data using Google's Rich Results Test (https://search.google.com/test/rich-results) or the generic Schema Markup Validator (https://validator.schema.org/).
JSON-LD TypeScript typing with schema-dts
Use the community package schema-dts to type JSON-LD with TypeScript. Example:
```tsx
import { Product, WithContext } from 'schema-dts'
const jsonLd: WithContext<Product> = {
'@context': 'https://schema.org',
'@type': 'Product',
name: 'Next.js Sticker',
image: 'https://nextjs.org/imgs/sticker.png',
description: 'Dynamic at the speed of static.',
}
```
Why not use next/script for JSON-LD
The next/script component is optimized for loading and executing JavaScript. Since JSON-LD is structured data and not executable code, a native <script> tag is the appropriate choice instead of next/script.
JSON-LD implementation in Next.js
JSON-LD is a format for structured data used by search engines and AI to understand page structure. It can describe entities like persons, events, organizations, movies, books, recipes, and others. The recommended approach is to render structured data as a <script> tag in layout.js or page.js components.
JSON-LD script tag implementation example
Here is a complete example of implementing JSON-LD in a Next.js page component:
```tsx
export default async function Page({ params }) {
const { id } = await params
const product = await getProduct(id)
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
image: product.image,
description: product.description,
}
return (
<section>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
}}
/>
</section>
)
}
```
This example sanitizes the JSON-LD output by replacing '<' with its unicode equivalent.
Tailwind CSS 3.4.8 warns about slow settings
Tailwind CSS version 3.4.8 or newer will warn you about settings that might slow down your build.
Tailwind CSS content array should be specific
In your `tailwind.config.js`, be specific about which files to scan in the `content` array. Avoid broad patterns that might include `node_modules` or other large directories of files that should not be scanned. For example, use `'./src/**/*.{js,ts,jsx,tsx}'` instead of `'../../packages/**/*.{js,ts,jsx,tsx}'` which might match `packages/**/node_modules` too.
Image Component prevents layout shift and optimizes formats
Images should be optimized using the Image Component, which automatically optimizes images, prevents layout shift, and serves them in modern formats like WebP.
Use eslint-plugin-jsx-a11y for accessibility linting
The built-in eslint-plugin-jsx-a11y plugin should be used to catch accessibility issues early in Next.js applications.
Use TypeScript and TS Plugin for type safety
TypeScript and the TypeScript plugin should be used for better type-safety and to catch errors early in Next.js applications.
Font Module optimization removes external network requests
Fonts should be optimized using the Font Module, which automatically hosts font files with other static assets, removes external network requests, and reduces layout shift.
Script Component defers third-party scripts
Third-party scripts should be optimized using the Script Component, which automatically defers scripts and prevents them from blocking the main thread.
Install sass package
To use Sass in Next.js, install the sass package as a dev dependency. It can be installed with pnpm, npm, yarn, or bun.
.scss vs .sass file extensions
The .scss extension requires SCSS syntax, while the .sass extension requires Indented Syntax. The .scss extension is recommended as it is a superset of CSS and does not require learning the Indented Syntax.
Sass support in Next.js
Next.js has built-in support for Sass using the .scss and .sass file extensions after the sass package is installed. Component-level Sass is available via CSS Modules using the .module.scss or .module.sass extensions.
Configure Sass options in next.config.ts
Sass options can be configured using the sassOptions property in next.config.ts or next.config.js. The additionalData option can be used to inject Sass variables globally, for example: sassOptions: { additionalData: `$var: red;` }.
Sass implementation property in next.config.ts
The implementation property in sassOptions specifies which Sass implementation to use. By default, Next.js uses the sass package. Other implementations like sass-embedded can be specified: sassOptions: { implementation: 'sass-embedded' }.
Export Sass variables from CSS Module files
Sass variables can be exported from CSS Module files using the :export selector. For example, a .module.scss file can export a primaryColor variable using :export { primaryColor: $primary-color; } and then import it as a JavaScript object in components.
Using exported Sass variables in Pages Router
In the Pages Router, Sass variables exported from CSS Module files can be imported in _app.js and passed as props to layouts or components. For example: import variables from '../styles/variables.module.scss' allows accessing variables.primaryColor.
Turbopack support for Tailwind CSS
As of Next.js 13.1, Tailwind CSS and PostCSS are supported with Turbopack.
Import global CSS in Pages Router _app file
In the Pages Router, import the global CSS file in pages/_app.js using an alias like `import '@/styles/globals.css'`.
Install Tailwind CSS v3 with Next.js
To install Tailwind CSS v3 in a Next.js application, install tailwindcss@^3, postcss, and autoprefixer as dev dependencies, then run the init command. For pnpm: `pnpm add -D tailwindcss@^3 postcss autoprefixer && npx tailwindcss init -p`. For npm: `npm install -D tailwindcss@^3 postcss autoprefixer && npx tailwindcss init -p`. For yarn: `yarn add -D tailwindcss@^3 postcss autoprefixer && npx tailwindcss init -p`. For bun: `bun add -D tailwindcss@^3 postcss autoprefixer && bunx tailwindcss init -p`. The init command generates tailwind.config.js and postcss.config.js files.
Configure Tailwind v3 template paths in Pages Router
For the Pages Router, configure template paths in tailwind.config.js with content array containing './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', and './app/**/*.{js,ts,jsx,tsx,mdx}'.
Add Tailwind directives to global CSS
Add the Tailwind directives to a global CSS file: @tailwind base; @tailwind components; @tailwind utilities;
Import global CSS in App Router root layout
In the App Router, import the global CSS file in app/layout.tsx or app/layout.js at the root of the application.