Unverified Commit c95e357f authored by Joseph's avatar Joseph Committed by GitHub

Backport/docs fixes 16.1.x (#90125)

Trying out a new way to publish updates. We won't always backport this
many docs updates.

Typos and other minor fixes can wait until a new minor release. 

This is more about keeping the docs in sync with the latest release,
while still being able to still or publish content (new guides, etc),
without having to wait for a patch release.

Merging to the backport branch is enough to get the document published
automatically.

---------
Co-authored-by: 's avatarSebastian "Sebbie" Silbermann <sebastian.silbermann@vercel.com>
Co-authored-by: 's avatarCursor Agent <cursoragent@cursor.com>
Co-authored-by: 's avatarDeni Mintsaev <cube327@tuta.io>
Co-authored-by: 's avatarPavan Shinde <pavann97@gmail.com>
Co-authored-by: 's avatarJan Amann <jan@amann.work>
Co-authored-by: 's avatarRhys Evans <wheresrhys@gmail.com>
Co-authored-by: 's avatarEric Rabinowitz <ericrabinowitz@me.com>
Co-authored-by: 's avatarThomas Schrödinger <tomas.computer.guy@gmail.com>
Co-authored-by: 's avatarAbhishek Mardiya <97448460+abhishekmardiya@users.noreply.github.com>
Co-authored-by: 's avatarVasiliy Vanchuk <v.vanchuk@tut.by>
Co-authored-by: 's avatarJimmy Lai <laijimmy0@gmail.com>
Co-authored-by: 's avatarfreek-boon-greenberry <freek.boon@greenberry.nl>
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarAllen Zhou <46854522+allenzhou101@users.noreply.github.com>
Co-authored-by: 's avatarJinsoo Lee <binary01@kakao.com>
Co-authored-by: 's avatarAndrew D'Amelio <dev@andrewdamel.io>
Co-authored-by: 's avatarAndrew Damelio <andrewdamelio@users.noreply.github.com>
Co-authored-by: 's avatarSwarnava Sengupta <swarnava.sengupta@vercel.com>
Co-authored-by: 's avatarJude Gao <jude.gao@vercel.com>
parent cba6144e
...@@ -65,10 +65,22 @@ Learn more about [browser support](/docs/architecture/supported-browsers), inclu ...@@ -65,10 +65,22 @@ Learn more about [browser support](/docs/architecture/supported-browsers), inclu
The quickest way to create a new Next.js app is using [`create-next-app`](/docs/app/api-reference/cli/create-next-app), which sets up everything automatically for you. To create a project, run: The quickest way to create a new Next.js app is using [`create-next-app`](/docs/app/api-reference/cli/create-next-app), which sets up everything automatically for you. To create a project, run:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app
```
```bash package="npm"
npx create-next-app@latest npx create-next-app@latest
``` ```
```bash package="yarn"
yarn create next-app
```
```bash package="bun"
bun create next-app
```
On installation, you'll see the following prompts: On installation, you'll see the following prompts:
```txt filename="Terminal" ```txt filename="Terminal"
......
...@@ -284,7 +284,7 @@ export default function LikeButton({ likes }) { ...@@ -284,7 +284,7 @@ export default function LikeButton({ likes }) {
} }
``` ```
Alternatively, you can stream data from a Server Component to a Client Component with the [`use` Hook](https://react.dev/reference/react/use). See an [example](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-hook). Alternatively, you can stream data from a Server Component to a Client Component with the [`use` API](https://react.dev/reference/react/use). See an [example](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-api).
> **Good to know**: Props passed to Client Components need to be [serializable](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values) by React. > **Good to know**: Props passed to Client Components need to be [serializable](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values) by React.
......
...@@ -33,8 +33,8 @@ Cache Components eliminates these tradeoffs by prerendering routes into a **stat ...@@ -33,8 +33,8 @@ Cache Components eliminates these tradeoffs by prerendering routes into a **stat
At build time, Next.js renders your route's component tree. As long as components don't access network resources, certain system APIs, or require an incoming request to render, their output is **automatically added to the static shell**. Otherwise, you must choose how to handle them: At build time, Next.js renders your route's component tree. As long as components don't access network resources, certain system APIs, or require an incoming request to render, their output is **automatically added to the static shell**. Otherwise, you must choose how to handle them:
- Defer rendering to request time by wrapping components in React's [`<Suspense>`](https://react.dev/reference/react/Suspense), [showing fallback UI](#defer-rendering-to-request-time) until the content is ready, or - Either defer rendering to request time by wrapping components in React's [`<Suspense>`](https://react.dev/reference/react/Suspense), [showing fallback UI](#defer-rendering-to-request-time) until the content is ready
- Cache the result using the [`use cache`](/docs/app/api-reference/directives/use-cache) directive to [include it in the static shell](#using-use-cache) (if no request data is needed) - Or cache the result using the [`use cache`](/docs/app/api-reference/directives/use-cache) directive to [include it in the static shell](#using-use-cache) (if no request data is needed)
Because this happens ahead of time, before a request arrives, we refer to it as prerendering. This generates a static shell consisting of HTML for initial page loads and a serialized [RSC Payload](/docs/app/getting-started/server-and-client-components#on-the-server) for client-side navigation, ensuring the browser receives fully rendered content instantly whether users navigate directly to the URL or transition from another page. Because this happens ahead of time, before a request arrives, we refer to it as prerendering. This generates a static shell consisting of HTML for initial page loads and a serialized [RSC Payload](/docs/app/getting-started/server-and-client-components#on-the-server) for client-side navigation, ensuring the browser receives fully rendered content instantly whether users navigate directly to the URL or transition from another page.
......
...@@ -99,12 +99,12 @@ export default async function Page() { ...@@ -99,12 +99,12 @@ export default async function Page() {
There are two ways to fetch data in Client Components, using: There are two ways to fetch data in Client Components, using:
1. React's [`use` hook](https://react.dev/reference/react/use) 1. React's [`use` API](https://react.dev/reference/react/use)
2. A community library like [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/latest) 2. A community library like [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/latest)
#### Streaming data with the `use` hook #### Streaming data with the `use` API
You can use React's [`use` hook](https://react.dev/reference/react/use) to [stream](#streaming) data from the server to client. Start by fetching data in your Server component, and pass the promise to your Client Component as prop: You can use React's [`use` API](https://react.dev/reference/react/use) to [stream](#streaming) data from the server to client. Start by fetching data in your Server component, and pass the promise to your Client Component as prop:
```tsx filename="app/blog/page.tsx" switcher ```tsx filename="app/blog/page.tsx" switcher
import Posts from '@/app/ui/posts' import Posts from '@/app/ui/posts'
...@@ -138,7 +138,7 @@ export default function Page() { ...@@ -138,7 +138,7 @@ export default function Page() {
} }
``` ```
Then, in your Client Component, use the `use` hook to read the promise: Then, in your Client Component, use the `use` API to read the promise:
```tsx filename="app/ui/posts.tsx" switcher ```tsx filename="app/ui/posts.tsx" switcher
'use client' 'use client'
......
...@@ -206,7 +206,7 @@ Create an error boundary by adding an [`error.js`](/docs/app/api-reference/file- ...@@ -206,7 +206,7 @@ Create an error boundary by adding an [`error.js`](/docs/app/api-reference/file-
import { useEffect } from 'react' import { useEffect } from 'react'
export default function Error({ export default function ErrorPage({
error, error,
reset, reset,
}: { }: {
...@@ -239,7 +239,7 @@ export default function Error({ ...@@ -239,7 +239,7 @@ export default function Error({
import { useEffect } from 'react' import { useEffect } from 'react'
export default function Error({ error, reset }) { export default function ErrorPage({ error, reset }) {
useEffect(() => { useEffect(() => {
// Log the error to an error reporting service // Log the error to an error reporting service
console.error(error) console.error(error)
......
...@@ -14,8 +14,20 @@ related: ...@@ -14,8 +14,20 @@ related:
To update to the latest version of Next.js, you can use the `upgrade` command: To update to the latest version of Next.js, you can use the `upgrade` command:
```bash filename="Terminal" ```bash package="pnpm"
next upgrade pnpm next upgrade
```
```bash package="npm"
npx next upgrade
```
```bash package="yarn"
yarn next upgrade
```
```bash package="bun"
bunx next upgrade
``` ```
Next.js 15 and earlier do not support the `upgrade` command and need to use a separate package instead: Next.js 15 and earlier do not support the `upgrade` command and need to use a separate package instead:
...@@ -46,10 +58,22 @@ bun add next@latest react@latest react-dom@latest eslint-config-next@latest ...@@ -46,10 +58,22 @@ bun add next@latest react@latest react-dom@latest eslint-config-next@latest
To update to the latest canary, make sure you're on the latest version of Next.js and everything is working as expected. Then, run the following command: To update to the latest canary, make sure you're on the latest version of Next.js and everything is working as expected. Then, run the following command:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add next@canary
```
```bash package="npm"
npm i next@canary npm i next@canary
``` ```
```bash package="yarn"
yarn add next@canary
```
```bash package="bun"
bun add next@canary
```
### Features available in canary ### Features available in canary
The following features are currently available in canary: The following features are currently available in canary:
......
---
title: How to set up your Next.js project for AI coding agents
nav_title: AI Coding Agents
description: Learn how to configure your Next.js project so AI coding agents use up-to-date documentation instead of outdated training data.
related:
title: Next Steps
links:
- app/guides/mcp
---
Next.js ships version-matched documentation inside the `next` package, allowing AI coding agents to reference accurate, up-to-date APIs and patterns. An `AGENTS.md` file at the root of your project directs agents to these bundled docs instead of their training data.
## How it works
When you install `next`, the Next.js documentation is bundled at `node_modules/next/dist/docs/`. The bundled docs mirror the structure of the [Next.js documentation site](https://nextjs.org/docs):
```txt
node_modules/next/dist/docs/
├── 01-app/
│ ├── 01-getting-started/
│ ├── 02-guides/
│ └── 03-api-reference/
├── 02-pages/
├── 03-architecture/
└── index.mdx
```
This means agents always have access to docs that match your installed version — no network request or external lookup required.
The `AGENTS.md` file at the root of your project tells agents to read these bundled docs before writing any code. Most AI coding agents — including Claude Code, Cursor, GitHub Copilot, and others — automatically read `AGENTS.md` when they start a session.
## Getting started
### New projects
[`create-next-app`](/docs/app/api-reference/cli/create-next-app) generates `AGENTS.md` and `CLAUDE.md` automatically. No additional setup is needed:
```bash package="pnpm"
pnpm create next-app@canary
```
```bash package="npm"
npx create-next-app@canary
```
```bash package="yarn"
yarn create next-app@canary
```
```bash package="bun"
bun create next-app@canary
```
If you don't want the agent files, pass `--no-agents-md`:
```bash
npx create-next-app@canary --no-agents-md
```
### Existing projects
Ensure you are on Next.js `v16.2.0-canary.37` or later, then add the following files to the root of your project.
`AGENTS.md` contains the instructions that agents will read:
```md filename="AGENTS.md"
<!-- BEGIN:nextjs-agent-rules -->
# Next.js: ALWAYS read docs before coding
Before any Next.js work, find and read the relevant doc in `node_modules/next/dist/docs/`. Your training data is outdated — the docs are the source of truth.
<!-- END:nextjs-agent-rules -->
```
`CLAUDE.md` uses the `@` import syntax to include `AGENTS.md`, so [Claude Code](https://docs.anthropic.com/en/docs/claude-code) users get the same instructions without duplicating content:
```md filename="CLAUDE.md"
@AGENTS.md
```
## Understanding AGENTS.md
The default `AGENTS.md` contains a single, focused instruction: **read the bundled docs before writing code**. This is intentionally minimal — the goal is to redirect agents from stale training data to the accurate, version-matched documentation in `node_modules/next/dist/docs/`.
The `<!-- BEGIN:nextjs-agent-rules -->` and `<!-- END:nextjs-agent-rules -->` comment markers delimit the Next.js-managed section. You can add your own project-specific instructions outside these markers without worrying about them being overwritten by future updates.
The bundled docs include guides, API references, and file conventions for the App Router and Pages Router. When an agent encounters a task involving routing, data fetching, or any other Next.js feature, it can look up the correct API in the bundled docs rather than relying on potentially outdated training data.
> **Good to know:** To see how bundled docs and `AGENTS.md` improve agent performance on real-world Next.js tasks, visit the [benchmark results](https://nextjs.org/evals).
...@@ -12,12 +12,24 @@ related: ...@@ -12,12 +12,24 @@ related:
Next.js supports the "Backend for Frontend" pattern. This lets you create public endpoints to handle HTTP requests and return any content type—not just HTML. You can also access data sources and perform side effects like updating remote data. Next.js supports the "Backend for Frontend" pattern. This lets you create public endpoints to handle HTTP requests and return any content type—not just HTML. You can also access data sources and perform side effects like updating remote data.
If you are starting a new project, using `create-next-app` with the `--api` flag automatically includes an example `route.ts` in your new project’s `app/` folder, demonstrating how to create an API endpoint. If you are starting a new project, using `create-next-app` with the `--api` flag automatically includes an example `route.ts` in your new project's `app/` folder, demonstrating how to create an API endpoint.
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --api
```
```bash package="npm"
npx create-next-app@latest --api npx create-next-app@latest --api
``` ```
```bash package="yarn"
yarn create next-app --api
```
```bash package="bun"
bun create next-app --api
```
> **Good to know**: Next.js backend capabilities are not a full backend replacement. They serve as an API layer that: > **Good to know**: Next.js backend capabilities are not a full backend replacement. They serve as an API layer that:
> >
> - is publicly reachable > - is publicly reachable
......
...@@ -39,14 +39,17 @@ Every time a page is viewed, a fresh nonce should be generated. This means that ...@@ -39,14 +39,17 @@ Every time a page is viewed, a fresh nonce should be generated. This means that
For example: For example:
> **Good to know**: In development, `'unsafe-eval'` is required because React uses `eval` to provide enhanced debugging information, such as reconstructing server-side error stacks in the browser. `unsafe-eval` is not required for production. Neither React nor Next.js use `eval` in production by default.
```ts filename="proxy.ts" switcher ```ts filename="proxy.ts" switcher
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
export function proxy(request: NextRequest) { export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const isDev = process.env.NODE_ENV === 'development'
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ''};
style-src 'self' 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}';
img-src 'self' blob: data:; img-src 'self' blob: data:;
font-src 'self'; font-src 'self';
...@@ -88,9 +91,10 @@ import { NextResponse } from 'next/server' ...@@ -88,9 +91,10 @@ import { NextResponse } from 'next/server'
export function proxy(request) { export function proxy(request) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
const isDev = process.env.NODE_ENV === 'development'
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ''};
style-src 'self' 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}';
img-src 'self' blob: data:; img-src 'self' blob: data:;
font-src 'self'; font-src 'self';
...@@ -483,9 +487,11 @@ When SRI is enabled, you can continue using your existing CSP policies. SRI work ...@@ -483,9 +487,11 @@ When SRI is enabled, you can continue using your existing CSP policies. SRI work
> **Good to know**: For dynamic rendering scenarios, you can still generate nonces with proxy if needed, combining both SRI integrity attributes and nonce-based CSP approaches. > **Good to know**: For dynamic rendering scenarios, you can still generate nonces with proxy if needed, combining both SRI integrity attributes and nonce-based CSP approaches.
```js filename="next.config.js" ```js filename="next.config.js"
const isDev = process.env.NODE_ENV === 'development'
const cspHeader = ` const cspHeader = `
default-src 'self'; default-src 'self';
script-src 'self'; script-src 'self'${isDev ? " 'unsafe-eval'" : ''};
style-src 'self'; style-src 'self';
img-src 'self' blob: data:; img-src 'self' blob: data:;
font-src 'self'; font-src 'self';
...@@ -540,7 +546,7 @@ CSP implementation differs between development and production environments: ...@@ -540,7 +546,7 @@ CSP implementation differs between development and production environments:
### Development Environment ### Development Environment
In development, you will need to enable `'unsafe-eval'` to support APIs that provide additional debugging information: In development, you will need to enable `'unsafe-eval'` because React uses `eval` to provide enhanced debugging information, such as reconstructing server-side error stacks in the browser to show you where errors originated on the server:
```ts filename="proxy.ts" switcher ```ts filename="proxy.ts" switcher
export function proxy(request: NextRequest) { export function proxy(request: NextRequest) {
......
...@@ -17,7 +17,6 @@ Take a look at the [following example](https://github.com/vercel/next.js/tree/ca ...@@ -17,7 +17,6 @@ Take a look at the [following example](https://github.com/vercel/next.js/tree/ca
```ts filename="server.ts" switcher ```ts filename="server.ts" switcher
import { createServer } from 'http' import { createServer } from 'http'
import { parse } from 'url'
import next from 'next' import next from 'next'
const port = parseInt(process.env.PORT || '3000', 10) const port = parseInt(process.env.PORT || '3000', 10)
...@@ -29,7 +28,6 @@ app.prepare().then(() => { ...@@ -29,7 +28,6 @@ app.prepare().then(() => {
createServer((req, res) => { createServer((req, res) => {
handle(req, res) handle(req, res)
}).listen(port) }).listen(port)
})
console.log( console.log(
`> Server listening at http://localhost:${port} as ${ `> Server listening at http://localhost:${port} as ${
...@@ -41,7 +39,6 @@ app.prepare().then(() => { ...@@ -41,7 +39,6 @@ app.prepare().then(() => {
```js filename="server.js" switcher ```js filename="server.js" switcher
import { createServer } from 'http' import { createServer } from 'http'
import { parse } from 'url'
import next from 'next' import next from 'next'
const port = parseInt(process.env.PORT || '3000', 10) const port = parseInt(process.env.PORT || '3000', 10)
...@@ -53,7 +50,6 @@ app.prepare().then(() => { ...@@ -53,7 +50,6 @@ app.prepare().then(() => {
createServer((req, res) => { createServer((req, res) => {
handle(req, res) handle(req, res)
}).listen(port) }).listen(port)
})
console.log( console.log(
`> Server listening at http://localhost:${port} as ${ `> Server listening at http://localhost:${port} as ${
......
...@@ -399,9 +399,15 @@ However, for this to happen, the captured variables are sent to the client and b ...@@ -399,9 +399,15 @@ However, for this to happen, the captured variables are sent to the client and b
When **self-hosting** your Next.js application across multiple servers, each server instance may end up with a different encryption key, leading to potential inconsistencies. When **self-hosting** your Next.js application across multiple servers, each server instance may end up with a different encryption key, leading to potential inconsistencies.
To mitigate this, you can overwrite the encryption key using the `process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. Specifying this variable ensures that your encryption keys are persistent across builds, and all server instances use the same key. This variable **must** be AES-GCM encrypted. To mitigate this, you can overwrite the encryption key using the `process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. Specifying this variable ensures that your encryption keys are persistent across builds, and all server instances use the same key.
This is an advanced use case where consistent encryption behavior across multiple deployments is critical for your application. You should consider standard security practices such key rotation and signing. The key must be a base64-encoded value whose decoded length matches a valid AES key size (16, 24, or 32 bytes). Next.js generates 32-byte keys by default. You can generate a compatible key using your platform’s cryptographic tools, for example:
```bash
openssl rand -base64 32
```
This is an advanced use case where consistent encryption behavior across multiple deployments is critical for your application. Follow standard security practices such as key rotation and signing. See the [Self-Hosting guide](/docs/app/guides/self-hosting#server-functions-encryption-key) for deployment-specific considerations.
### Allowed origins (advanced) ### Allowed origins (advanced)
......
...@@ -113,8 +113,20 @@ For React-specific debugging, install the [React Developer Tools](https://react. ...@@ -113,8 +113,20 @@ For React-specific debugging, install the [React Developer Tools](https://react.
To debug server-side Next.js code with browser DevTools, you need to pass the `--inspect` flag: To debug server-side Next.js code with browser DevTools, you need to pass the `--inspect` flag:
```bash filename="Terminal" ```bash package="pnpm"
next dev --inspect pnpm dev --inspect
```
```bash package="npm"
npm run dev -- --inspect
```
```bash package="yarn"
yarn dev --inspect
```
```bash package="bun"
bun run dev --inspect
``` ```
The value of `--inspect` is passed to the underlying Node.js process. Check out the [`--inspect` docs for advanced use cases](https://nodejs.org/api/cli.html#--inspecthostport). The value of `--inspect` is passed to the underlying Node.js process. Check out the [`--inspect` docs for advanced use cases](https://nodejs.org/api/cli.html#--inspecthostport).
......
...@@ -86,10 +86,22 @@ This package is used internally by Next.js to load environment variables from `. ...@@ -86,10 +86,22 @@ This package is used internally by Next.js to load environment variables from `.
To use it, install the package and use the `loadEnvConfig` function to load the environment variables: To use it, install the package and use the `loadEnvConfig` function to load the environment variables:
```bash ```bash package="pnpm"
pnpm add @next/env
```
```bash package="npm"
npm install @next/env npm install @next/env
``` ```
```bash package="yarn"
yarn add @next/env
```
```bash package="bun"
bun add @next/env
```
```tsx filename="envConfig.ts" switcher ```tsx filename="envConfig.ts" switcher
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
...@@ -145,7 +157,7 @@ Non-`NEXT_PUBLIC_` environment variables are only available in the Node.js envir ...@@ -145,7 +157,7 @@ Non-`NEXT_PUBLIC_` environment variables are only available in the Node.js envir
In order to make the value of an environment variable accessible in the browser, Next.js can "inline" a value, at build time, into the js bundle that is delivered to the client, replacing all references to `process.env.[variable]` with a hard-coded value. To tell it to do this, you just have to prefix the variable with `NEXT_PUBLIC_`. For example: In order to make the value of an environment variable accessible in the browser, Next.js can "inline" a value, at build time, into the js bundle that is delivered to the client, replacing all references to `process.env.[variable]` with a hard-coded value. To tell it to do this, you just have to prefix the variable with `NEXT_PUBLIC_`. For example:
```txt filename="Terminal" ```txt filename=".env"
NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
``` ```
......
...@@ -176,7 +176,7 @@ To display validation errors or messages, turn the component that defines the `< ...@@ -176,7 +176,7 @@ To display validation errors or messages, turn the component that defines the `<
When using `useActionState`, the Server function signature will change to receive a new `prevState` or `initialState` parameter as its first argument. When using `useActionState`, the Server function signature will change to receive a new `prevState` or `initialState` parameter as its first argument.
```tsx filename="app/actions.ts" highlight={4} switcher ```tsx filename="app/actions.ts" highlight={5} switcher
'use server' 'use server'
import { z } from 'zod' import { z } from 'zod'
...@@ -189,7 +189,7 @@ export async function createUser(initialState: any, formData: FormData) { ...@@ -189,7 +189,7 @@ export async function createUser(initialState: any, formData: FormData) {
} }
``` ```
```jsx filename="app/actions.ts" highlight={4} switcher ```jsx filename="app/actions.ts" highlight={7} switcher
'use server' 'use server'
import { z } from 'zod' import { z } from 'zod'
......
...@@ -285,7 +285,7 @@ For a more precise method of revalidation, invalidate cached pages on-demand wit ...@@ -285,7 +285,7 @@ For a more precise method of revalidation, invalidate cached pages on-demand wit
For example, this Server Action would get called after adding a new post. Regardless of how you retrieve your data in your Server Component, either using `fetch` or connecting to a database, this will invalidate the cache for the entire route. The next request to that route will trigger regeneration and serve fresh data, which will then be cached for subsequent requests. For example, this Server Action would get called after adding a new post. Regardless of how you retrieve your data in your Server Component, either using `fetch` or connecting to a database, this will invalidate the cache for the entire route. The next request to that route will trigger regeneration and serve fresh data, which will then be cached for subsequent requests.
> **Note:** `revalidatePath` invalidates the cache entries but regeneration happens on the next request. If you want to eagerly regenerate the cache entry immediately instead of waiting for the next request, you can use the Pages router [`res.revalidate`](docs/pages/guides/incremental-static-regeneration#on-demand-validation-with-resrevalidate) method. We're working on adding new methods to provide eager regeneration capabilities for the App Router. > **Note:** `revalidatePath` invalidates the cache entries but regeneration happens on the next request. If you want to eagerly regenerate the cache entry immediately instead of waiting for the next request, you can use the Pages router [`res.revalidate`](/docs/pages/guides/incremental-static-regeneration#on-demand-validation-with-resrevalidate) method. We're working on adding new methods to provide eager regeneration capabilities for the App Router.
```ts filename="app/actions.ts" switcher ```ts filename="app/actions.ts" switcher
'use server' 'use server'
......
...@@ -16,7 +16,7 @@ Instrumentation is the process of using code to integrate monitoring and logging ...@@ -16,7 +16,7 @@ Instrumentation is the process of using code to integrate monitoring and logging
To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/api-reference/file-conventions/src-folder) folder if using one). To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/api-reference/file-conventions/src-folder) folder if using one).
Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated. Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated, and must complete before the server is ready to handle requests.
For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/observability/otel-overview): For example, to use Next.js with [OpenTelemetry](https://opentelemetry.io/) and [@vercel/otel](https://vercel.com/docs/observability/otel-overview):
......
...@@ -54,15 +54,42 @@ Make sure you're using the latest version of Next.js. Each new version often inc ...@@ -54,15 +54,42 @@ Make sure you're using the latest version of Next.js. Each new version often inc
Turbopack is now the default bundler for Next.js development and provides significant performance improvements over webpack. Turbopack is now the default bundler for Next.js development and provides significant performance improvements over webpack.
```bash ```bash package="pnpm"
pnpm add next@latest
pnpm dev # Turbopack is used by default
```
```bash package="npm"
npm install next@latest npm install next@latest
npm run dev # Turbopack is used by default npm run dev # Turbopack is used by default
``` ```
```bash package="yarn"
yarn add next@latest
yarn dev # Turbopack is used by default
```
```bash package="bun"
bun add next@latest
bun dev # Turbopack is used by default
```
If you need to use Webpack instead of Turbopack, you can opt-in: If you need to use Webpack instead of Turbopack, you can opt-in:
```bash ```bash package="pnpm"
npm run dev --webpack pnpm dev --webpack
```
```bash package="npm"
npm run dev -- --webpack
```
```bash package="yarn"
yarn dev --webpack
```
```bash package="bun"
bun run dev --webpack
``` ```
[Learn more about Turbopack](/blog/turbopack-for-development-stable). See our [upgrade guides](/docs/app/guides/upgrading) and codemods for more information. [Learn more about Turbopack](/blog/turbopack-for-development-stable). See our [upgrade guides](/docs/app/guides/upgrading) and codemods for more information.
...@@ -208,10 +235,22 @@ It provides detailed information about the time taken for each module to compile ...@@ -208,10 +235,22 @@ It provides detailed information about the time taken for each module to compile
1. Make sure you have the latest version of Next.js installed. 1. Make sure you have the latest version of Next.js installed.
1. Generate a Turbopack trace file: 1. Generate a Turbopack trace file:
```bash ```bash package="pnpm"
NEXT_TURBOPACK_TRACING=1 pnpm dev
```
```bash package="npm"
NEXT_TURBOPACK_TRACING=1 npm run dev NEXT_TURBOPACK_TRACING=1 npm run dev
``` ```
```bash package="yarn"
NEXT_TURBOPACK_TRACING=1 yarn dev
```
```bash package="bun"
NEXT_TURBOPACK_TRACING=1 bun dev
```
1. Navigate around your application or make edits to files to reproduce the problem. 1. Navigate around your application or make edits to files to reproduce the problem.
1. Stop the Next.js development server. 1. Stop the Next.js development server.
1. A file called `trace-turbopack` will be available in the `.next/dev` folder. 1. A file called `trace-turbopack` will be available in the `.next/dev` folder.
......
...@@ -54,10 +54,22 @@ For more configuration options, see the [next-devtools-mcp repository](https://g ...@@ -54,10 +54,22 @@ For more configuration options, see the [next-devtools-mcp repository](https://g
1. Start your Next.js development server: 1. Start your Next.js development server:
```bash filename="Terminal" ```bash package="pnpm"
pnpm dev
```
```bash package="npm"
npm run dev npm run dev
``` ```
```bash package="yarn"
yarn dev
```
```bash package="bun"
bun dev
```
2. Your Coding Agent will automatically connect to the running Next.js instance via `next-devtools-mcp` 2. Your Coding Agent will automatically connect to the running Next.js instance via `next-devtools-mcp`
3. Open your application in the browser to view pages 3. Open your application in the browser to view pages
......
...@@ -32,10 +32,22 @@ The `@next/mdx` package, and related packages, are used to configure Next.js so ...@@ -32,10 +32,22 @@ The `@next/mdx` package, and related packages, are used to configure Next.js so
Install these packages to render MDX with Next.js: Install these packages to render MDX with Next.js:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add @next/mdx @mdx-js/loader @mdx-js/react @types/mdx
```
```bash package="npm"
npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx
``` ```
```bash package="yarn"
yarn add @next/mdx @mdx-js/loader @mdx-js/react @types/mdx
```
```bash package="bun"
bun add @next/mdx @mdx-js/loader @mdx-js/react @types/mdx
```
## Configure `next.config.mjs` ## Configure `next.config.mjs`
Update the `next.config.mjs` file at your project's root to configure it to use MDX: Update the `next.config.mjs` file at your project's root to configure it to use MDX:
...@@ -747,93 +759,6 @@ export default withMDX(nextConfig) ...@@ -747,93 +759,6 @@ export default withMDX(nextConfig)
> >
> remark and rehype plugins without serializable options cannot be used yet with [Turbopack](/docs/app/api-reference/turbopack), because JavaScript functions can't be passed to Rust. > remark and rehype plugins without serializable options cannot be used yet with [Turbopack](/docs/app/api-reference/turbopack), because JavaScript functions can't be passed to Rust.
## Remote MDX
If your MDX files or content lives _somewhere else_, you can fetch it dynamically on the server. This is useful for content stored in a CMS, database, or anywhere else. A community package for this use is [`next-mdx-remote-client`](https://github.com/ipikuka/next-mdx-remote-client?tab=readme-ov-file#the-part-associated-with-nextjs-app-router).
> **Good to know**: Please proceed with caution. MDX compiles to JavaScript and is executed on the server. You should only fetch MDX content from a trusted source, otherwise this can lead to remote code execution (RCE).
The following example uses `next-mdx-remote-client`:
<AppOnly>
```tsx filename="app/mdx-page-remote/page.tsx" switcher
import { MDXRemote } from 'next-mdx-remote-client/rsc'
export default async function RemoteMdxPage() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https://...')
const markdown = await res.text()
return <MDXRemote source={markdown} />
}
```
```jsx filename="app/mdx-page-remote/page.js" switcher
import { MDXRemote } from 'next-mdx-remote-client/rsc'
export default async function RemoteMdxPage() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https://...')
const markdown = await res.text()
return <MDXRemote source={markdown} />
}
```
</AppOnly>
<PagesOnly>
```tsx filename="pages/mdx-page-remote.tsx" switcher
import {
serialize,
type SerializeResult,
} from 'next-mdx-remote-client/serialize'
import { MDXClient } from 'next-mdx-remote-client'
type Props = {
mdxSource: SerializeResult
}
export default function RemoteMdxPage({ mdxSource }: Props) {
if ('error' in mdxSource) {
// either render error UI or throw `mdxSource.error`
}
return <MDXClient {...mdxSource} />
}
export async function getStaticProps() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https:...')
const mdxText = await res.text()
const mdxSource = await serialize({ source: mdxText })
return { props: { mdxSource } }
}
```
```jsx filename="pages/mdx-page-remote.js" switcher
import { serialize } from 'next-mdx-remote-client/serialize'
import { MDXClient } from 'next-mdx-remote-client'
export default function RemoteMdxPage({ mdxSource }) {
if ('error' in mdxSource) {
// either render error UI or throw `mdxSource.error`
}
return <MDXClient {...mdxSource} />
}
export async function getStaticProps() {
// MDX text - can be from a database, CMS, fetch, anywhere...
const res = await fetch('https:...')
const mdxText = await res.text()
const mdxSource = await serialize({ source: mdxText })
return { props: { mdxSource } }
}
```
</PagesOnly>
Navigating to the `/mdx-page-remote` route should display your rendered MDX.
## Deep Dive: How do you transform markdown into HTML? ## Deep Dive: How do you transform markdown into HTML?
React does not natively understand markdown. The markdown plaintext needs to first be transformed into HTML. This can be accomplished with `remark` and `rehype`. React does not natively understand markdown. The markdown plaintext needs to first be transformed into HTML. This can be accomplished with `remark` and `rehype`.
......
...@@ -20,18 +20,42 @@ The minimum Node.js version is now **v18.17**. See the [Node.js documentation](h ...@@ -20,18 +20,42 @@ The minimum Node.js version is now **v18.17**. See the [Node.js documentation](h
To update to Next.js version 13, run the following command using your preferred package manager: To update to Next.js version 13, run the following command using your preferred package manager:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add next@latest react@latest react-dom@latest
```
```bash package="npm"
npm install next@latest react@latest react-dom@latest npm install next@latest react@latest react-dom@latest
``` ```
```bash package="yarn"
yarn add next@latest react@latest react-dom@latest
```
```bash package="bun"
bun add next@latest react@latest react-dom@latest
```
### ESLint Version ### ESLint Version
If you're using ESLint, you need to upgrade your ESLint version: If you're using ESLint, you need to upgrade your ESLint version:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -D eslint-config-next@latest
```
```bash package="npm"
npm install -D eslint-config-next@latest npm install -D eslint-config-next@latest
``` ```
```bash package="yarn"
yarn add -D eslint-config-next@latest
```
```bash package="bun"
bun add -D eslint-config-next@latest
```
> **Good to know**: You may need to restart the ESLint server in VS Code for the ESLint changes to take effect. Open the Command Palette (`cmd+shift+p` on Mac; `ctrl+shift+p` on Windows) and search for `ESLint: Restart ESLint Server`. > **Good to know**: You may need to restart the ESLint server in VS Code for the ESLint changes to take effect. Open the Command Palette (`cmd+shift+p` on Mac; `ctrl+shift+p` on Windows) and search for `ESLint: Restart ESLint Server`.
## Next Steps ## Next Steps
...@@ -121,10 +145,22 @@ We recommend reducing the combined complexity of these updates by breaking down ...@@ -121,10 +145,22 @@ We recommend reducing the combined complexity of these updates by breaking down
Update to the latest Next.js version (requires 13.4 or greater): Update to the latest Next.js version (requires 13.4 or greater):
```bash ```bash package="pnpm"
pnpm add next@latest
```
```bash package="npm"
npm install next@latest npm install next@latest
``` ```
```bash package="yarn"
yarn add next@latest
```
```bash package="bun"
bun add next@latest
```
Then, create a new `app` directory at the root of your project (or `src/` directory). Then, create a new `app` directory at the root of your project (or `src/` directory).
### Step 2: Creating a Root Layout ### Step 2: Creating a Root Layout
......
...@@ -55,10 +55,22 @@ Our goal is to get a working Next.js application as quickly as possible so that ...@@ -55,10 +55,22 @@ Our goal is to get a working Next.js application as quickly as possible so that
Install Next.js in your existing project: Install Next.js in your existing project:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add next@latest
```
```bash package="npm"
npm install next@latest npm install next@latest
``` ```
```bash package="yarn"
yarn add next@latest
```
```bash package="bun"
bun add next@latest
```
### Step 2: Create the Next.js Configuration File ### Step 2: Create the Next.js Configuration File
Create a `next.config.ts` at the root of your project (same level as your `package.json`). This file holds your [Next.js configuration options](/docs/app/api-reference/config/next-config-js). Create a `next.config.ts` at the root of your project (same level as your `package.json`). This file holds your [Next.js configuration options](/docs/app/api-reference/config/next-config-js).
...@@ -470,10 +482,22 @@ next-env.d.ts ...@@ -470,10 +482,22 @@ next-env.d.ts
Now you can run: Now you can run:
```bash ```bash package="pnpm"
pnpm dev
```
```bash package="npm"
npm run dev npm run dev
``` ```
```bash package="yarn"
yarn dev
```
```bash package="bun"
bun dev
```
Open [http://localhost:3000](http://localhost:3000). You should see your application now running on Next.js (in SPA mode). Open [http://localhost:3000](http://localhost:3000). You should see your application now running on Next.js (in SPA mode).
### Step 11: Clean Up ### Step 11: Clean Up
......
...@@ -56,10 +56,22 @@ chances of encountering issues during the migration process and reduces merge co ...@@ -56,10 +56,22 @@ chances of encountering issues during the migration process and reduces merge co
The first thing you need to do is to install `next` as a dependency: The first thing you need to do is to install `next` as a dependency:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add next@latest
```
```bash package="npm"
npm install next@latest npm install next@latest
``` ```
```bash package="yarn"
yarn add next@latest
```
```bash package="bun"
bun add next@latest
```
### Step 2: Create the Next.js Configuration File ### Step 2: Create the Next.js Configuration File
Create a `next.config.mjs` at the root of your project. This file will hold your Create a `next.config.mjs` at the root of your project. This file will hold your
......
...@@ -104,9 +104,9 @@ Routing requests through [`rewrites`](/docs/app/api-reference/config/next-config ...@@ -104,9 +104,9 @@ Routing requests through [`rewrites`](/docs/app/api-reference/config/next-config
```js filename="proxy.js" ```js filename="proxy.js"
export async function proxy(request) { export async function proxy(request) {
const { pathname, search } = req.nextUrl; const { pathname, search } = request.nextUrl
if (pathname === '/your-path' && myFeatureFlag.isEnabled()) { if (pathname === '/your-path' && myFeatureFlag.isEnabled()) {
return NextResponse.rewrite(`${rewriteDomain}${pathname}${search}); return NextResponse.rewrite(`${rewriteDomain}${pathname}${search}`)
} }
} }
``` ```
......
...@@ -32,10 +32,22 @@ That's why we prepared a package `@vercel/otel` that helps you get started quick ...@@ -32,10 +32,22 @@ That's why we prepared a package `@vercel/otel` that helps you get started quick
To get started, install the following packages: To get started, install the following packages:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
```bash package="npm"
npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
``` ```
```bash package="yarn"
yarn add @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
```bash package="bun"
bun add @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
<AppOnly> <AppOnly>
Next, create a custom [`instrumentation.ts`](/docs/app/guides/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): Next, create a custom [`instrumentation.ts`](/docs/app/guides/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one):
...@@ -92,10 +104,22 @@ The `@vercel/otel` package provides many configuration options and should serve ...@@ -92,10 +104,22 @@ The `@vercel/otel` package provides many configuration options and should serve
Firstly you need to install OpenTelemetry packages: Firstly you need to install OpenTelemetry packages:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash package="npm"
npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
``` ```
```bash package="yarn"
yarn add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash package="bun"
bun add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
Now you can initialize `NodeSDK` in your `instrumentation.ts`. Now you can initialize `NodeSDK` in your `instrumentation.ts`.
Unlike `@vercel/otel`, `NodeSDK` is not compatible with edge runtime, so you need to make sure that you are importing them only when `process.env.NEXT_RUNTIME === 'nodejs'`. We recommend creating a new file `instrumentation.node.ts` which you conditionally import only when using node: Unlike `@vercel/otel`, `NodeSDK` is not compatible with edge runtime, so you need to make sure that you are importing them only when `process.env.NEXT_RUNTIME === 'nodejs'`. We recommend creating a new file `instrumentation.node.ts` which you conditionally import only when using node:
...@@ -189,10 +213,22 @@ OpenTelemetry Collector is not necessary. You can use a custom OpenTelemetry exp ...@@ -189,10 +213,22 @@ OpenTelemetry Collector is not necessary. You can use a custom OpenTelemetry exp
You can add a custom span with [OpenTelemetry APIs](https://opentelemetry.io/docs/instrumentation/js/instrumentation). You can add a custom span with [OpenTelemetry APIs](https://opentelemetry.io/docs/instrumentation/js/instrumentation).
```bash filename="Terminal" ```bash package="pnpm"
pnpm add @opentelemetry/api
```
```bash package="npm"
npm install @opentelemetry/api npm install @opentelemetry/api
``` ```
```bash package="yarn"
yarn add @opentelemetry/api
```
```bash package="bun"
bun add @opentelemetry/api
```
The following example demonstrates a function that fetches GitHub stars and adds a custom `fetchGithubStars` span to track the fetch request's result: The following example demonstrates a function that fetches GitHub stars and adds a custom `fetchGithubStars` span to track the fetch request's result:
```ts ```ts
......
...@@ -29,10 +29,22 @@ The Next.js Bundle Analyzer is integrated with Turbopack's module graph. You can ...@@ -29,10 +29,22 @@ The Next.js Bundle Analyzer is integrated with Turbopack's module graph. You can
To get started, run the following command and open up the interactive view in your browser. To get started, run the following command and open up the interactive view in your browser.
```bash filename="Terminal" ```bash filename="Terminal" package="npm"
npx next experimental-analyze npx next experimental-analyze
``` ```
```bash filename="Terminal" package="yarn"
yarn next experimental-analyze
```
```bash filename="Terminal" package="pnpm"
pnpm next experimental-analyze
```
```bash filename="Terminal" package="bun"
bunx next experimental-analyze
```
### Step 2: Filter and inspect modules ### Step 2: Filter and inspect modules
Within the UI, you can filter by route, environment (client or server), and type (JavaScript, CSS, JSON), or search by file: Within the UI, you can filter by route, environment (client or server), and type (JavaScript, CSS, JSON), or search by file:
...@@ -62,10 +74,22 @@ Click a module to see its size, inspect its full import chain and see exactly wh ...@@ -62,10 +74,22 @@ Click a module to see its size, inspect its full import chain and see exactly wh
If you want to share the analysis with teammates or compare bundle sizes before/after optimizations, you can skip the interactive view and save the analysis as a static file with the `--output` flag: If you want to share the analysis with teammates or compare bundle sizes before/after optimizations, you can skip the interactive view and save the analysis as a static file with the `--output` flag:
```bash filename="Terminal" ```bash filename="Terminal" package="npm"
npx next experimental-analyze --output npx next experimental-analyze --output
``` ```
```bash filename="Terminal" package="yarn"
yarn next experimental-analyze --output
```
```bash filename="Terminal" package="pnpm"
pnpm next experimental-analyze --output
```
```bash filename="Terminal" package="bun"
bunx next experimental-analyze --output
```
This command writes the output to `.next/diagnostics/analyze`. You can copy this directory elsewhere to compare results: This command writes the output to `.next/diagnostics/analyze`. You can copy this directory elsewhere to compare results:
```bash filename="Terminal" ```bash filename="Terminal"
...@@ -82,14 +106,22 @@ The [`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyze ...@@ -82,14 +106,22 @@ The [`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyze
Install the plugin by running the following command: Install the plugin by running the following command:
```bash ```bash package="pnpm"
npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/bundle-analyzer pnpm add @next/bundle-analyzer
``` ```
```bash package="npm"
npm install @next/bundle-analyzer
```
```bash package="yarn"
yarn add @next/bundle-analyzer
```
```bash package="bun"
bun add @next/bundle-analyzer
```
Then, add the bundle analyzer's settings to your `next.config.js`. Then, add the bundle analyzer's settings to your `next.config.js`.
```js filename="next.config.js" ```js filename="next.config.js"
......
...@@ -513,10 +513,22 @@ To use the Web Push API, you need to generate [VAPID](https://vapidkeys.com/) ke ...@@ -513,10 +513,22 @@ To use the Web Push API, you need to generate [VAPID](https://vapidkeys.com/) ke
First, install web-push globally: First, install web-push globally:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -g web-push
```
```bash package="npm"
npm install -g web-push npm install -g web-push
``` ```
```bash package="yarn"
yarn global add web-push
```
```bash package="bun"
bun add -g web-push
```
Generate the VAPID keys by running: Generate the VAPID keys by running:
```bash filename="Terminal" ```bash filename="Terminal"
......
...@@ -10,10 +10,22 @@ Next.js has built-in support for integrating with Sass after the package is inst ...@@ -10,10 +10,22 @@ Next.js has built-in support for integrating with Sass after the package is inst
First, install [`sass`](https://github.com/sass/sass): First, install [`sass`](https://github.com/sass/sass):
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -D sass
```
```bash package="npm"
npm install --save-dev sass npm install --save-dev sass
``` ```
```bash package="yarn"
yarn add -D sass
```
```bash package="bun"
bun add -D sass
```
> **Good to know**: > **Good to know**:
> >
> Sass supports [two different syntaxes](https://sass-lang.com/documentation/syntax), each with their own extension. > Sass supports [two different syntaxes](https://sass-lang.com/documentation/syntax), each with their own extension.
......
...@@ -139,12 +139,24 @@ module.exports = { ...@@ -139,12 +139,24 @@ module.exports = {
} }
``` ```
Then, run `next` (normally `npm run dev` or `yarn dev`) and Next.js will guide you through the installation of the required packages to finish the setup: Then, run the development server and Next.js will guide you through the installation of the required packages to finish the setup:
```bash filename="Terminal" ```bash package="pnpm"
pnpm dev
```
```bash package="npm"
npm run dev npm run dev
``` ```
```bash package="yarn"
yarn dev
```
```bash package="bun"
bun dev
```
You'll see instructions like these: Please install Partytown by running `npm install @qwik.dev/partytown` You'll see instructions like these: Please install Partytown by running `npm install @qwik.dev/partytown`
Once setup is complete, defining `strategy="worker"` will automatically instantiate Partytown in your application and offload the script to a web worker. Once setup is complete, defining `strategy="worker"` will automatically instantiate Partytown in your application and offload the script to a web worker.
......
...@@ -180,11 +180,55 @@ module.exports = { ...@@ -180,11 +180,55 @@ module.exports = {
} }
``` ```
## Multi-Server Deployments
When running Next.js across multiple server instances (for example, containers behind a load balancer), there are additional considerations to ensure consistent behavior.
### Server Functions encryption key
Next.js encrypts [Server Function](/docs/app/getting-started/updating-data) closure variables before sending them to the client. By default, a unique encryption key is generated for each build.
When running multiple server instances, all instances must use the same encryption key. Otherwise, a Server Function encrypted by one instance cannot be decrypted by another, causing "Failed to find Server Action" errors.
Set a consistent encryption key using the `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. The key must be a base64-encoded value with a valid AES key length (16, 24, or 32 bytes). Next.js generates 32-byte keys by default.
```bash
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=your-generated-key next build
```
The key is embedded in the build output and used automatically at runtime. Learn more in the [Data Security guide](/docs/app/guides/data-security#overwriting-encryption-keys-advanced).
### Deployment identifier
Configure a [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) to enable version skew protection during rolling deployments. This ensures clients always receive assets from a consistent deployment version.
### Shared cache
By default, Next.js uses an in-memory cache that is not shared across instances. For consistent caching behavior, use [`'use cache: remote'`](/docs/app/api-reference/directives/use-cache-remote) with a [custom cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers) that stores data in external storage.
## Version Skew ## Version Skew
Next.js will automatically mitigate most instances of [version skew](https://www.industrialempathy.com/posts/version-skew/) and automatically reload the application to retrieve new assets when detected. For example, if there is a mismatch in the `deploymentId`, transitions between pages will perform a hard navigation versus using a prefetched value. When self-hosting across multiple instances or doing rolling deployments, [version skew](/docs/app/glossary#version-skew) can cause:
- **Missing assets**: The client requests JavaScript or CSS files that no longer exist on the server
- **Server Function mismatches**: The client invokes a Server Function using an ID from a previous build that the server no longer recognizes
- **Navigation failures**: Prefetched page data from an old deployment is incompatible with the new server
Next.js uses the [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) to detect and handle version skew. When a deployment ID is configured:
- Static assets include a `?dpl=<deploymentId>` query parameter
- Client-side navigation requests include an `x-deployment-id` header
- The server compares the client's deployment ID with its own
If a mismatch is detected, Next.js triggers a hard navigation (full page reload) instead of a client-side navigation. This ensures the client fetches assets from a consistent deployment version.
```js filename="next.config.js"
module.exports = {
deploymentId: process.env.DEPLOYMENT_VERSION,
}
```
When the application is reloaded, there may be a loss of application state if it's not designed to persist between page navigations. For example, using URL state or local storage would persist state after a page refresh. However, component state like `useState` would be lost in such navigations. > **Good to know:** When the application is reloaded, there may be a loss of application state if it's not designed to persist between page navigations. URL state or local storage would persist, but component state like `useState` would be lost.
<AppOnly> <AppOnly>
......
...@@ -33,7 +33,7 @@ Let's explore common patterns used to build SPAs and how Next.js solves them. ...@@ -33,7 +33,7 @@ Let's explore common patterns used to build SPAs and how Next.js solves them.
### Using React’s `use` within a Context Provider ### Using React’s `use` within a Context Provider
We recommend fetching data in a parent component (or layout), returning the Promise, and then unwrapping the value in a Client Component with React’s [`use` hook](https://react.dev/reference/react/use). We recommend fetching data in a parent component (or layout), returning the Promise, and then unwrapping the value in a Client Component with React’s [`use` API](https://react.dev/reference/react/use).
Next.js can start data fetching early on the server. In this example, that’s the root layout — the entry point to your application. The server can immediately begin streaming a response to the client. Next.js can start data fetching early on the server. In this example, that’s the root layout — the entry point to your application. The server can immediately begin streaming a response to the client.
...@@ -79,7 +79,7 @@ export default function RootLayout({ children }) { ...@@ -79,7 +79,7 @@ export default function RootLayout({ children }) {
} }
``` ```
While you can [defer and pass a single Promise](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-hook) as a prop to a Client Component, we generally see this pattern paired with a React context provider. This enables easier access from Client Components with a custom React Hook. While you can [defer and pass a single Promise](/docs/app/getting-started/fetching-data#streaming-data-with-the-use-api) as a prop to a Client Component, we generally see this pattern paired with a React context provider. This enables easier access from Client Components with a custom React Hook.
You can forward a Promise to the React context provider: You can forward a Promise to the React context provider:
......
...@@ -16,22 +16,42 @@ description: Learn how to set up Cypress with Next.js for End-to-End (E2E) and C ...@@ -16,22 +16,42 @@ description: Learn how to set up Cypress with Next.js for End-to-End (E2E) and C
You can use `create-next-app` with the [with-cypress example](https://github.com/vercel/next.js/tree/canary/examples/with-cypress) to quickly get started. You can use `create-next-app` with the [with-cypress example](https://github.com/vercel/next.js/tree/canary/examples/with-cypress) to quickly get started.
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --example with-cypress with-cypress-app
```
```bash package="npm"
npx create-next-app@latest --example with-cypress with-cypress-app npx create-next-app@latest --example with-cypress with-cypress-app
``` ```
```bash package="yarn"
yarn create next-app --example with-cypress with-cypress-app
```
```bash package="bun"
bun create next-app --example with-cypress with-cypress-app
```
</AppOnly> </AppOnly>
## Manual setup ## Manual setup
To manually set up Cypress, install `cypress` as a dev dependency: To manually set up Cypress, install `cypress` as a dev dependency:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -D cypress
```
```bash package="npm"
npm install -D cypress npm install -D cypress
# or ```
```bash package="yarn"
yarn add -D cypress yarn add -D cypress
# or ```
pnpm install -D cypress
```bash package="bun"
bun add -D cypress
``` ```
Add the Cypress `open` command to the `package.json` scripts field: Add the Cypress `open` command to the `package.json` scripts field:
...@@ -50,10 +70,22 @@ Add the Cypress `open` command to the `package.json` scripts field: ...@@ -50,10 +70,22 @@ Add the Cypress `open` command to the `package.json` scripts field:
Run Cypress for the first time to open the Cypress testing suite: Run Cypress for the first time to open the Cypress testing suite:
```bash filename="Terminal" ```bash package="pnpm"
pnpm cypress:open
```
```bash package="npm"
npm run cypress:open npm run cypress:open
``` ```
```bash package="yarn"
yarn cypress:open
```
```bash package="bun"
bun run cypress:open
```
You can choose to configure **E2E Testing** and/or **Component Testing**. Selecting any of these options will automatically create a `cypress.config.js` file and a `cypress` folder in your project. You can choose to configure **E2E Testing** and/or **Component Testing**. Selecting any of these options will automatically create a `cypress.config.js` file and a `cypress` folder in your project.
## Creating your first Cypress E2E test ## Creating your first Cypress E2E test
......
...@@ -8,8 +8,8 @@ In React and Next.js, there are a few different types of tests you can write, ea ...@@ -8,8 +8,8 @@ In React and Next.js, there are a few different types of tests you can write, ea
## Types of tests ## Types of tests
- **Unit Testing** involves testing individual units (or blocks of code) in isolation. In React, a unit can be a single function, hook, or component. - **Unit Testing** involves testing individual units (or blocks of code) in isolation. In React, a unit can be a single function, hook, or component.
- **Component Testing** is a more focused version of unit testing where the primary subject of the tests is React components. This may involve testing how components are rendered, their interaction with props, and their behavior in response to user events. - **Component Testing** is a more focused version of unit testing where the primary subject of the tests is React components. This may involve testing how components are rendered, their interaction with props, and their behavior in response to user events.
- **Integration Testing** involves testing how multiple units work together. This can be a combination of components, hooks, and functions. - **Integration Testing** involves testing how multiple units work together. This can be a combination of components, hooks, and functions.
- **End-to-End (E2E) Testing** involves testing user flows in an environment that simulates real user scenarios, like the browser. This means testing specific tasks (e.g. signup flow) in a production-like environment. - **End-to-End (E2E) Testing** involves testing user flows in an environment that simulates real user scenarios, like the browser. This means testing specific tasks (e.g. signup flow) in a production-like environment.
- **Snapshot Testing** involves capturing the rendered output of a component and saving it to a snapshot file. When tests run, the current rendered output of the component is compared against the saved snapshot. Changes in the snapshot are used to indicate unexpected changes in behavior. - **Snapshot Testing** involves capturing the rendered output of a component and saving it to a snapshot file. When tests run, the current rendered output of the component is compared against the saved snapshot. Changes in the snapshot are used to indicate unexpected changes in behavior.
......
...@@ -14,32 +14,60 @@ Jest and React Testing Library are frequently used together for **Unit Testing** ...@@ -14,32 +14,60 @@ Jest and React Testing Library are frequently used together for **Unit Testing**
You can use `create-next-app` with the Next.js [with-jest](https://github.com/vercel/next.js/tree/canary/examples/with-jest) example to quickly get started: You can use `create-next-app` with the Next.js [with-jest](https://github.com/vercel/next.js/tree/canary/examples/with-jest) example to quickly get started:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --example with-jest with-jest-app
```
```bash package="npm"
npx create-next-app@latest --example with-jest with-jest-app npx create-next-app@latest --example with-jest with-jest-app
``` ```
```bash package="yarn"
yarn create next-app --example with-jest with-jest-app
```
```bash package="bun"
bun create next-app --example with-jest with-jest-app
```
## Manual setup ## Manual setup
Since the release of [Next.js 12](https://nextjs.org/blog/next-12), Next.js now has built-in configuration for Jest. Since the release of [Next.js 12](https://nextjs.org/blog/next-12), Next.js now has built-in configuration for Jest.
To set up Jest, install `jest` and the following packages as dev dependencies: To set up Jest, install `jest` and the following packages as dev dependencies:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
```
```bash package="npm"
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# or ```
```bash package="yarn"
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# or ```
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
```bash package="bun"
bun add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
``` ```
Generate a basic Jest configuration file by running the following command: Generate a basic Jest configuration file by running the following command:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create jest@latest
```
```bash package="npm"
npm init jest@latest npm init jest@latest
# or ```
```bash package="yarn"
yarn create jest@latest yarn create jest@latest
# or ```
pnpm create jest@latest
```bash package="bun"
bun create jest@latest
``` ```
This will take you through a series of prompts to setup Jest for your project, including automatically creating a `jest.config.ts|js` file. This will take you through a series of prompts to setup Jest for your project, including automatically creating a `jest.config.ts|js` file.
...@@ -369,12 +397,20 @@ it('renders homepage unchanged', () => { ...@@ -369,12 +397,20 @@ it('renders homepage unchanged', () => {
Then, run the following command to run your tests: Then, run the following command to run your tests:
```bash filename="Terminal" ```bash package="pnpm"
pnpm test
```
```bash package="npm"
npm run test npm run test
# or ```
```bash package="yarn"
yarn test yarn test
# or ```
pnpm test
```bash package="bun"
bun run test
``` ```
## Additional Resources ## Additional Resources
......
...@@ -10,20 +10,40 @@ Playwright is a testing framework that lets you automate Chromium, Firefox, and ...@@ -10,20 +10,40 @@ Playwright is a testing framework that lets you automate Chromium, Firefox, and
The fastest way to get started is to use `create-next-app` with the [with-playwright example](https://github.com/vercel/next.js/tree/canary/examples/with-playwright). This will create a Next.js project complete with Playwright configured. The fastest way to get started is to use `create-next-app` with the [with-playwright example](https://github.com/vercel/next.js/tree/canary/examples/with-playwright). This will create a Next.js project complete with Playwright configured.
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --example with-playwright with-playwright-app
```
```bash package="npm"
npx create-next-app@latest --example with-playwright with-playwright-app npx create-next-app@latest --example with-playwright with-playwright-app
``` ```
```bash package="yarn"
yarn create next-app --example with-playwright with-playwright-app
```
```bash package="bun"
bun create next-app --example with-playwright with-playwright-app
```
## Manual setup ## Manual setup
To install Playwright, run the following command: To install Playwright, run the following command:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create playwright
```
```bash package="npm"
npm init playwright npm init playwright
# or ```
```bash package="yarn"
yarn create playwright yarn create playwright
# or ```
pnpm create playwright
```bash package="bun"
bun create playwright
``` ```
This will take you through a series of prompts to setup and configure Playwright for your project, including adding a `playwright.config.ts` file. Please refer to the [Playwright installation guide](https://playwright.dev/docs/intro#installation) for the step-by-step guide. This will take you through a series of prompts to setup and configure Playwright for your project, including adding a `playwright.config.ts` file. Please refer to the [Playwright installation guide](https://playwright.dev/docs/intro#installation) for the step-by-step guide.
......
...@@ -12,21 +12,54 @@ Vitest and React Testing Library are frequently used together for **Unit Testing ...@@ -12,21 +12,54 @@ Vitest and React Testing Library are frequently used together for **Unit Testing
You can use `create-next-app` with the Next.js [with-vitest](https://github.com/vercel/next.js/tree/canary/examples/with-vitest) example to quickly get started: You can use `create-next-app` with the Next.js [with-vitest](https://github.com/vercel/next.js/tree/canary/examples/with-vitest) example to quickly get started:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --example with-vitest with-vitest-app
```
```bash package="npm"
npx create-next-app@latest --example with-vitest with-vitest-app npx create-next-app@latest --example with-vitest with-vitest-app
``` ```
```bash package="yarn"
yarn create next-app --example with-vitest with-vitest-app
```
```bash package="bun"
bun create next-app --example with-vitest with-vitest-app
```
## Manual Setup ## Manual Setup
To manually set up Vitest, install `vitest` and the following packages as dev dependencies: To manually set up Vitest, install `vitest` and the following packages as dev dependencies:
```bash filename="Terminal" ```bash package="pnpm"
# Using TypeScript
pnpm add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
# Using JavaScript
pnpm add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
```
```bash package="npm"
# Using TypeScript # Using TypeScript
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
# Using JavaScript # Using JavaScript
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
``` ```
```bash package="yarn"
# Using TypeScript
yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
# Using JavaScript
yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
```
```bash package="bun"
# Using TypeScript
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
# Using JavaScript
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
```
Create a `vitest.config.mts|js` file in the root of your project, and add the following options: Create a `vitest.config.mts|js` file in the root of your project, and add the following options:
```ts filename="vitest.config.mts" switcher ```ts filename="vitest.config.mts" switcher
...@@ -185,14 +218,20 @@ test('Page', () => { ...@@ -185,14 +218,20 @@ test('Page', () => {
Then, run the following command to run your tests: Then, run the following command to run your tests:
```bash filename="Terminal" ```bash package="pnpm"
pnpm test
```
```bash package="npm"
npm run test npm run test
# or ```
```bash package="yarn"
yarn test yarn test
# or ```
pnpm test
# or ```bash package="bun"
bun test bun run test
``` ```
## Additional Resources ## Additional Resources
......
...@@ -14,10 +14,22 @@ All third-party integrations provided by `@next/third-parties` have been optimiz ...@@ -14,10 +14,22 @@ All third-party integrations provided by `@next/third-parties` have been optimiz
To get started, install the `@next/third-parties` library: To get started, install the `@next/third-parties` library:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add @next/third-parties@latest next@latest
```
```bash package="npm"
npm install @next/third-parties@latest next@latest npm install @next/third-parties@latest next@latest
``` ```
```bash package="yarn"
yarn add @next/third-parties@latest next@latest
```
```bash package="bun"
bun add @next/third-parties@latest next@latest
```
{/* To do: Remove this paragraph once package becomes stable */} {/* To do: Remove this paragraph once package becomes stable */}
`@next/third-parties` is currently an **experimental** library under active development. We recommend installing it with the **latest** or **canary** flags while we work on adding more third-party integrations. `@next/third-parties` is currently an **experimental** library under active development. We recommend installing it with the **latest** or **canary** flags while we work on adding more third-party integrations.
......
...@@ -10,14 +10,38 @@ description: Upgrade your Next.js Application from Version 14 to 15. ...@@ -10,14 +10,38 @@ description: Upgrade your Next.js Application from Version 14 to 15.
To update to Next.js version 15, you can use the `upgrade` codemod: To update to Next.js version 15, you can use the `upgrade` codemod:
```bash filename="Terminal" ```bash package="pnpm"
pnpm dlx @next/codemod@canary upgrade latest
```
```bash package="npm"
npx @next/codemod@canary upgrade latest npx @next/codemod@canary upgrade latest
``` ```
```bash package="yarn"
yarn dlx @next/codemod@canary upgrade latest
```
```bash package="bun"
bunx @next/codemod@canary upgrade latest
```
If you prefer to do it manually, ensure that you're installing the latest Next & React versions: If you prefer to do it manually, ensure that you're installing the latest Next & React versions:
```bash filename="Terminal" ```bash package="pnpm"
npm i next@latest react@latest react-dom@latest eslint-config-next@latest pnpm add next@latest react@latest react-dom@latest eslint-config-next@latest
```
```bash package="npm"
npm install next@latest react@latest react-dom@latest eslint-config-next@latest
```
```bash package="yarn"
yarn add next@latest react@latest react-dom@latest eslint-config-next@latest
```
```bash package="bun"
bun add next@latest react@latest react-dom@latest eslint-config-next@latest
``` ```
> **Good to know:** > **Good to know:**
......
...@@ -59,10 +59,22 @@ Learn more in the documentation [here](/docs/app/guides/mcp). ...@@ -59,10 +59,22 @@ Learn more in the documentation [here](/docs/app/guides/mcp).
To update to Next.js version 16, you can use the `upgrade` [codemod](/docs/app/guides/upgrading/codemods#160): To update to Next.js version 16, you can use the `upgrade` [codemod](/docs/app/guides/upgrading/codemods#160):
```bash filename="Terminal" ```bash package="pnpm"
pnpm dlx @next/codemod@canary upgrade latest
```
```bash package="npm"
npx @next/codemod@canary upgrade latest npx @next/codemod@canary upgrade latest
``` ```
```bash package="yarn"
yarn dlx @next/codemod@canary upgrade latest
```
```bash package="bun"
bunx @next/codemod@canary upgrade latest
```
The [codemod](/docs/app/guides/upgrading/codemods#160) is able to: The [codemod](/docs/app/guides/upgrading/codemods#160) is able to:
- Update `next.config.js` to use the new `turbopack` configuration - Update `next.config.js` to use the new `turbopack` configuration
...@@ -73,10 +85,22 @@ The [codemod](/docs/app/guides/upgrading/codemods#160) is able to: ...@@ -73,10 +85,22 @@ The [codemod](/docs/app/guides/upgrading/codemods#160) is able to:
If you prefer to do it manually, install the latest Next.js and React versions: If you prefer to do it manually, install the latest Next.js and React versions:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add next@latest react@latest react-dom@latest
```
```bash package="npm"
npm install next@latest react@latest react-dom@latest npm install next@latest react@latest react-dom@latest
``` ```
```bash package="yarn"
yarn add next@latest react@latest react-dom@latest
```
```bash package="bun"
bun add next@latest react@latest react-dom@latest
```
If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions. If you are using TypeScript, ensure you also upgrade `@types/react` and `@types/react-dom` to their latest versions.
## Node.js runtime and browser support ## Node.js runtime and browser support
...@@ -408,10 +432,22 @@ module.exports = nextConfig ...@@ -408,10 +432,22 @@ module.exports = nextConfig
Install the latest version of the React Compiler plugin: Install the latest version of the React Compiler plugin:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -D babel-plugin-react-compiler
```
```bash package="npm"
npm install -D babel-plugin-react-compiler npm install -D babel-plugin-react-compiler
``` ```
```bash package="yarn"
yarn add -D babel-plugin-react-compiler
```
```bash package="bun"
bun add -D babel-plugin-react-compiler
```
> **Good to know:** Expect compile times in development and during builds to be higher when enabling this option as the React Compiler relies on Babel. > **Good to know:** Expect compile times in development and during builds to be higher when enabling this option as the React Compiler relies on Babel.
## Caching APIs ## Caching APIs
...@@ -877,10 +913,22 @@ Additionally, a lockfile mechanism prevents multiple `next dev` or `next build` ...@@ -877,10 +913,22 @@ Additionally, a lockfile mechanism prevents multiple `next dev` or `next build`
Since the development server outputs to `.next/dev`, the [Turbopack tracing command](/docs/app/guides/local-development#turbopack-tracing) should be: Since the development server outputs to `.next/dev`, the [Turbopack tracing command](/docs/app/guides/local-development#turbopack-tracing) should be:
```bash ```bash package="pnpm"
pnpm next internal trace .next/dev/trace-turbopack
```
```bash package="npm"
npx next internal trace .next/dev/trace-turbopack npx next internal trace .next/dev/trace-turbopack
``` ```
```bash package="yarn"
yarn next internal trace .next/dev/trace-turbopack
```
```bash package="bun"
bunx next internal trace .next/dev/trace-turbopack
```
## Parallel Routes `default.js` requirement ## Parallel Routes `default.js` requirement
All [parallel route](/docs/app/api-reference/file-conventions/parallel-routes) slots now require explicit `default.js` files. Builds will fail without them. All [parallel route](/docs/app/api-reference/file-conventions/parallel-routes) slots now require explicit `default.js` files. Builds will fail without them.
...@@ -1038,10 +1086,22 @@ The `next lint` command has been removed. Use Biome or ESLint directly. `next bu ...@@ -1038,10 +1086,22 @@ The `next lint` command has been removed. Use Biome or ESLint directly. `next bu
A codemod is available to automate migration: A codemod is available to automate migration:
```bash filename="Terminal" ```bash package="pnpm"
pnpm dlx @next/codemod@canary next-lint-to-eslint-cli .
```
```bash package="npm"
npx @next/codemod@canary next-lint-to-eslint-cli . npx @next/codemod@canary next-lint-to-eslint-cli .
``` ```
```bash package="yarn"
yarn dlx @next/codemod@canary next-lint-to-eslint-cli .
```
```bash package="bun"
bunx @next/codemod@canary next-lint-to-eslint-cli .
```
The `eslint` option in the Next.js config file is also removed. The `eslint` option in the Next.js config file is also removed.
```js filename="next.config.mjs" ```js filename="next.config.mjs"
......
...@@ -14,7 +14,7 @@ related: ...@@ -14,7 +14,7 @@ related:
- app/api-reference/functions/connection - app/api-reference/functions/connection
--- ---
While the `use cache` directive is sufficient for most application needs, you might occasionally notice that cached operations are re-running more often than expected, or that your upstream services (CMS, databases, external APIs) are getting more hits than you'd expect. This can happen because in-memory caching has inherent limitations: While the `use cache` directive is sufficient for most application needs, you might notice that cached operations are re-running more often than expected, or that your upstream services (CMS, databases, external APIs) are getting more hits than you'd expect. This can happen because `use cache` stores entries in-memory, which has inherent limitations:
- Cache entries being evicted to make room for new ones - Cache entries being evicted to make room for new ones
- Memory constraints in your deployment environment - Memory constraints in your deployment environment
...@@ -22,7 +22,7 @@ While the `use cache` directive is sufficient for most application needs, you mi ...@@ -22,7 +22,7 @@ While the `use cache` directive is sufficient for most application needs, you mi
Note that `use cache` still provides value beyond server-side caching: it informs Next.js what can be prefetched and defines stale times for client-side navigation. Note that `use cache` still provides value beyond server-side caching: it informs Next.js what can be prefetched and defines stale times for client-side navigation.
The `'use cache: remote'` directive lets you declaratively specify that a cached output should be stored in a **remote cache** instead of in-memory. While this gives you more durable caching for specific operations, it comes with tradeoffs: infrastructure cost and network latency during cache lookups. The `'use cache: remote'` directive lets you declaratively specify that a cached output should be stored in a remote cache instead of in-memory, providing durable caching shared across all server instances. This comes with tradeoffs: infrastructure cost and network latency during cache lookups.
## Usage ## Usage
...@@ -73,7 +73,7 @@ Compelling scenarios for `'use cache: remote'`: ...@@ -73,7 +73,7 @@ Compelling scenarios for `'use cache: remote'`:
In these cases, the cost and latency of remote caching is justified by avoiding worse outcomes (rate limit errors, backend overload, high compute bills, or degraded user experience). In these cases, the cost and latency of remote caching is justified by avoiding worse outcomes (rate limit errors, backend overload, high compute bills, or degraded user experience).
For static shell content, `use cache` is usually sufficient. However, if your static pages share data from an upstream that can't handle concurrent revalidation requests (like a rate-limited CMS), `use cache: remote` acts as a shared cache layer in front of that upstream. This is the same pattern as putting a key-value store in front of a database, but declared in your code rather than configured in infrastructure. For static shell content, `use cache` is usually sufficient. If your upstream source can't handle concurrent revalidation requests (like a rate-limited CMS), `use cache: remote` acts as a shared cache layer. This is the same pattern as putting a key-value store in front of a database, but declared in code.
### How `use cache: remote` differs from `use cache` and `use cache: private` ### How `use cache: remote` differs from `use cache` and `use cache: private`
...@@ -90,9 +90,13 @@ Next.js provides three caching directives, each designed for different use cases ...@@ -90,9 +90,13 @@ Next.js provides three caching directives, each designed for different use cases
### Caching with runtime data ### Caching with runtime data
Both `use cache` and `'use cache: remote'` directives can't access runtime data like cookies or search params directly, since this data isn't available when computing the cache. However, you can extract values from these APIs and pass them as arguments to cached functions. See [with runtime data](/docs/app/getting-started/cache-components#with-runtime-data) for this pattern. Both `use cache` and `'use cache: remote'` can't access runtime values like cookies or search params directly. You can extract these values and pass them as arguments to cached functions. See [with runtime data](/docs/app/getting-started/cache-components#with-runtime-data) for this pattern.
In general, but most importantly for `'use cache: remote'`, be thoughtful about which values you include in cache keys. Each unique value creates a separate cache entry, reducing cache utilization. Consider this example with search filters: > **Good to know**: `use cache` stores entries in-memory. In serverless environments, memory is not shared between instances and is typically destroyed after serving a request, leading to frequent cache misses for runtime caching.
### Cache key considerations
Be thoughtful about which values you include in cache keys. Each unique value creates a separate cache entry, reducing cache utilization. Consider this example with search filters:
```tsx filename="app/products/[category]/page.tsx" ```tsx filename="app/products/[category]/page.tsx"
import { Suspense } from 'react' import { Suspense } from 'react'
......
...@@ -57,7 +57,7 @@ export async function fetchUsers() { ...@@ -57,7 +57,7 @@ export async function fetchUsers() {
Then you can import the `fetchUsers` Server Function into a Client Component and execute it on the client-side. Then you can import the `fetchUsers` Server Function into a Client Component and execute it on the client-side.
```tsx filename="app/components/my-button.tsx" highlight={1,2,8} switcher ```tsx filename="app/components/my-button.tsx" highlight={1,2,5} switcher
'use client' 'use client'
import { fetchUsers } from '../actions' import { fetchUsers } from '../actions'
...@@ -66,7 +66,7 @@ export default function MyButton() { ...@@ -66,7 +66,7 @@ export default function MyButton() {
} }
``` ```
```jsx filename="app/components/my-button.js" highlight={1,2,8} switcher ```jsx filename="app/components/my-button.js" highlight={1,2,5} switcher
'use client' 'use client'
import { fetchUsers } from '../actions' import { fetchUsers } from '../actions'
......
...@@ -19,7 +19,7 @@ Sitemap: https://acme.com/sitemap.xml ...@@ -19,7 +19,7 @@ Sitemap: https://acme.com/sitemap.xml
Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object). Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object).
> **Good to know**: `robots.js` is a special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option. > **Good to know**: `robots.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/guides/caching#dynamic-apis) or [dynamic config](/docs/app/guides/caching#segment-config-options) option.
```ts filename="app/robots.ts" switcher ```ts filename="app/robots.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
...@@ -61,7 +61,7 @@ Sitemap: https://acme.com/sitemap.xml ...@@ -61,7 +61,7 @@ Sitemap: https://acme.com/sitemap.xml
### Customizing specific user agents ### Customizing specific user agents
You can customise how individual search engine bots crawl your site by passing an array of user agents to the `rules` property. For example: You can customize how individual search engine bots crawl your site by passing an array of user agents to the `rules` property. For example:
```ts filename="app/robots.ts" switcher ```ts filename="app/robots.ts" switcher
import type { MetadataRoute } from 'next' import type { MetadataRoute } from 'next'
......
...@@ -43,7 +43,7 @@ Dynamic Segments are passed as the `params` prop to [`layout`](/docs/app/api-ref ...@@ -43,7 +43,7 @@ Dynamic Segments are passed as the `params` prop to [`layout`](/docs/app/api-ref
### In Client Components ### In Client Components
In a Client Component **page**, dynamic segments from props can be accessed using the [`use`](https://react.dev/reference/react/use) hook. In a Client Component **page**, dynamic segments from props can be accessed using the [`use`](https://react.dev/reference/react/use) API.
```tsx filename="app/blog/[slug]/page.tsx" switcher ```tsx filename="app/blog/[slug]/page.tsx" switcher
'use client' 'use client'
......
...@@ -15,7 +15,7 @@ To use it, place the file in the **root** of your application or inside a [`src` ...@@ -15,7 +15,7 @@ To use it, place the file in the **root** of your application or inside a [`src`
### `register` (optional) ### `register` (optional)
The file exports a `register` function that is called **once** when a new Next.js server instance is initiated. `register` can be an async function. The file exports a `register` function that is called **once** when a new Next.js server instance is initiated, and must complete before the server is ready to handle requests. `register` can be an async function.
```ts filename="instrumentation.ts" switcher ```ts filename="instrumentation.ts" switcher
import { registerOTel } from '@vercel/otel' import { registerOTel } from '@vercel/otel'
......
...@@ -116,7 +116,7 @@ export const config = { ...@@ -116,7 +116,7 @@ export const config = {
} }
``` ```
Configured matchers: The `source` path patterns:
1. MUST start with `/` 1. MUST start with `/`
2. Can include named parameters: `/about/:path` matches `/about/a` and `/about/b` but not `/about/a/c` 2. Can include named parameters: `/about/:path` matches `/about/a` and `/about/b` but not `/about/a/c`
......
...@@ -59,9 +59,13 @@ export default function Layout({ children }) { ...@@ -59,9 +59,13 @@ export default function Layout({ children }) {
### With request APIs ### With request APIs
You can use request APIs such as [`cookies`](/docs/app/api-reference/functions/cookies) and [`headers`](/docs/app/api-reference/functions/headers) inside `after` in [Server Functions](/docs/app/getting-started/updating-data) and [Route Handlers](/docs/app/api-reference/file-conventions/route). This is useful for logging activity after a mutation. For example: Whether you can use request APIs like [`cookies`](/docs/app/api-reference/functions/cookies) and [`headers`](/docs/app/api-reference/functions/headers) inside `after` depends on where `after` is called from.
```ts filename="app/api/route.ts" highlight={2,7-9} switcher #### In Route Handlers and Server Functions
You can call `cookies` and `headers` directly inside the `after` callback when used in [Route Handlers](/docs/app/api-reference/file-conventions/route) and [Server Functions](/docs/app/getting-started/updating-data). This is useful for logging activity after a mutation or API request. For example:
```ts filename="app/api/route.ts" highlight={2,10-16} switcher
import { after } from 'next/server' import { after } from 'next/server'
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils' import { logUserAction } from '@/app/utils'
...@@ -72,9 +76,9 @@ export async function POST(request: Request) { ...@@ -72,9 +76,9 @@ export async function POST(request: Request) {
// Log user activity for analytics // Log user activity for analytics
after(async () => { after(async () => {
const userAgent = (await headers().get('user-agent')) || 'unknown' const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie = const sessionCookie =
(await cookies().get('session-id'))?.value || 'anonymous' (await cookies()).get('session-id')?.value || 'anonymous'
logUserAction({ sessionCookie, userAgent }) logUserAction({ sessionCookie, userAgent })
}) })
...@@ -86,7 +90,7 @@ export async function POST(request: Request) { ...@@ -86,7 +90,7 @@ export async function POST(request: Request) {
} }
``` ```
```js filename="app/api/route.js" highlight={2,7-9} switcher ```js filename="app/api/route.js" highlight={2,10-16} switcher
import { after } from 'next/server' import { after } from 'next/server'
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils' import { logUserAction } from '@/app/utils'
...@@ -97,9 +101,9 @@ export async function POST(request) { ...@@ -97,9 +101,9 @@ export async function POST(request) {
// Log user activity for analytics // Log user activity for analytics
after(async () => { after(async () => {
const userAgent = (await headers().get('user-agent')) || 'unknown' const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie = const sessionCookie =
(await cookies().get('session-id'))?.value || 'anonymous' (await cookies()).get('session-id')?.value || 'anonymous'
logUserAction({ sessionCookie, userAgent }) logUserAction({ sessionCookie, userAgent })
}) })
...@@ -111,7 +115,123 @@ export async function POST(request) { ...@@ -111,7 +115,123 @@ export async function POST(request) {
} }
``` ```
However, you cannot use these request APIs inside `after` in [Server Components](/docs/app/getting-started/server-and-client-components). This is because Next.js needs to know which part of the tree access the request APIs to support [Cache Components](/docs/app/getting-started/cache-components), but `after` runs after React's rendering lifecycle. #### In Server Components (pages and layouts)
[Server Components](/docs/app/getting-started/server-and-client-components) (including pages, layouts, and `generateMetadata`) **cannot** use `cookies`, `headers`, or other [Dynamic APIs](/docs/app/guides/caching#dynamic-rendering) inside `after`. This is because Next.js needs to know which part of the component tree accesses request data to support [Partial Prerendering](/docs/app/glossary#partial-prerendering-ppr) and [Cache Components](/docs/app/getting-started/cache-components), but `after` runs after React's rendering lifecycle.
If you need request data inside an `after` callback in a Server Component, read it beforehand and pass the values in:
```tsx filename="app/page.tsx" highlight={8-10,12} switcher
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
export default async function Page() {
// Read request data before `after` — this is allowed
// These calls will be read during the component's rendering lifecycle
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie =
(await cookies()).get('session-id')?.value || 'anonymous'
after(() => {
// Use the values read above
logUserAction({ sessionCookie, userAgent })
})
return <h1>My Page</h1>
}
```
```jsx filename="app/page.jsx" highlight={8-10,12} switcher
import { after } from 'next/server'
import { cookies, headers } from 'next/headers'
import { logUserAction } from '@/app/utils'
export default async function Page() {
// Read request data before `after` — this is allowed
// These calls will be read during the component's rendering lifecycle
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie =
(await cookies()).get('session-id')?.value || 'anonymous'
after(() => {
// Use the values read above
logUserAction({ sessionCookie, userAgent })
})
return <h1>My Page</h1>
}
```
Calling `cookies()` or `headers()` inside the `after` callback in a Server Component will throw a runtime error.
#### With Cache Components
When using [Cache Components](/docs/app/getting-started/cache-components), components that access request data like `cookies` or `headers` must be wrapped in [`<Suspense>`](https://react.dev/reference/react/Suspense) so the rest of the page can be prerendered into a static shell.
You can combine this pattern with `after` by reading request data in a dynamic component and passing it into `after`:
```tsx filename="app/page.tsx" highlight={18-19,22-24} switcher
import { Suspense } from 'react'
import { after } from 'next/server'
import { cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'
export default function Page() {
return (
<>
<h1>Part of the static shell</h1>
<Suspense fallback={<p>Loading...</p>}>
<DynamicContent />
</Suspense>
</>
)
}
async function DynamicContent() {
const sessionCookie =
(await cookies()).get('session-id')?.value || 'anonymous'
// Schedule work after the response is sent
after(() => {
logUserAction({ sessionCookie })
})
return <p>Your session: {sessionCookie}</p>
}
```
```jsx filename="app/page.jsx" highlight={18-19,22-24} switcher
import { Suspense } from 'react'
import { after } from 'next/server'
import { cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'
export default function Page() {
return (
<>
<h1>Part of the static shell</h1>
<Suspense fallback={<p>Loading...</p>}>
<DynamicContent />
</Suspense>
</>
)
}
async function DynamicContent() {
const sessionCookie =
(await cookies()).get('session-id')?.value || 'anonymous'
// Schedule work after the response is sent
after(() => {
logUserAction({ sessionCookie })
})
return <p>Your session: {sessionCookie}</p>
}
```
In this example, `<h1>` and the `<Suspense>` fallback are included in the static shell. `DynamicContent` reads the cookie during rendering and passes it into `after` via closure. Since `cookies()` is called _outside_ the `after` callback (during the component's render), this works correctly.
## Platform Support ## Platform Support
...@@ -177,7 +297,7 @@ const handler = (req, res) => { ...@@ -177,7 +297,7 @@ const handler = (req, res) => {
## Version History ## Version History
| Version History | Description | | Version | Changes |
| --------------- | ---------------------------- | | ------------ | ---------------------------- |
| `v15.1.0` | `after` became stable. | | `v15.1.0` | `after` became stable. |
| `v15.0.0-rc` | `unstable_after` introduced. | | `v15.0.0-rc` | `unstable_after` introduced. |
...@@ -93,6 +93,8 @@ Cache profiles control caching behavior through three timing properties: ...@@ -93,6 +93,8 @@ Cache profiles control caching behavior through three timing properties:
During this time, the client-side router displays cached content immediately without any network request. After this period expires, the router must check with the server on the next navigation or request. This provides instant page loads from the client cache, but data may be outdated. During this time, the client-side router displays cached content immediately without any network request. After this period expires, the router must check with the server on the next navigation or request. This provides instant page loads from the client cache, but data may be outdated.
- If omitted, defaults to the `default` profile's `stale` value (5 minutes, see [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes))
```tsx ```tsx
cacheLife({ stale: 300 }) // 5 minutes cacheLife({ stale: 300 }) // 5 minutes
``` ```
...@@ -106,6 +108,7 @@ How often the server regenerates cached content in the background. ...@@ -106,6 +108,7 @@ How often the server regenerates cached content in the background.
2. Regenerates content in the background 2. Regenerates content in the background
3. Updates the cache with fresh content 3. Updates the cache with fresh content
- Similar to [Incremental Static Regeneration (ISR)](/docs/app/guides/incremental-static-regeneration) - Similar to [Incremental Static Regeneration (ISR)](/docs/app/guides/incremental-static-regeneration)
- If omitted, defaults to the `default` profile's `revalidate` value (15 minutes)
```tsx ```tsx
cacheLife({ revalidate: 900 }) // 15 minutes cacheLife({ revalidate: 900 }) // 15 minutes
...@@ -117,6 +120,7 @@ Maximum time before the server must regenerate cached content. ...@@ -117,6 +120,7 @@ Maximum time before the server must regenerate cached content.
- After this period with no traffic, the server regenerates content synchronously on the next request - After this period with no traffic, the server regenerates content synchronously on the next request
- When you set both `revalidate` and `expire`, `expire` must be longer than `revalidate`. Next.js validates this and raises an error for invalid configurations. - When you set both `revalidate` and `expire`, `expire` must be longer than `revalidate`. Next.js validates this and raises an error for invalid configurations.
- If omitted, defaults to the `default` profile's `expire` value (never expires)
```tsx ```tsx
cacheLife({ expire: 3600 }) // 1 hour cacheLife({ expire: 3600 }) // 1 hour
...@@ -128,7 +132,7 @@ If you don't specify a profile, Next.js uses the `default` profile. We recommend ...@@ -128,7 +132,7 @@ If you don't specify a profile, Next.js uses the `default` profile. We recommend
| **Profile** | **Use Case** | `stale` | `revalidate` | `expire` | | **Profile** | **Use Case** | `stale` | `revalidate` | `expire` |
| ----------- | -------------------------------------- | ---------- | ------------ | -------- | | ----------- | -------------------------------------- | ---------- | ------------ | -------- |
| `default` | Standard content | 5 minutes | 15 minutes | 1 year | | `default` | Standard content | 5 minutes | 15 minutes | never |
| `seconds` | Real-time data | 30 seconds | 1 second | 1 minute | | `seconds` | Real-time data | 30 seconds | 1 second | 1 minute |
| `minutes` | Frequently updated content | 5 minutes | 1 minute | 1 hour | | `minutes` | Frequently updated content | 5 minutes | 1 minute | 1 hour |
| `hours` | Content updated multiple times per day | 5 minutes | 1 hour | 1 day | | `hours` | Content updated multiple times per day | 5 minutes | 1 hour | 1 day |
...@@ -174,6 +178,8 @@ module.exports = nextConfig ...@@ -174,6 +178,8 @@ module.exports = nextConfig
The example above caches for 14 days, checks for updates daily, and expires the cache after 14 days. You can then reference this profile throughout your application by its name: The example above caches for 14 days, checks for updates daily, and expires the cache after 14 days. You can then reference this profile throughout your application by its name:
> **Good to know**: Any omitted properties in a custom profile inherit from the `default` profile. This also applies to inline profile objects passed directly to `cacheLife()`.
```tsx filename="app/page.tsx" highlight={5} ```tsx filename="app/page.tsx" highlight={5}
'use cache' 'use cache'
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
...@@ -456,7 +462,7 @@ This pattern is useful when different outcomes need different cache durations, f ...@@ -456,7 +462,7 @@ This pattern is useful when different outcomes need different cache durations, f
If you want to calculate cache lifetime at runtime, for example by reading it from the fetched data, use an [inline cache profile](#inline-cache-profiles) object: If you want to calculate cache lifetime at runtime, for example by reading it from the fetched data, use an [inline cache profile](#inline-cache-profiles) object:
```tsx filename="lib/posts.ts" highlight={15,16,17} ```tsx filename="lib/posts.ts" highlight={15,16,17,18}
import { cacheLife, cacheTag } from 'next/cache' import { cacheLife, cacheTag } from 'next/cache'
async function getPostContent(slug: string) { async function getPostContent(slug: string) {
...@@ -473,6 +479,7 @@ async function getPostContent(slug: string) { ...@@ -473,6 +479,7 @@ async function getPostContent(slug: string) {
// Use cache timing from CMS data directly as an object // Use cache timing from CMS data directly as an object
cacheLife({ cacheLife({
// Ensure post.revalidateSeconds is a number in seconds // Ensure post.revalidateSeconds is a number in seconds
// stale and expire inherit from 'default' profile
revalidate: post.revalidateSeconds ?? 3600, revalidate: post.revalidateSeconds ?? 3600,
}) })
......
...@@ -1227,7 +1227,7 @@ export async function generateMetadata() { ...@@ -1227,7 +1227,7 @@ export async function generateMetadata() {
If metadata genuinely requires runtime data, add a dynamic marker component to your page: If metadata genuinely requires runtime data, add a dynamic marker component to your page:
```tsx filename="app/page.tsx" highlight={11-14,19,28} ```tsx filename="app/page.tsx" highlight={11-14,19,31}
import { Suspense } from 'react' import { Suspense } from 'react'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
......
...@@ -29,6 +29,16 @@ permanentRedirect(path, type) ...@@ -29,6 +29,16 @@ permanentRedirect(path, type)
By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/getting-started/updating-data) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/getting-started/updating-data) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
The `RedirectType` object contains the available options for the `type` parameter.
```ts
import { permanentRedirect, RedirectType } from 'next/navigation'
permanentRedirect('/redirect-to', RedirectType.replace)
// or
permanentRedirect('/redirect-to', RedirectType.push)
```
The `type` parameter has no effect when used in Server Components. The `type` parameter has no effect when used in Server Components.
## Returns ## Returns
......
...@@ -3,7 +3,9 @@ title: unstable_cache ...@@ -3,7 +3,9 @@ title: unstable_cache
description: API Reference for the unstable_cache function. description: API Reference for the unstable_cache function.
--- ---
> **Warning:** This API will be replaced by [`use cache`](/docs/app/api-reference/directives/use-cache) when it reaches stability. > **Note:**
> This API has been replaced by [`use cache`](/docs/app/api-reference/directives/use-cache) in Next.js 16.
> We recommend opting into [Cache Components](/docs/app/getting-started/cache-components) and replacing `unstable_cache` with the `use cache` directive.
`unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests. `unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
......
...@@ -35,6 +35,7 @@ export default function ExampleClientComponent() { ...@@ -35,6 +35,7 @@ export default function ExampleClientComponent() {
> >
> - Since `useSelectedLayoutSegment` is a [Client Component](/docs/app/getting-started/server-and-client-components) hook, and Layouts are [Server Components](/docs/app/getting-started/server-and-client-components) by default, `useSelectedLayoutSegment` is usually called via a Client Component that is imported into a Layout. > - Since `useSelectedLayoutSegment` is a [Client Component](/docs/app/getting-started/server-and-client-components) hook, and Layouts are [Server Components](/docs/app/getting-started/server-and-client-components) by default, `useSelectedLayoutSegment` is usually called via a Client Component that is imported into a Layout.
> - `useSelectedLayoutSegment` only returns the segment one level down. To return all active segments, see [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) > - `useSelectedLayoutSegment` only returns the segment one level down. To return all active segments, see [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments)
> - For [catch-all](/docs/app/api-reference/file-conventions/dynamic-routes#catch-all-segments) routes, the matched segments are returned as a single joined string. For example, given `app/blog/[...slug]/page.js`, calling from `app/blog/layout.js` when visiting `/blog/a/b/c` returns `'a/b/c'`.
## Parameters ## Parameters
...@@ -59,6 +60,12 @@ For example, given the Layouts and URLs below, the returned segment would be: ...@@ -59,6 +60,12 @@ For example, given the Layouts and URLs below, the returned segment would be:
| `app/dashboard/layout.js` | `/dashboard/analytics` | `'analytics'` | | `app/dashboard/layout.js` | `/dashboard/analytics` | `'analytics'` |
| `app/dashboard/layout.js` | `/dashboard/analytics/monthly` | `'analytics'` | | `app/dashboard/layout.js` | `/dashboard/analytics/monthly` | `'analytics'` |
For catch-all routes (`[...slug]`), the returned segment contains all matched path segments joined as a single string:
| Layout | Visited URL | Returned Segment |
| -------------------- | ------------- | ---------------- |
| `app/blog/layout.js` | `/blog/a/b/c` | `'a/b/c'` |
## Examples ## Examples
### Creating an active link component ### Creating an active link component
......
...@@ -47,6 +47,7 @@ export default function ExampleClientComponent() { ...@@ -47,6 +47,7 @@ export default function ExampleClientComponent() {
> >
> - Since `useSelectedLayoutSegments` is a [Client Component](/docs/app/getting-started/server-and-client-components) hook, and Layouts are [Server Components](/docs/app/getting-started/server-and-client-components) by default, `useSelectedLayoutSegments` is usually called via a Client Component that is imported into a Layout. > - Since `useSelectedLayoutSegments` is a [Client Component](/docs/app/getting-started/server-and-client-components) hook, and Layouts are [Server Components](/docs/app/getting-started/server-and-client-components) by default, `useSelectedLayoutSegments` is usually called via a Client Component that is imported into a Layout.
> - The returned segments include [Route Groups](/docs/app/api-reference/file-conventions/route-groups), which you might not want to be included in your UI. You can use the [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) array method to remove items that start with a bracket. > - The returned segments include [Route Groups](/docs/app/api-reference/file-conventions/route-groups), which you might not want to be included in your UI. You can use the [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) array method to remove items that start with a bracket.
> - For [catch-all](/docs/app/api-reference/file-conventions/dynamic-routes#catch-all-segments) routes, the matched segments are returned as a single joined string within the array. For example, given `app/blog/[...slug]/page.js`, calling from `app/layout.js` when visiting `/blog/a/b/c` returns `['blog', 'a/b/c']`, not `['blog', 'a', 'b', 'c']`.
## Parameters ## Parameters
...@@ -70,6 +71,13 @@ For example, given the Layouts and URLs below, the returned segments would be: ...@@ -70,6 +71,13 @@ For example, given the Layouts and URLs below, the returned segments would be:
| `app/dashboard/layout.js` | `/dashboard` | `[]` | | `app/dashboard/layout.js` | `/dashboard` | `[]` |
| `app/dashboard/layout.js` | `/dashboard/settings` | `['settings']` | | `app/dashboard/layout.js` | `/dashboard/settings` | `['settings']` |
For catch-all routes (`[...slug]`), all matched path segments are returned as a single joined string within the array:
| Layout | Visited URL | Returned Segments |
| -------------------- | ------------- | ------------------- |
| `app/layout.js` | `/blog/a/b/c` | `['blog', 'a/b/c']` |
| `app/blog/layout.js` | `/blog/a/b/c` | `['a/b/c']` |
## Version History ## Version History
| Version | Changes | | Version | Changes |
......
---
title: deploymentId
description: Configure a deployment identifier used for version skew protection and cache busting.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
The `deploymentId` option allows you to set an identifier for your deployment. This identifier is used for [version skew](/docs/app/guides/self-hosting#version-skew) protection and cache busting during rolling deployments.
```js filename="next.config.js"
module.exports = {
deploymentId: 'my-deployment-id',
}
```
You can also set the deployment ID using the `NEXT_DEPLOYMENT_ID` environment variable:
```bash
NEXT_DEPLOYMENT_ID=my-deployment-id next build
```
> **Good to know:** If both are set, the `deploymentId` value in `next.config.js` takes precedence over the `NEXT_DEPLOYMENT_ID` environment variable.
## How it works
When a `deploymentId` is configured, Next.js:
1. Appends `?dpl=<deploymentId>` to static asset URLs (JavaScript, CSS, images)
2. Adds an `x-deployment-id` header to client-side navigation requests
3. Adds an `x-nextjs-deployment-id` header to navigation responses
4. Injects a `data-dpl-id` attribute on the `<html>` element
When the client detects a mismatch between its deployment ID and the server's (via the response header), it triggers a hard navigation (full page reload) instead of a client-side navigation. This ensures users always receive assets <AppOnly>and Server Functions</AppOnly> from a consistent deployment version.
> **Good to know:** Next.js does not read the `?dpl=` query parameter on incoming requests. The query parameter is for cache busting (ensuring browsers and CDNs fetch fresh assets), not for routing. If you need version-aware routing, consult your hosting provider or CDN's documentation for implementing deployment-based routing.
## Use cases
### Rolling deployments
During a rolling deployment, some server instances may be running the new version while others are still running the old version. Without a deployment ID, users might receive a mix of old and new assets, causing errors.
Setting a consistent `deploymentId` per deployment ensures:
<AppOnly>
- Clients always request assets from a matching deployment version
- Mismatches trigger a full reload to fetch the correct assets
- Server Functions work correctly across deployment boundaries
</AppOnly>
<PagesOnly>
- Clients always request assets from a matching deployment version
- Mismatches trigger a full reload to fetch the correct assets
</PagesOnly>
### Multi-server environments
When running multiple instances of your Next.js application behind a load balancer, all instances for the same deployment should use the same `deploymentId`.
```js filename="next.config.js"
module.exports = {
deploymentId: process.env.DEPLOYMENT_VERSION || process.env.GIT_SHA,
}
```
## Version History
| Version | Changes |
| ---------- | ----------------------------------------------------- |
| `v14.1.4` | `deploymentId` stabilized as top-level config option. |
| `v13.4.10` | `experimental.deploymentId` introduced. |
## Related
- [Self-Hosting - Version Skew](/docs/app/guides/self-hosting#version-skew)
- [generateBuildId](/docs/app/api-reference/config/next-config-js/generateBuildId)
...@@ -33,28 +33,34 @@ module.exports = nextConfig ...@@ -33,28 +33,34 @@ module.exports = nextConfig
## Trade-Offs ## Trade-Offs
### When to Use Inline CSS - **Enable** if you use atomic CSS (like Tailwind) and want to optimize first-load performance for new visitors
- **Skip** if returning visitors are common and you want them to benefit from cached stylesheets
Inlining CSS can be beneficial in several scenarios: ### When Inline CSS Helps
- **First-Time Visitors**: Since CSS files are render-blocking resources, inlining eliminates the initial download delay that first-time visitors experience, improving page load performance. Normally, the browser must download HTML, parse it, discover CSS `<link>` tags, then request stylesheets before it can render. Inlining [eliminates this request waterfall](https://web.dev/learn/performance/optimize-resource-loading#inline_critical_css), so that styles arrive with the HTML, so the browser can render immediately.
- **Performance Metrics**: By removing the additional network requests for CSS files, inlining can significantly improve key metrics like First Contentful Paint (FCP) and Largest Contentful Paint (LCP). This benefit is strongest with:
- **Slow Connections**: For users on slower networks where each request adds considerable latency, inlining CSS can provide a noticeable performance boost by reducing network roundtrips. - **First-time visitors**: Since CSS files are render-blocking, inlining eliminates the initial download delay that first-time visitors experience. Returning visitors with cached stylesheets won't see this benefit.
- **Atomic CSS Bundles (e.g., Tailwind)**: With utility-first frameworks like Tailwind CSS, the size of the styles required for a page is often O(1) relative to the complexity of the design. This makes inlining a compelling choice because the entire set of styles for the current page is lightweight and doesn’t grow with the page size. Inlining Tailwind styles ensures minimal payload and eliminates the need for additional network requests, which can further enhance performance. - **Performance metrics**: By removing additional network requests for CSS files, inlining can significantly improve [First Contentful Paint (FCP)](https://web.dev/articles/fcp) and [Largest Contentful Paint (LCP)](https://web.dev/articles/lcp).
### When Not to Use Inline CSS - **Slow connections**: For users on high-latency networks, each additional request adds delay. Inlining reduces round trips, which matters most when connections are slow.
While inlining CSS offers significant benefits for performance, there are scenarios where it may not be the best choice: - **Atomic CSS (Tailwind)**: Utility-first frameworks generate only the classes you use, keeping CSS small. The styles for a page don't grow proportionally with page complexity—they're typically compact regardless of how much UI you build. This makes inlining practical since you get the performance benefit without significantly bloating HTML.
- **Large CSS Bundles**: If your CSS bundle is too large, inlining it may significantly increase the size of the HTML, resulting in slower Time to First Byte (TTFB) and potentially worse performance for users with slow connections. ### When External CSS is Better
- **Dynamic or Page-Specific CSS**: For applications with highly dynamic styles or pages that use different sets of CSS, inlining may lead to redundancy and bloat, as the full CSS for all pages may need to be inlined repeatedly.
- **Browser Caching**: In cases where visitors frequently return to your site, external CSS files allow browsers to cache styles efficiently, reducing data transfer for subsequent visits. Inlining CSS eliminates this benefit. Inlined styles cannot be cached separately from HTML. Every page load re-downloads the same CSS.
Evaluate these trade-offs carefully, and consider combining inlining with other strategies, such as critical CSS extraction or a hybrid approach, for the best results tailored to your site's needs. This trade-off matters most with:
- **Returning visitors**: Users who visit your site repeatedly would benefit from cached external stylesheets. With inlining, they re-download styles on every visit.
- **Large CSS bundles**: External stylesheets cache independently and load efficiently on modern infrastructure. Inlined CSS arrives with every HTML response, increasing [Time to First Byte (TTFB)](https://web.dev/articles/ttfb) and preventing browsers from caching styles separately. This trade-off works for small CSS (atomic frameworks like Tailwind), but adds overhead for larger bundles (component libraries like Bootstrap or Material UI).
- **Many pages sharing styles**: External stylesheets cached on one page speed up navigation to other pages. Inlined styles provide no cross-page caching benefit.
> **Good to know**: > **Good to know**:
> >
......
...@@ -15,10 +15,22 @@ This avoids compiling everything and keeps the performance cost minimal. You may ...@@ -15,10 +15,22 @@ This avoids compiling everything and keeps the performance cost minimal. You may
To use it, install the `babel-plugin-react-compiler`: To use it, install the `babel-plugin-react-compiler`:
```bash filename="Terminal" ```bash package="pnpm"
pnpm add -D babel-plugin-react-compiler
```
```bash package="npm"
npm install -D babel-plugin-react-compiler npm install -D babel-plugin-react-compiler
``` ```
```bash package="yarn"
yarn add -D babel-plugin-react-compiler
```
```bash package="bun"
bun add -D babel-plugin-react-compiler
```
Then, add `reactCompiler` option in `next.config.js`: Then, add `reactCompiler` option in `next.config.js`:
```ts filename="next.config.ts" switcher ```ts filename="next.config.ts" switcher
......
...@@ -408,7 +408,7 @@ module.exports = { ...@@ -408,7 +408,7 @@ module.exports = {
}, },
{ {
// does not add /docs to /without-basePath since basePath: false is set // does not add /docs to /without-basePath since basePath: false is set
// Note: this can not be used for internal rewrites e.g. `destination: '/another'` // Note: this cannot be used for internal rewrites e.g. `destination: '/another'`
source: '/without-basePath', source: '/without-basePath',
destination: 'https://example.com', destination: 'https://example.com',
basePath: false, basePath: false,
......
...@@ -9,10 +9,22 @@ The `create-next-app` CLI allow you to create a new Next.js application using th ...@@ -9,10 +9,22 @@ The `create-next-app` CLI allow you to create a new Next.js application using th
Basic usage: Basic usage:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app [project-name] [options]
```
```bash package="npm"
npx create-next-app@latest [project-name] [options] npx create-next-app@latest [project-name] [options]
``` ```
```bash package="yarn"
yarn create next-app [project-name] [options]
```
```bash package="bun"
bun create next-app [project-name] [options]
```
## Reference ## Reference
The following options are available: The following options are available:
...@@ -53,10 +65,22 @@ The following options are available: ...@@ -53,10 +65,22 @@ The following options are available:
To create a new app using the default template, run the following command in your terminal: To create a new app using the default template, run the following command in your terminal:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app
```
```bash package="npm"
npx create-next-app@latest npx create-next-app@latest
``` ```
```bash package="yarn"
yarn create next-app
```
```bash package="bun"
bun create next-app
```
On installation, you'll see the following prompts: On installation, you'll see the following prompts:
```txt filename="Terminal" ```txt filename="Terminal"
...@@ -96,16 +120,40 @@ Once you've answered the prompts, a new project will be created with your chosen ...@@ -96,16 +120,40 @@ Once you've answered the prompts, a new project will be created with your chosen
To create a new app using an official Next.js example, use the `--example` flag. For example: To create a new app using an official Next.js example, use the `--example` flag. For example:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --example [example-name] [your-project-name]
```
```bash package="npm"
npx create-next-app@latest --example [example-name] [your-project-name] npx create-next-app@latest --example [example-name] [your-project-name]
``` ```
```bash package="yarn"
yarn create next-app --example [example-name] [your-project-name]
```
```bash package="bun"
bun create next-app --example [example-name] [your-project-name]
```
You can view a list of all available examples along with setup instructions in the [Next.js repository](https://github.com/vercel/next.js/tree/canary/examples). You can view a list of all available examples along with setup instructions in the [Next.js repository](https://github.com/vercel/next.js/tree/canary/examples).
### With any public GitHub example ### With any public GitHub example
To create a new app using any public GitHub example, use the `--example` option with the GitHub repo's URL. For example: To create a new app using any public GitHub example, use the `--example` option with the GitHub repo's URL. For example:
```bash filename="Terminal" ```bash package="pnpm"
pnpm create next-app --example "https://github.com/.../" [your-project-name]
```
```bash package="npm"
npx create-next-app@latest --example "https://github.com/.../" [your-project-name] npx create-next-app@latest --example "https://github.com/.../" [your-project-name]
``` ```
```bash package="yarn"
yarn create next-app --example "https://github.com/.../" [your-project-name]
```
```bash package="bun"
bun create next-app --example "https://github.com/.../" [your-project-name]
```
...@@ -9,10 +9,24 @@ The Next.js CLI allows you to develop, build, start your application, and more. ...@@ -9,10 +9,24 @@ The Next.js CLI allows you to develop, build, start your application, and more.
Basic usage: Basic usage:
```bash filename="Terminal" ```bash package="pnpm"
pnpm next [command] [options]
```
```bash package="npm"
npx next [command] [options] npx next [command] [options]
``` ```
```bash package="yarn"
yarn next [command] [options]
```
```bash package="bun"
bunx next [command] [options]
```
> **Good to know**: With `npm run`, use `--` before CLI flags so npm forwards them to `next`. This is not required for `pnpm`, `yarn`, or `bun`.
## Reference ## Reference
The following options are available: The following options are available:
...@@ -205,10 +219,22 @@ The following options are available for the `next upgrade` command: ...@@ -205,10 +219,22 @@ The following options are available for the `next upgrade` command:
`next experimental-analyze` analyzes your application's bundle output using [Turbopack](/docs/app/api-reference/turbopack). This command helps you understand the size and composition of your bundles, including JavaScript, CSS, and other assets. This command doesn't produce an application build. `next experimental-analyze` analyzes your application's bundle output using [Turbopack](/docs/app/api-reference/turbopack). This command helps you understand the size and composition of your bundles, including JavaScript, CSS, and other assets. This command doesn't produce an application build.
```bash filename="Terminal" ```bash package="pnpm"
pnpm next experimental-analyze
```
```bash package="npm"
npx next experimental-analyze npx next experimental-analyze
``` ```
```bash package="yarn"
yarn next experimental-analyze
```
```bash package="bun"
bunx next experimental-analyze
```
By default, the command starts a local server after analysis completes, allowing you to explore your bundle composition in the browser. The analyzer lets you: By default, the command starts a local server after analysis completes, allowing you to explore your bundle composition in the browser. The analyzer lets you:
- Filter bundles by route and switch between client and server views - Filter bundles by route and switch between client and server views
......
...@@ -158,7 +158,7 @@ The following JavaScript language features are disabled, and **will not work:** ...@@ -158,7 +158,7 @@ The following JavaScript language features are disabled, and **will not work:**
| [`WebAssembly.compile`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile) | Compiles a WebAssembly module from a buffer source | | [`WebAssembly.compile`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile) | Compiles a WebAssembly module from a buffer source |
| [`WebAssembly.instantiate`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) | Compiles and instantiates a WebAssembly module from a buffer source | | [`WebAssembly.instantiate`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) | Compiles and instantiates a WebAssembly module from a buffer source |
In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by treeshaking. In rare cases, your code could contain (or import) some dynamic code evaluation statements which _cannot be reached at runtime_ and which cannot be removed by treeshaking.
You can relax the check to allow specific files with your Proxy configuration: You can relax the check to allow specific files with your Proxy configuration:
```javascript filename="proxy.ts" ```javascript filename="proxy.ts"
......
...@@ -270,3 +270,9 @@ A special React directive that marks the boundary between server and client code ...@@ -270,3 +270,9 @@ A special React directive that marks the boundary between server and client code
## `"use server"` Directive ## `"use server"` Directive
A directive that marks a function as a [Server Function](#server-function) that can be called from client-side code. It can be placed at the top of a file to indicate that all exports in the file are Server Functions, or inline at the top of a function to mark that specific function. Learn more in the [`"use server"` reference](/docs/app/api-reference/directives/use-server). A directive that marks a function as a [Server Function](#server-function) that can be called from client-side code. It can be placed at the top of a file to indicate that all exports in the file are Server Functions, or inline at the top of a function to mark that specific function. Learn more in the [`"use server"` reference](/docs/app/api-reference/directives/use-server).
# V
## Version skew
After a new version of your application is deployed, clients that are still active may reference JavaScript, CSS, or data from an older build. This mismatch between client and server versions is called version skew, and it can cause missing assets, Server Action errors, and navigation failures. Next.js uses [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) to detect and handle version skew. Learn more in [Self-Hosting - Version Skew](/docs/app/guides/self-hosting#version-skew).
...@@ -45,9 +45,8 @@ export default function handler(req, res) { ...@@ -45,9 +45,8 @@ export default function handler(req, res) {
> **Good to know**: > **Good to know**:
> >
> - API Routes [do not specify CORS headers](https://developer.mozilla.org/docs/Web/HTTP/CORS), meaning they are **same-origin only** by default. You can customize such behavior by wrapping the request handler with the [CORS request helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors). > - API Routes [do not specify CORS headers](https://developer.mozilla.org/docs/Web/HTTP/CORS), meaning they are **same-origin only** by default. You can customize such behavior by wrapping the request handler with the [CORS request helpers](https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors).
> - API Routes can't be used with [static exports](/docs/pages/guides/static-exports). However, [Route Handlers](/docs/app/api-reference/file-conventions/route) in the App Router can.
- API Routes can't be used with [static exports](/docs/pages/guides/static-exports). However, [Route Handlers](/docs/app/api-reference/file-conventions/route) in the App Router can. > - API Routes will be affected by [`pageExtensions` configuration](/docs/pages/api-reference/config/next-config-js/pageExtensions) in `next.config.js`.
> - API Routes will be affected by [`pageExtensions` configuration](/docs/pages/api-reference/config/next-config-js/pageExtensions) in `next.config.js`.
## Parameters ## Parameters
......
...@@ -466,7 +466,7 @@ The following Image Optimization cloud providers are included: ...@@ -466,7 +466,7 @@ The following Image Optimization cloud providers are included:
If you need a different provider, you can use the [`loader`](#loader) prop with `next/legacy/image`. If you need a different provider, you can use the [`loader`](#loader) prop with `next/legacy/image`.
> Images can not be optimized at build time using [`output: 'export'`](/docs/pages/guides/static-exports), only on-demand. To use `next/legacy/image` with `output: 'export'`, you will need to use a different loader than the default. [Read more in the discussion.](https://github.com/vercel/next.js/discussions/19065) > Images cannot be optimized at build time using [`output: 'export'`](/docs/pages/guides/static-exports), only on-demand. To use `next/legacy/image` with `output: 'export'`, you will need to use a different loader than the default. [Read more in the discussion.](https://github.com/vercel/next.js/discussions/19065)
## Advanced ## Advanced
......
...@@ -446,7 +446,7 @@ const MyComponent = () => { ...@@ -446,7 +446,7 @@ const MyComponent = () => {
} }
``` ```
Will error when converted over to `next/compat/router`, as `null` can not be destructured. Instead, developers will be able to take advantage of new hooks: Will error when converted over to `next/compat/router`, as `null` cannot be destructured. Instead, developers will be able to take advantage of new hooks:
```jsx ```jsx
import { useEffect } from 'react' import { useEffect } from 'react'
......
---
title: deploymentId
description: Configure a deployment identifier used for version skew protection and cache busting.
source: app/api-reference/config/next-config-js/deploymentId
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
...@@ -209,11 +209,33 @@ Always run examples locally before committing them. This will ensure that the co ...@@ -209,11 +209,33 @@ Always run examples locally before committing them. This will ensure that the co
### Language and Filename ### Language and Filename
Code blocks should have a header that includes the language and the `filename`. Add a `filename` prop to render a special Terminal icon that helps orientate users where to input the command. For example: Code blocks should have a header that includes the language and the `filename`. For example:
````mdx filename="code-example.mdx" ````mdx filename="code-example.mdx"
```bash filename="Terminal" ```tsx filename="app/page.tsx"
npx create-next-app export default function Page() {
return <h1>Hello, Next.js!</h1>
}
```
````
For CLI commands, use the `package` prop to show the command for each package manager:
````mdx filename="code-example.mdx"
```bash package="pnpm"
pnpm create next-app
```
```bash package="npm"
npx create-next-app@latest
```
```bash package="yarn"
yarn create next-app
```
```bash package="bun"
bun create next-app
``` ```
```` ````
......
...@@ -10,7 +10,9 @@ When self-hosting your Next.js application across multiple servers, each server ...@@ -10,7 +10,9 @@ When self-hosting your Next.js application across multiple servers, each server
## Possible Ways to Fix It ## Possible Ways to Fix It
To mitigate this, you can overwrite the encryption key using the `process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. Specifying this variable ensures that your encryption keys are persistent across builds, and all server instances use the same key. This variable **must** be AES-GCM encrypted. To mitigate this, you can overwrite the encryption key using the `process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY` environment variable. Specifying this variable ensures that your encryption keys are persistent across builds, and all server instances use the same key.
The key must be a base64-encoded value with a valid AES key length (16, 24, or 32 bytes). Set this variable at **build time**—the key is embedded in the build output and used automatically at runtime.
If you are deploying your Next.js application to Vercel, you can use the feature [Skew Protection](https://vercel.com/docs/deployments/skew-protection) to ensure assets and functions from the previous version are still available, even after a new version is deployed. If you are deploying your Next.js application to Vercel, you can use the feature [Skew Protection](https://vercel.com/docs/deployments/skew-protection) to ensure assets and functions from the previous version are still available, even after a new version is deployed.
......
...@@ -22,7 +22,7 @@ async function ClientComponent() { ...@@ -22,7 +22,7 @@ async function ClientComponent() {
1. **Convert to a Server Component**: If possible, convert your Client Component to a Server Component. This allows you to use `async`/`await` directly in your component. 1. **Convert to a Server Component**: If possible, convert your Client Component to a Server Component. This allows you to use `async`/`await` directly in your component.
2. **Remove the `async` keyword**: If you need to keep it as a Client Component, remove the `async` keyword and handle data fetching differently. 2. **Remove the `async` keyword**: If you need to keep it as a Client Component, remove the `async` keyword and handle data fetching differently.
3. **Use React Hooks for data fetching**: Utilize hooks like `useEffect` for client-side data fetching, or use third-party libraries. 3. **Use React Hooks for data fetching**: Utilize hooks like `useEffect` for client-side data fetching, or use third-party libraries.
4. **Leverage the `use` hook with a Context Provider**: Pass promises to child components using context, then resolve them with the `use` hook. 4. **Leverage the `use` API with a Context Provider**: Pass promises to child components using context, then resolve them with the `use` API.
### Recommended: Server-side data fetching ### Recommended: Server-side data fetching
...@@ -44,7 +44,7 @@ export default async function Page() { ...@@ -44,7 +44,7 @@ export default async function Page() {
### Using `use` with Context Provider ### Using `use` with Context Provider
Another pattern to explore is using the React `use` hook with a Context Provider. This allows you to pass Promises to child components and resolve them using the `use` hook . Here's an example: Another pattern to explore is using the React `use` API with a Context Provider. This allows you to pass Promises to child components and resolve them using the `use` API . Here's an example:
First, let's create a separate file for the context provider: First, let's create a separate file for the context provider:
...@@ -110,7 +110,7 @@ export function BlogPosts() { ...@@ -110,7 +110,7 @@ export function BlogPosts() {
} }
``` ```
This pattern allows you to start data fetching early and pass the Promise down to child components, which can then use the `use` hook to access the data when it's ready. This pattern allows you to start data fetching early and pass the Promise down to child components, which can then use the `use` API to access the data when it's ready.
### Client-side data fetching ### Client-side data fetching
......
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# MDX Remote Example
This example shows how a simple blog might be built using the [next-mdx-remote](https://github.com/hashicorp/next-mdx-remote) library, which allows mdx content to be loaded via [`generateStaticParams`](https://nextjs.org/docs/app/api-reference/functions/generate-static-params). The mdx content is loaded from a local folder, but it could be loaded from a database or anywhere else.
## Deploy your own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/mdx-remote&project-name=mdx-remote&repository-name=mdx-remote)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) to bootstrap the example:
```bash
npx create-next-app --example mdx-remote mdx-remote-app
```
```bash
yarn create next-app --example mdx-remote mdx-remote-app
```
```bash
pnpm create next-app --example mdx-remote mdx-remote-app
```
```bash
bunx create-next-app --example mdx-remote mdx-remote-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/app/building-your-application/deploying)).
## Notes
### Conditional custom components
When using `next-mdx-remote`, you can pass custom components to the MDX renderer. However, some pages/MDX files might use components that are used infrequently, or only on a single page. To avoid loading those components on every MDX page, you can use [`next/dynamic`](https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic) to conditionally load them.
```typescript
import dynamic from "next/dynamic";
import Test from "@/components/test";
import { MDXRemote, type MDXRemoteProps } from 'next-mdx-remote/rsc'
const SomeHeavyComponent = dynamic(() => import("../component/SomeHeavyComponent"));
const defaultComponents = { Test };
export function CustomMDX(props: MDXRemoteProps) {
const componentNames = [
/<SomeHeavyComponent/.test(props.source as string) ? "SomeHeavyComponent" : "",
].filter(Boolean);
const components = {
...defaultComponents,
SomeHeavyComponent: componentNames.includes("SomeHeavyComponent")
? SomeHeavyComponent
: () => null,
};
return <MDXRemote {...props} components={components} />;
}
```
import { notFound } from "next/navigation";
import { CustomMDX } from "@/components/mdx";
import { getPosts } from "@/lib/utils";
import styles from "./page.module.css";
import Link from "next/link";
export function generateStaticParams() {
const posts = getPosts();
return posts.map((post) => ({
slug: post.slug,
}));
}
export default async function Blog({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const post = getPosts().find((post) => post.slug === slug);
if (!post) {
notFound();
}
return (
<>
<header>
<nav>
<Link href="/">👈 Go back home</Link>
</nav>
</header>
<main>
<h1 className={styles.postHeader}>{post.metadata.title}</h1>
{post.metadata.description && (
<p className={styles.description}>{post.metadata.description}</p>
)}
<article>
<CustomMDX source={post.content} />
</article>
</main>
</>
);
}
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
html,
body {
font: 100%/1.5 system-ui;
max-width: 100vw;
overflow-x: hidden;
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
max-width: 36rem;
margin: 0 auto;
padding: 1.5rem;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
a {
color: inherit;
text-decoration-thickness: 2px;
}
a:hover {
color: royalblue;
text-decoration-color: currentcolor;
}
p {
margin-bottom: 1.5rem;
}
code {
font-family: Menlo;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
}
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "MDX Remote App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable}`}>
{children}
</body>
</html>
);
}
import Link from "next/link";
import { getPosts } from "@/lib/utils";
export default function Home() {
const posts = getPosts();
return (
<main>
<h1>Home Page</h1>
<p>
Click the link below to navigate to a page generated by{" "}
<code>next-mdx-remote</code>.
</p>
<ul>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/${post.slug}`}>{post.metadata.title}</Link>
</li>
))}
</ul>
</main>
);
}
---
title: Example Post
description: This frontmatter description will appear below the title
---
This is an example post, with with a [link](https://nextjs.org) and a React component:
<Greet name="next-mdx-remote" />
Links are rendered using a custom component passed to `next-mdx-remote`.
Go back [home](/).
---
title: Hello World
---
This is an example post. There's another one [here](/example-post).
.div {
background-color: #111;
border-radius: 0.5em;
color: #fff;
margin-bottom: 1.5em;
padding: 0.5em 0.75em;
}
import styles from "./greet.module.css";
export function Greet({ name = "world" }: { name: string }) {
return <div className={styles.div}>Hello, {name}!</div>;
}
.a {
color: tomato;
text-decoration-color: rgba(0, 0, 0, 0.4);
}
import React from "react";
import Link from "next/link";
import { MDXRemote, type MDXRemoteProps } from "next-mdx-remote/rsc";
import { Greet } from "./greet";
import styles from "./mdx.module.css";
function CustomLink({
href,
children,
...props
}: React.LinkHTMLAttributes<HTMLAnchorElement>) {
if (href?.startsWith("/")) {
return (
<Link href={href} className={styles.a} {...props}>
{children}
</Link>
);
}
if (href?.startsWith("#")) {
return (
<a href={href} className={styles.a} {...props}>
{children}
</a>
);
}
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className={styles.a}
{...props}
>
{children}
</a>
);
}
export function CustomMDX(props: MDXRemoteProps) {
const components = {
a: CustomLink,
Greet: Greet,
};
return (
<MDXRemote
{...props}
components={{ ...components, ...(props.components || {}) }}
/>
);
}
import fs from "node:fs";
import path from "node:path";
type Metadata = {
title: string;
description?: string;
};
function parseFrontmatter(fileContent: string) {
const frontmatterRegex = /---\s*([\s\S]*?)\s*---/;
const content = fileContent.replace(frontmatterRegex, "").trim();
const match = frontmatterRegex.exec(fileContent);
const frontMatterBlock = match![1];
const frontMatterLines = frontMatterBlock.trim().split("\n");
const metadata: Partial<Metadata> = {};
frontMatterLines.forEach((line) => {
const [key, ...valueArr] = line.split(": ");
let value = valueArr.join(": ").trim();
value = value.replace(/^['"](.*)['"]$/, "$1"); // Remove quotes
metadata[key.trim() as keyof Metadata] = value;
});
return { metadata: metadata as Metadata, content: content };
}
function getMDXFiles(dir: fs.PathLike) {
return fs.readdirSync(dir).filter((file) => path.extname(file) === ".mdx");
}
function readMDXFile(filePath: fs.PathOrFileDescriptor) {
const rawContent = fs.readFileSync(filePath, "utf-8");
return parseFrontmatter(rawContent);
}
function getMDXData(dir: fs.PathLike) {
const mdxFiles = getMDXFiles(dir);
return mdxFiles.map((file) => {
const { metadata, content } = readMDXFile(path.join(dir.toString(), file));
const slug = path.basename(file, path.extname(file));
return {
metadata,
slug,
content,
};
});
}
export function getPosts() {
return getMDXData(path.join(process.cwd(), "app", "posts"));
}
{
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"next-mdx-remote": "^5.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"typescript": "^5.7.2"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Contentlayer Example
This example shows how to integrate Contentlayer in Next.js. Learn more about [Contentlayer](https://www.contentlayer.dev/docs).
## Deploy your own
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-contentlayer&project-name=with-contentlayer&repository-name=with-contentlayer)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example with-contentlayer with-contentlayer-app
```
```bash
yarn create next-app --example with-contentlayer with-contentlayer-app
```
```bash
pnpm create next-app --example with-contentlayer with-contentlayer-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import { defineDocumentType, makeSource } from "contentlayer/source-files";
const computedFields = {
slug: {
type: "string",
resolve: (doc) => doc._raw.sourceFileName.replace(/\.md$/, ""),
},
};
export const Post = defineDocumentType(() => ({
name: "Post",
filePathPattern: `**/*.md`,
fields: {
title: { type: "string", required: true },
date: { type: "string", required: true },
},
computedFields,
}));
export default makeSource({
contentDirPath: "posts",
documentTypes: [Post],
});
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"contentlayer/generated": ["./.contentlayer/generated"]
}
},
"include": [".contentlayer/generated"]
}
const { withContentlayer } = require("next-contentlayer");
module.exports = withContentlayer({});
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"contentlayer": "^0.2.4",
"next": "latest",
"next-contentlayer": "^0.3.4",
"react": "18.0.0",
"react-dom": "18.0.0"
}
}
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
import Link from "next/link";
import Head from "next/head";
import { allPosts } from "contentlayer/generated";
import { pick } from "@contentlayer/client";
import utilStyles from "../styles/utils.module.css";
export default function Home({ posts }) {
return (
<>
<Head>
<title>Home</title>
</Head>
<section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
<h2 className={utilStyles.headingLg}>Blog</h2>
<ul className={utilStyles.list}>
{posts.map(({ slug, date, title }) => (
<li className={utilStyles.listItem} key={slug}>
<Link href={`/posts/${slug}`}>{title}</Link>
<br />
<small className={utilStyles.lightText}>{date}</small>
</li>
))}
</ul>
</section>
</>
);
}
export async function getStaticProps() {
const posts = allPosts.map((post) => pick(post, ["title", "date", "slug"]));
return { props: { posts } };
}
import Head from "next/head";
import { allPosts } from "contentlayer/generated";
import utilStyles from "../../styles/utils.module.css";
export default function Post({ post }) {
return (
<>
<Head>
<title>{post.title}</title>
</Head>
<article>
<h1 className={utilStyles.headingXl}>{post.title}</h1>
<div className={utilStyles.lightText}>{post.date}</div>
<div dangerouslySetInnerHTML={{ __html: post.body.html }} />
</article>
</>
);
}
export async function getStaticPaths() {
return {
paths: allPosts.map((p) => ({ params: { id: p.slug } })),
fallback: false,
};
}
export async function getStaticProps({ params }) {
const post = allPosts.find((post) => post.slug === params?.id);
return { props: { post } };
}
---
title: "Two Forms of Pre-rendering"
date: "2020-01-01"
---
Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page.
- **Static Generation** is the pre-rendering method that generates the HTML at **build time**. The pre-rendered HTML is then _reused_ on each request.
- **Server-side Rendering** is the pre-rendering method that generates the HTML on **each request**.
Importantly, Next.js lets you **choose** which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.
---
title: "When to Use Static Generation vs Server-side Rendering"
date: "2020-01-02"
---
We recommend using **Static Generation** (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.
You can use Static Generation for many types of pages, including:
- Marketing pages
- Blog posts
- E-commerce product listings
- Help and documentation
You should ask yourself: "Can I pre-render this page **ahead** of a user's request?" If the answer is yes, then you should choose Static Generation.
On the other hand, Static Generation is **not** a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.
In that case, you can use **Server-Side Rendering**. It will be slower, but the pre-rendered page will always be up-to-date. Or you can skip pre-rendering and use client-side JavaScript to populate data.
html,
body {
padding: 0;
margin: 0;
font-family:
-apple-system,
BlinkMacSystemFont,
Segoe UI,
Roboto,
Oxygen,
Ubuntu,
Cantarell,
Fira Sans,
Droid Sans,
Helvetica Neue,
sans-serif;
line-height: 1.6;
font-size: 18px;
}
* {
box-sizing: border-box;
}
a {
color: #0070f3;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.heading2Xl {
font-size: 2.5rem;
line-height: 1.2;
font-weight: 800;
letter-spacing: -0.05rem;
margin: 1rem 0;
}
.headingXl {
font-size: 2rem;
line-height: 1.3;
font-weight: 800;
letter-spacing: -0.05rem;
margin: 1rem 0;
}
.headingLg {
font-size: 1.5rem;
line-height: 1.4;
margin: 1rem 0;
}
.headingMd {
font-size: 1.2rem;
line-height: 1.5;
}
.borderCircle {
border-radius: 9999px;
}
.colorInherit {
color: inherit;
}
.padding1px {
padding-top: 1px;
}
.list {
list-style: none;
padding: 0;
margin: 0;
}
.listItem {
margin: 0 0 1.25rem;
}
.lightText {
color: #666;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment