Unverified Commit 98941fc4 authored by Joseph's avatar Joseph Committed by GitHub

backport: docs fixes 16.2.x (#94935)

Includes:

- e519ede9 docs: less aggressive AI agent hint for an experimental API
(#93811)
- 22fc63da docs: fix typos and links (#92541)
- dc3a7ebf docs: rework dynamic segments intro section (#94126)
- 48d3ab5c Remove extra word (#94160)
- ae76532c docs: transpilePackages usage (#93602)
- b14d9a42 docs: fix code examples in getting-started guides (#93273)
- 57ddbf81 docs: point deployment docs to the new Docker official
guide (#94185)
- 16e862ae docs: correct custom server optimization guidance (#94229)
- 13847b2e docs: bodySizeLimit measures raw HTTP body (#94137)
- bc384860 docs: accuracy and papercuts (#94299)
- 044e25ac docs: clarify rewrites execution order (#93765)
- d3cd3681 docs: update draftMode guide (#94155)
- 2aefd051 docs: fix typos in contribution guide (#94375)
- bd9f0eb4 docs: clarify next-env.d.ts regeneration (#94232)
- 5c9bc5c8 docs: fix onRequestError error type example (#94518)
- ca2a022c docs: fix 'time zone' spelling in FOUC guide (#93244)
- 40d08d66 docs: expand the Cache Components migration guide (#94649)
- 21a1eafb docs: server actions guide (#93553)
- 3691c518 docs: fix capitalization of Server and Client Components
(#94891)

And additionally, adapts the Cache Components migration guide for the
16.2 release line (instant navigation and the `instant` route config
aren't available on 16.2):

- docs: remove instant navigation content from the Cache Components
migration guide for 16.2

---------
Co-authored-by: 's avatarJude Gao <jude.gao@vercel.com>
Co-authored-by: 's avatarAyodele Samuel Adebayo <unclebigbay@gmail.com>
Co-authored-by: 's avatarIgor Babko <i.i.babko@gmail.com>
Co-authored-by: 's avatarStanislav Kozachenko <49488521+StanislavKozachenko@users.noreply.github.com>
Co-authored-by: 's avatarKristiyan Velkov <40764277+kristiyan-velkov@users.noreply.github.com>
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
Co-authored-by: 's avatarRazin Shafayet <sumonislamk29@gmail.com>
Co-authored-by: 's avatarSJvaca30 <122259127+SJvaca30@users.noreply.github.com>
Co-authored-by: 's avatarDanyal Ahmed <58849388+danyalahmed1995@users.noreply.github.com>
Co-authored-by: 's avatarKarl Horky <karl.horky@gmail.com>
Co-authored-by: 's avatarniketchandivade <56070211+niketchandivade@users.noreply.github.com>
parent 6e1a94de
...@@ -122,7 +122,7 @@ Use `@slot` for named slots rendered by a parent layout. Use intercept patterns ...@@ -122,7 +122,7 @@ Use `@slot` for named slots rendered by a parent layout. Use intercept patterns
| [`favicon`](/docs/app/api-reference/file-conventions/metadata/app-icons#favicon) | `.ico` | Favicon file | | [`favicon`](/docs/app/api-reference/file-conventions/metadata/app-icons#favicon) | `.ico` | Favicon file |
| [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#icon) | `.ico` `.jpg` `.jpeg` `.png` `.svg` | App Icon file | | [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#icon) | `.ico` `.jpg` `.jpeg` `.png` `.svg` | App Icon file |
| [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated App Icon | | [`icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated App Icon |
| [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#apple-icon) | `.jpg` `.jpeg`, `.png` | Apple App Icon file | | [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#apple-icon) | `.jpg` `.jpeg` `.png` | Apple App Icon file |
| [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated Apple App Icon | | [`apple-icon`](/docs/app/api-reference/file-conventions/metadata/app-icons#generate-icons-using-code-js-ts-tsx) | `.js` `.ts` `.tsx` | Generated Apple App Icon |
#### Open Graph and Twitter images #### Open Graph and Twitter images
......
...@@ -287,10 +287,11 @@ You can use the [`<Link>` component](/docs/app/api-reference/components/link) to ...@@ -287,10 +287,11 @@ You can use the [`<Link>` component](/docs/app/api-reference/components/link) to
For example, to generate a list of blog posts, import `<Link>` from `next/link` and pass a `href` prop to the component: For example, to generate a list of blog posts, import `<Link>` from `next/link` and pass a `href` prop to the component:
```tsx filename="app/ui/post.tsx" highlight={1,10} switcher ```tsx filename="app/ui/post.tsx" highlight={1,2,11} switcher
import Link from 'next/link' import Link from 'next/link'
import { getPosts } from '@/lib/posts'
export default async function Post({ post }) { export default async function Posts() {
const posts = await getPosts() const posts = await getPosts()
return ( return (
...@@ -305,10 +306,11 @@ export default async function Post({ post }) { ...@@ -305,10 +306,11 @@ export default async function Post({ post }) {
} }
``` ```
```jsx filename="app/ui/post.js" highlight={1,10} switcher ```jsx filename="app/ui/post.js" highlight={1,2,11} switcher
import Link from 'next/link' import Link from 'next/link'
import { getPosts } from '@/lib/posts'
export default async function Post({ post }) { export default async function Posts() {
const posts = await getPosts() const posts = await getPosts()
return ( return (
......
...@@ -65,7 +65,7 @@ export default function Layout({ children }: { children: React.ReactNode }) { ...@@ -65,7 +65,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
```jsx filename="app/layout.js" switcher ```jsx filename="app/layout.js" switcher
import Link from 'next/link' import Link from 'next/link'
export default function Layout() { export default function Layout({ children }) {
return ( return (
<html> <html>
<body> <body>
......
...@@ -14,7 +14,7 @@ This page explains how Server and Client Components work in Next.js and when to ...@@ -14,7 +14,7 @@ This page explains how Server and Client Components work in Next.js and when to
## When to use Server and Client Components? ## When to use Server and Client Components?
The client and server environments have different capabilities. Server and Client components allow you to run logic in each environment depending on your use case. The client and server environments have different capabilities. Server and Client Components allow you to run logic in each environment depending on your use case.
Use **Client Components** when you need: Use **Client Components** when you need:
......
...@@ -2,15 +2,16 @@ ...@@ -2,15 +2,16 @@
title: Mutating Data title: Mutating Data
description: Learn how to mutate data using Server Functions and Server Actions in Next.js. description: Learn how to mutate data using Server Functions and Server Actions in Next.js.
related: related:
title: API Reference title: Next steps
description: Learn more about the features mentioned in this page by reading the API Reference. description: Learn more about Server Actions and the APIs mentioned in this page.
links: links:
- app/guides/server-actions
- app/api-reference/functions/revalidatePath - app/api-reference/functions/revalidatePath
- app/api-reference/functions/revalidateTag - app/api-reference/functions/revalidateTag
- app/api-reference/functions/redirect - app/api-reference/functions/redirect
--- ---
You can mutate data in Next.js using [React Server Functions](https://react.dev/reference/rsc/server-functions). This page will go through how you can [create](#creating-server-functions) and [invoke](#invoking-server-functions) Server Functions. You can mutate data in Next.js using [React Server Functions](https://react.dev/reference/rsc/server-functions). This page will go through how you can [create](#creating-server-functions) and [invoke](#invoking-server-functions) Server Functions. For Next.js-specific behaviors (single-roundtrip response, sequential dispatch, security, deployment), see [Server Actions and Mutations](/docs/app/guides/server-actions).
## What are Server Functions? ## What are Server Functions?
......
...@@ -35,14 +35,15 @@ export async function getProducts() { ...@@ -35,14 +35,15 @@ export async function getProducts() {
`cacheLife` accepts a profile name or a custom configuration object: `cacheLife` accepts a profile name or a custom configuration object:
| Profile | `stale` | `revalidate` | `expire` | | Profile | `stale` | `revalidate` | `expire` |
| --------- | ------- | ------------ | ----------- | | --------- | ------- | ------------ | -------- |
| `seconds` | 0 | 1s | 60s | | `default` | 5m | 15m | never |
| `minutes` | 5m | 1m | 1h | | `seconds` | 30s | 1s | 60s |
| `hours` | 5m | 1h | 1d | | `minutes` | 5m | 1m | 1h |
| `days` | 5m | 1d | 1w | | `hours` | 5m | 1h | 1d |
| `weeks` | 5m | 1w | 30d | | `days` | 5m | 1d | 1w |
| `max` | 5m | 30d | ~indefinite | | `weeks` | 5m | 1w | 30d |
| `max` | 5m | 30d | 1y |
For fine-grained control, pass an object: For fine-grained control, pass an object:
......
...@@ -93,7 +93,7 @@ export default function MyApp({ Component, pageProps }) { ...@@ -93,7 +93,7 @@ export default function MyApp({ Component, pageProps }) {
## Google fonts ## Google fonts
You can automatically self-host any Google Font. Fonts are included stored as static assets and served from the same domain as your deployment, meaning no requests are sent to Google by the browser when the user visits your site. You can automatically self-host any Google Font. Fonts are included as static assets and served from the same domain as your deployment, meaning no requests are sent to Google by the browser when the user visits your site.
To start using a Google Font, import your chosen font from `next/font/google`: To start using a Google Font, import your chosen font from `next/font/google`:
......
...@@ -162,17 +162,23 @@ import { getPost } from '@/app/lib/data' ...@@ -162,17 +162,23 @@ import { getPost } from '@/app/lib/data'
export async function generateMetadata({ export async function generateMetadata({
params, params,
}: { }: {
params: { slug: string } params: Promise<{ slug: string }>
}) { }) {
const post = await getPost(params.slug) const { slug } = await params
const post = await getPost(slug)
return { return {
title: post.title, title: post.title,
description: post.description, description: post.description,
} }
} }
export default async function Page({ params }: { params: { slug: string } }) { export default async function Page({
const post = await getPost(params.slug) params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await getPost(slug)
return <div>{post.title}</div> return <div>{post.title}</div>
} }
``` ```
...@@ -181,7 +187,8 @@ export default async function Page({ params }: { params: { slug: string } }) { ...@@ -181,7 +187,8 @@ export default async function Page({ params }: { params: { slug: string } }) {
import { getPost } from '@/app/lib/data' import { getPost } from '@/app/lib/data'
export async function generateMetadata({ params }) { export async function generateMetadata({ params }) {
const post = await getPost(params.slug) const { slug } = await params
const post = await getPost(slug)
return { return {
title: post.title, title: post.title,
description: post.description, description: post.description,
...@@ -189,7 +196,8 @@ export async function generateMetadata({ params }) { ...@@ -189,7 +196,8 @@ export async function generateMetadata({ params }) {
} }
export default async function Page({ params }) { export default async function Page({ params }) {
const post = await getPost(params.slug) const { slug } = await params
const post = await getPost(slug)
return <div>{post.title}</div> return <div>{post.title}</div>
} }
``` ```
...@@ -264,8 +272,13 @@ export const size = { ...@@ -264,8 +272,13 @@ export const size = {
export const contentType = 'image/png' export const contentType = 'image/png'
// Image generation // Image generation
export default async function Image({ params }: { params: { slug: string } }) { export default async function Image({
const post = await getPost(params.slug) params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await getPost(slug)
return new ImageResponse( return new ImageResponse(
( (
...@@ -302,7 +315,8 @@ export const contentType = 'image/png' ...@@ -302,7 +315,8 @@ export const contentType = 'image/png'
// Image generation // Image generation
export default async function Image({ params }) { export default async function Image({ params }) {
const post = await getPost(params.slug) const { slug } = await params
const post = await getPost(slug)
return new ImageResponse( return new ImageResponse(
( (
......
...@@ -39,7 +39,7 @@ Node.js deployments support all Next.js features. Learn how to [configure them]( ...@@ -39,7 +39,7 @@ Node.js deployments support all Next.js features. Learn how to [configure them](
## Docker ## Docker
Next.js can be deployed to any provider that supports [Docker](https://www.docker.com/) containers. This includes container orchestrators like Kubernetes or a cloud provider that runs Docker. For containerization best practices, see the [Docker guide for React.js](https://docs.docker.com/guides/reactjs/). Next.js can be deployed to any provider that supports [Docker](https://www.docker.com/) containers. This includes container orchestrators like Kubernetes or a cloud provider that runs Docker. For best practices on containerizing your app, refer to Docker's official [Next.js](https://docs.docker.com/guides/nextjs) and [React.js](https://docs.docker.com/guides/reactjs) guides.
Docker deployments support all Next.js features. Learn how to [configure them](/docs/app/guides/self-hosting) for your infrastructure. Docker deployments support all Next.js features. Learn how to [configure them](/docs/app/guides/self-hosting) for your infrastructure.
......
...@@ -749,16 +749,16 @@ import { cookies } from 'next/headers' ...@@ -749,16 +749,16 @@ import { cookies } from 'next/headers'
import { decrypt } from '@/app/lib/session' import { decrypt } from '@/app/lib/session'
export async function updateSession() { export async function updateSession() {
const session = (await cookies()).get('session')?.value const cookieStore = await cookies()
const session = cookieStore.get('session')?.value
const payload = await decrypt(session) const payload = await decrypt(session)
if (!session || !payload) { if (!session || !payload) {
return null return null
} }
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)( const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
await cookies() cookieStore.set('session', session, {
).set('session', session, {
httpOnly: true, httpOnly: true,
secure: true, secure: true,
expires: expires, expires: expires,
...@@ -1120,7 +1120,7 @@ While Proxy can be useful for initial checks, it should not be your only line of ...@@ -1120,7 +1120,7 @@ While Proxy can be useful for initial checks, it should not be your only line of
> **Tips**: > **Tips**:
> >
> - In Proxy, you can also read cookies using `req.cookies.get('session').value`. > - In Proxy, you can also read cookies using `req.cookies.get('session')?.value`.
> - Proxy uses the Node.js runtime, check if your Auth library and session management library are compatible. You may need to use [Middleware](https://github.com/vercel/next.js/blob/v15.5.6/docs/01-app/03-api-reference/03-file-conventions/middleware.mdx) if your Auth library only supports [Edge Runtime](/docs/app/api-reference/edge) > - Proxy uses the Node.js runtime, check if your Auth library and session management library are compatible. You may need to use [Middleware](https://github.com/vercel/next.js/blob/v15.5.6/docs/01-app/03-api-reference/03-file-conventions/middleware.mdx) if your Auth library only supports [Edge Runtime](/docs/app/api-reference/edge)
> - You can use the `matcher` property in the Proxy to specify which routes Proxy should run on. Although, for auth, it's recommended Proxy runs on all routes. > - You can use the `matcher` property in the Proxy to specify which routes Proxy should run on. Although, for auth, it's recommended Proxy runs on all routes.
......
...@@ -351,9 +351,9 @@ export async function POST(request: Request) { ...@@ -351,9 +351,9 @@ export async function POST(request: Request) {
try { try {
const clonedRequest = request.clone() const clonedRequest = request.clone()
await request.body() await request.text()
await clonedRequest.body() await clonedRequest.text()
await request.body() // Throws error await request.text() // Throws error
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
} catch { } catch {
...@@ -367,9 +367,9 @@ export async function POST(request) { ...@@ -367,9 +367,9 @@ export async function POST(request) {
try { try {
const clonedRequest = request.clone() const clonedRequest = request.clone()
await request.body() await request.text()
await clonedRequest.body() await clonedRequest.text()
await request.body() // Throws error await request.text() // Throws error
return new Response(null, { status: 204 }) return new Response(null, { status: 204 })
} catch { } catch {
...@@ -612,7 +612,13 @@ export async function GET(request: NextRequest) { ...@@ -612,7 +612,13 @@ export async function GET(request: NextRequest) {
const token = request.nextUrl.searchParams.get('session_token') const token = request.nextUrl.searchParams.get('session_token')
const redirectUrl = request.nextUrl.searchParams.get('redirect_url') const redirectUrl = request.nextUrl.searchParams.get('redirect_url')
const response = NextResponse.redirect(new URL(redirectUrl, request.url)) const destination = new URL(redirectUrl ?? '/', request.url)
// Prevent open redirects: only allow same-origin destinations
if (destination.origin !== request.nextUrl.origin) {
return new Response('Invalid redirect', { status: 400 })
}
const response = NextResponse.redirect(destination)
response.cookies.set({ response.cookies.set({
value: token, value: token,
...@@ -634,7 +640,13 @@ export async function GET(request) { ...@@ -634,7 +640,13 @@ export async function GET(request) {
const token = request.nextUrl.searchParams.get('session_token') const token = request.nextUrl.searchParams.get('session_token')
const redirectUrl = request.nextUrl.searchParams.get('redirect_url') const redirectUrl = request.nextUrl.searchParams.get('redirect_url')
const response = NextResponse.redirect(new URL(redirectUrl, request.url)) const destination = new URL(redirectUrl ?? '/', request.url)
// Prevent open redirects: only allow same-origin destinations
if (destination.origin !== request.nextUrl.origin) {
return new Response('Invalid redirect', { status: 400 })
}
const response = NextResponse.redirect(destination)
response.cookies.set({ response.cookies.set({
value: token, value: token,
......
...@@ -27,7 +27,7 @@ CDNs that respect `s-maxage` and `stale-while-revalidate` can cache static and I ...@@ -27,7 +27,7 @@ CDNs that respect `s-maxage` and `stale-while-revalidate` can cache static and I
### Static assets ### Static assets
Static assets (JavaScript, CSS, images, fonts) served from `/_next/static/` include content hashes in their filenames and have a 1 year `max-age` and `immutable` directive: `public,max-age=31536000,immutable` Static assets (JavaScript, CSS, images, fonts) served from `/_next/static/` include content hashes in their filenames and have a 1 year `max-age` and `immutable` directive: `public, max-age=31536000, immutable`
You can use [`assetPrefix`](/docs/app/api-reference/config/next-config-js/assetPrefix) to serve static assets from a different domain or CDN origin. You can use [`assetPrefix`](/docs/app/api-reference/config/next-config-js/assetPrefix) to serve static assets from a different domain or CDN origin.
......
...@@ -10,7 +10,7 @@ Next.js includes its own server with `next start` by default. If you have an exi ...@@ -10,7 +10,7 @@ Next.js includes its own server with `next start` by default. If you have an exi
> **Good to know**: > **Good to know**:
> >
> - Before deciding to use a custom server, keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like **[Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization).** > - Before deciding to use a custom server, keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements.
> - When using standalone output mode, it does not trace custom server files. This mode outputs a separate minimal `server.js` file, instead. These cannot be used together. > - When using standalone output mode, it does not trace custom server files. This mode outputs a separate minimal `server.js` file, instead. These cannot be used together.
Take a look at the [following example](https://github.com/vercel/next.js/tree/canary/examples/custom-server) of a custom server: Take a look at the [following example](https://github.com/vercel/next.js/tree/canary/examples/custom-server) of a custom server:
......
...@@ -9,6 +9,7 @@ related: ...@@ -9,6 +9,7 @@ related:
- app/guides/authentication - app/guides/authentication
- app/guides/content-security-policy - app/guides/content-security-policy
- app/guides/forms - app/guides/forms
- app/guides/server-actions
--- ---
[React Server Components](https://react.dev/reference/rsc/server-components) improve performance and simplify data fetching, but also shift where and how data is accessed, changing some of the traditional security assumptions for handling data in frontend apps. [React Server Components](https://react.dev/reference/rsc/server-components) improve performance and simplify data fetching, but also shift where and how data is accessed, changing some of the traditional security assumptions for handling data in frontend apps.
...@@ -33,7 +34,7 @@ You should follow a **Zero Trust** model when adopting Server Components in an e ...@@ -33,7 +34,7 @@ You should follow a **Zero Trust** model when adopting Server Components in an e
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export default async function Page() { export default async function Page() {
const cookieStore = cookies() const cookieStore = await cookies()
const token = cookieStore.get('AUTH_TOKEN')?.value const token = cookieStore.get('AUTH_TOKEN')?.value
const res = await fetch('https://api.example.com/profile', { const res = await fetch('https://api.example.com/profile', {
...@@ -73,7 +74,8 @@ import { cookies } from 'next/headers' ...@@ -73,7 +74,8 @@ import { cookies } from 'next/headers'
// Component to Server Component which minimizes risk of passing it to a Client // Component to Server Component which minimizes risk of passing it to a Client
// Component. // Component.
export const getCurrentUser = cache(async () => { export const getCurrentUser = cache(async () => {
const token = cookies().get('AUTH_TOKEN') const cookieStore = await cookies()
const token = cookieStore.get('AUTH_TOKEN')
const decodedToken = await decryptAndValidate(token) const decodedToken = await decryptAndValidate(token)
// Don't include secret tokens or private information as public fields. // Don't include secret tokens or private information as public fields.
// Use classes to avoid accidentally passing the whole object to the client. // Use classes to avoid accidentally passing the whole object to the client.
...@@ -116,12 +118,13 @@ export async function getProfileDTO(slug: string) { ...@@ -116,12 +118,13 @@ export async function getProfileDTO(slug: string) {
``` ```
```tsx filename="app/page.tsx" ```tsx filename="app/page.tsx"
import { getProfile } from '../../data/user' import { getProfileDTO } from '../../data/user-dto'
export async function Page({ params: { slug } }) { export default async function Page({ params }) {
const { slug } = await params
// This page can now safely pass around this profile knowing // This page can now safely pass around this profile knowing
// that it shouldn't contain anything sensitive. // that it shouldn't contain anything sensitive.
const profile = await getProfile(slug); const profile = await getProfileDTO(slug)
... ...
} }
``` ```
...@@ -137,7 +140,8 @@ This approach, however, makes it easier to accidentally expose private data to t ...@@ -137,7 +140,8 @@ This approach, however, makes it easier to accidentally expose private data to t
```tsx filename="app/page.tsx" ```tsx filename="app/page.tsx"
import Profile from './components/profile.tsx' import Profile from './components/profile.tsx'
export async function Page({ params: { slug } }) { export default async function Page({ params }) {
const { slug } = await params
const [rows] = await sql`SELECT * FROM user WHERE slug = ${slug}` const [rows] = await sql`SELECT * FROM user WHERE slug = ${slug}`
const userData = rows[0] const userData = rows[0]
// EXPOSED: This exposes all the fields in userData to the client because // EXPOSED: This exposes all the fields in userData to the client because
...@@ -184,10 +188,11 @@ import { getUser } from '../data/user' ...@@ -184,10 +188,11 @@ import { getUser } from '../data/user'
import Profile from './ui/profile' import Profile from './ui/profile'
export default async function Page({ export default async function Page({
params: { slug }, params,
}: { }: {
params: { slug: string } params: Promise<{ slug: string }>
}) { }) {
const { slug } = await params
const publicProfile = await getUser(slug) const publicProfile = await getUser(slug)
return <Profile user={publicProfile} /> return <Profile user={publicProfile} />
} }
...@@ -307,7 +312,7 @@ You should always validate input from client, as they can be easily modified. Fo ...@@ -307,7 +312,7 @@ You should always validate input from client, as they can be easily modified. Fo
```tsx filename="app/page.tsx" ```tsx filename="app/page.tsx"
// BAD: Trusting searchParams directly // BAD: Trusting searchParams directly
export default async function Page({ searchParams }) { export default async function Page({ searchParams }) {
const isAdmin = searchParams.get('isAdmin') const isAdmin = (await searchParams).isAdmin
if (isAdmin === 'true') { if (isAdmin === 'true') {
// Vulnerable: relies on untrusted client data // Vulnerable: relies on untrusted client data
return <AdminPanel /> return <AdminPanel />
...@@ -319,7 +324,8 @@ import { cookies } from 'next/headers' ...@@ -319,7 +324,8 @@ import { cookies } from 'next/headers'
import { verifyAdmin } from './auth' import { verifyAdmin } from './auth'
export default async function Page() { export default async function Page() {
const token = cookies().get('AUTH_TOKEN') const cookieStore = await cookies()
const token = cookieStore.get('AUTH_TOKEN')
const isAdmin = await verifyAdmin(token) const isAdmin = await verifyAdmin(token)
if (isAdmin) { if (isAdmin) {
...@@ -565,8 +571,9 @@ Mutations (e.g. logging out users, updating databases, invalidating caches) shou ...@@ -565,8 +571,9 @@ Mutations (e.g. logging out users, updating databases, invalidating caches) shou
```tsx filename="app/page.tsx" ```tsx filename="app/page.tsx"
// BAD: Triggering a mutation during rendering // BAD: Triggering a mutation during rendering
export default async function Page({ searchParams }) { export default async function Page({ searchParams }) {
if (searchParams.get('logout')) { if ((await searchParams).logout) {
cookies().delete('AUTH_TOKEN') const cookieStore = await cookies()
cookieStore.delete('AUTH_TOKEN')
} }
return <UserProfile /> return <UserProfile />
......
This diff is collapsed.
...@@ -4,7 +4,7 @@ nav_title: Forms ...@@ -4,7 +4,7 @@ nav_title: Forms
description: Learn how to create forms in Next.js with React Server Actions. description: Learn how to create forms in Next.js with React Server Actions.
--- ---
React Server Actions are [Server Functions](https://react.dev/reference/rsc/server-functions) that execute on the server. They can be called in Server and Client Components to handle form submissions. This guide will walk you through how to create forms in Next.js with Server Actions. React Server Actions are [Server Functions](https://react.dev/reference/rsc/server-functions) that execute on the server. They can be called in Server and Client Components to handle form submissions. This guide will walk you through how to create forms in Next.js with Server Actions. For Server Action behaviors beyond forms (single-roundtrip response, sequential dispatch, security, deployment), see [Server Actions and Mutations](/docs/app/guides/server-actions).
> [!WARNING] > [!WARNING]
> Always verify [authentication and authorization](/docs/app/guides/authentication) inside each Server Action, even if the form is only rendered on an authenticated page. See the [Data Security guide](/docs/app/guides/data-security) for more details. > Always verify [authentication and authorization](/docs/app/guides/authentication) inside each Server Action, even if the form is only rendered on an authenticated page. See the [Data Security guide](/docs/app/guides/data-security) for more details.
......
...@@ -50,7 +50,7 @@ Soft tags are automatically generated by Next.js based on the route path, prefix ...@@ -50,7 +50,7 @@ Soft tags are automatically generated by Next.js based on the route path, prefix
Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based system. When `revalidatePath('/blog/hello')` is called, it invalidates cache entries associated with that path's leaf route tag and its ancestor layout soft tags (for example `_N_T_/layout`, `_N_T_/blog/layout`, `_N_T_/blog/hello/layout`, and `_N_T_/blog/hello`). Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based system. When `revalidatePath('/blog/hello')` is called, it invalidates cache entries associated with that path's leaf route tag and its ancestor layout soft tags (for example `_N_T_/layout`, `_N_T_/blog/layout`, `_N_T_/blog/hello/layout`, and `_N_T_/blog/hello`).
In the [cache handler API](/docs/app/api-reference/config/next-config-js/cacheHandlers), soft tags are passed to the `get()` method as the `softTags` parameter. Your handler should check whether any soft tag has been invalidated after the cache entry's timestamp. The `getExpiration()` method returns the most recent revalidation timestamp across all provided tags, or `0` if none have been revalidated. Your handler should treat an entry as stale if the returned timestamp is newer than the entry's own timestamp. See the [cache handler API reference](/docs/app/api-reference/config/next-config-js/cacheHandlers#getexpiration) for the full semantics. In the [cache handler API](/docs/app/api-reference/config/next-config-js/cacheHandlers), soft tags are passed to the `get()` method as the `softTags` parameter. Your handler should check whether any soft tag has been invalidated after the cache entry's timestamp. The `getExpiration()` method returns the most recent revalidation timestamp across all provided tags, or `0` if none have been revalidated. It can also return `Infinity` to signal that the soft tags should instead be passed to `get()` and checked for expiration there. Your handler should treat an entry as stale if the returned timestamp is newer than the entry's own timestamp. See the [cache handler API reference](/docs/app/api-reference/config/next-config-js/cacheHandlers#getexpiration) for the full semantics.
## Multi-Instance Considerations ## Multi-Instance Considerations
...@@ -89,7 +89,7 @@ If a CDN caches Next.js responses, it should respect the `Vary` header and the ` ...@@ -89,7 +89,7 @@ If a CDN caches Next.js responses, it should respect the `Vary` header and the `
The revalidation system prioritizes availability over strict consistency. Content is always served, even when infrastructure guarantees cannot be fully met: The revalidation system prioritizes availability over strict consistency. Content is always served, even when infrastructure guarantees cannot be fully met:
- **Cache write failure**: the response is still served to the user because writes are asynchronous. The cache entry is lost, and the next request triggers a fresh render. - **Cache write failure**: the response is still served to the user because writes are asynchronous. The cache entry is lost, and the next request triggers a fresh render.
- **Cache read failure**: your handler should catch internal errors and return `undefined` (the cache miss signal). The route is then server-rendered fresh. The framework does not wrap `get()` in a try/catch, so unhandled exceptions will propagate as render errors. - **Cache read failure**: your handler should catch internal errors and return `undefined` (the cache miss signal). The route is then server-rendered fresh. A thrown error is not treated as a cache miss; it propagates as a render error, so always return `undefined` to signal a miss.
- **HTML/RSC cache inconsistency**: if a CDN caches HTML and RSC responses with different TTLs or invalidation timing, users may see mismatched content during client-side navigation. Cache them together and respect the `Vary` header to avoid this. - **HTML/RSC cache inconsistency**: if a CDN caches HTML and RSC responses with different TTLs or invalidation timing, users may see mismatched content during client-side navigation. Cache them together and respect the `Vary` header to avoid this.
- **Cross-deployment skew**: during rolling deployments, configure [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) so that a build ID change triggers a hard navigation to fetch consistent content. - **Cross-deployment skew**: during rolling deployments, configure [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) so that a build ID change triggers a hard navigation to fetch consistent content.
......
...@@ -810,6 +810,7 @@ module.exports = withMDX({ ...@@ -810,6 +810,7 @@ module.exports = withMDX({
mdxRs: { mdxRs: {
jsxRuntime?: string // Custom jsx runtime jsxRuntime?: string // Custom jsx runtime
jsxImportSource?: string // Custom jsx import source, jsxImportSource?: string // Custom jsx import source,
providerImportSource?: string // Module providing a `useMDXComponents` context
mdxType?: 'gfm' | 'commonmark' // Configure what kind of mdx syntax will be used to parse & transform mdxType?: 'gfm' | 'commonmark' // Configure what kind of mdx syntax will be used to parse & transform
}, },
}, },
......
...@@ -113,7 +113,7 @@ export async function proxy(request) { ...@@ -113,7 +113,7 @@ export async function proxy(request) {
## Linking between zones ## Linking between zones
Links to paths in a different zone should use an `a` tag instead of the Next.js [`<Link>`](/docs/pages/api-reference/components/link) component. This is because Next.js will try to prefetch and soft navigate to any relative path in `<Link>` component, which will not work across zones. Links to paths in a different zone should use an `a` tag instead of the Next.js [`<Link>`](/docs/app/api-reference/components/link) component. This is because Next.js will try to prefetch and soft navigate to any relative path in `<Link>` component, which will not work across zones.
## Sharing code ## Sharing code
......
...@@ -281,7 +281,7 @@ const nextConfig = { ...@@ -281,7 +281,7 @@ const nextConfig = {
module.exports = nextConfig module.exports = nextConfig
``` ```
To automatically bundle all packages, you can use the [`bundlePagesRouterDependencies`](/docs/pages/api-reference/config/next-config-js/bundlePagesRouterDependencies) option in your `next.config.js`. To automatically bundle all packages, you can use the [`bundlePagesRouterDependencies`](/docs/pages/api-reference/config/next-config-js/bundlePagesRouterDependencies) option in your `next.config.js`. This option defaults to `false`.
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
......
...@@ -49,10 +49,10 @@ export default function NavLink() { ...@@ -49,10 +49,10 @@ export default function NavLink() {
} }
``` ```
| **Context** | **Prefetched payload** | **Client Cache TTL** | | **Context** | **Prefetched payload** | **Client Cache TTL** |
| ----------------- | -------------------------------- | ------------------------------------------------------------------------------ | | ----------------- | -------------------------------- | ------------------------------------------------------------------------------------------------- |
| No `loading.js` | Entire page | Until app reload | | No `loading.js` | Entire page | 5 min ([`staleTimes.static`](/docs/app/api-reference/config/next-config-js/staleTimes)) |
| With `loading.js` | Layout to first loading boundary | 30s ([configurable](/docs/app/api-reference/config/next-config-js/staleTimes)) | | With `loading.js` | Layout to first loading boundary | Off by default ([`staleTimes.dynamic`](/docs/app/api-reference/config/next-config-js/staleTimes)) |
Automatic prefetching runs only in production. Disable with `prefetch={false}` or use the wrapper in [Disabled Prefetch](#disabled-prefetch). Automatic prefetching runs only in production. Disable with `prefetch={false}` or use the wrapper in [Disabled Prefetch](#disabled-prefetch).
...@@ -78,7 +78,7 @@ export function PricingCard() { ...@@ -78,7 +78,7 @@ export function PricingCard() {
} }
``` ```
If the intent is to prefetch a URL when a component loads, see the extending or rejecting a link [example]. To prefetch a URL when a component loads, see [Extending or ejecting link](#extending-or-ejecting-link).
## Hover-triggered prefetch ## Hover-triggered prefetch
......
...@@ -4,7 +4,7 @@ nav_title: Preventing Flash ...@@ -4,7 +4,7 @@ nav_title: Preventing Flash
description: Learn how to correct server-rendered content before the browser paints, avoiding visible flash when the page hydrates. description: Learn how to correct server-rendered content before the browser paints, avoiding visible flash when the page hydrates.
--- ---
User preferences, browser settings, and client-side storage aren't available during server rendering. The server emits a reasonable default, but any UI that depends on client-only state (locale, timezone, theme, persisted interactions) needs to be updated before the user sees it. User preferences, browser settings, and client-side storage aren't available during server rendering. The server emits a reasonable default, but any UI that depends on client-only state (locale, time zone, theme, persisted interactions) needs to be updated before the user sees it.
Some common approaches to this problem: Some common approaches to this problem:
...@@ -26,7 +26,7 @@ Use Chrome DevTools [Sensors](https://developer.chrome.com/docs/devtools/sensors ...@@ -26,7 +26,7 @@ Use Chrome DevTools [Sensors](https://developer.chrome.com/docs/devtools/sensors
## Dates and formatting ## Dates and formatting
A UTC timestamp like `2026-06-15T18:00:00Z` represents a fixed point in time, but how it is formatted for display depends on the user's locale and timezone. `toLocaleDateString()` and `Intl.DateTimeFormat` on the server use the server's settings, which may not match the user's. A UTC timestamp like `2026-06-15T18:00:00Z` represents a fixed point in time, but how it is formatted for display depends on the user's locale and time zone. `toLocaleDateString()` and `Intl.DateTimeFormat` on the server use the server's settings, which may not match the user's.
### The problem ### The problem
...@@ -454,7 +454,7 @@ The inline script and the lazy `useState` initializer both read from `localStora ...@@ -454,7 +454,7 @@ The inline script and the lazy `useState` initializer both read from `localStora
### Why not read from headers or cookies at request time? ### Why not read from headers or cookies at request time?
Reading `Accept-Language` with `await headers()` lets the server format per-request. With Cache Components, you can wrap just the date in a Suspense fallback so the rest of the page stays static. But you'd need to show a fallback instead of immediate content, and `Accept-Language` doesn't include timezone information. Reading `Accept-Language` with `await headers()` lets the server format per-request. With Cache Components, you can wrap just the date in a Suspense fallback so the rest of the page stays static. But you'd need to show a fallback instead of immediate content, and `Accept-Language` doesn't include time zone information.
## Next steps ## Next steps
......
...@@ -99,7 +99,7 @@ However, if this component is rendered at request time, fetching its data will d ...@@ -99,7 +99,7 @@ However, if this component is rendered at request time, fetching its data will d
Even though the header is rendered instantly, it can't be sent to the browser until the product list has finished fetching. Even though the header is rendered instantly, it can't be sent to the browser until the product list has finished fetching.
To protect us from this performance cliff, Next.js will show us a [warning](/docs/messages/blocking-route) the first time we **await** data: `Blocking data was accessed outside of Suspense` To protect us from this performance cliff, the first time we **await** this uncached data Next.js shows a [warning](/docs/messages/blocking-route): accessing uncached data outside of `<Suspense>` prevents the route from being prerendered.
At this point, we have to decide how to **unblock** the response. Either: At this point, we have to decide how to **unblock** the response. Either:
......
...@@ -195,7 +195,7 @@ Although the `worker` strategy does not require any additional configuration to ...@@ -195,7 +195,7 @@ Although the `worker` strategy does not require any additional configuration to
If you would like to add additional configuration options, you can include it within the `<Head />` component used in a [custom `_document.js`](/docs/pages/building-your-application/routing/custom-document): If you would like to add additional configuration options, you can include it within the `<Head />` component used in a [custom `_document.js`](/docs/pages/building-your-application/routing/custom-document):
```jsx filename="_pages/document.jsx" ```jsx filename="pages/_document.js"
import { Html, Head, Main, NextScript } from 'next/document' import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() { export default function Document() {
......
This diff is collapsed.
...@@ -383,7 +383,6 @@ Prefer explicit `<Suspense>` boundaries close to the dynamic access. When the pr ...@@ -383,7 +383,6 @@ Prefer explicit `<Suspense>` boundaries close to the dynamic access. When the pr
### Error handling mid-stream ### Error handling mid-stream
{/* TODO: catchError semantics - not landed on stable yet */}
If a component throws an error after streaming has started, the nearest [`error.js`](/docs/app/api-reference/file-conventions/error) boundary catches it and renders the error UI in place of the failed component. The rest of the page remains intact, only the section that errored is replaced. If a component throws an error after streaming has started, the nearest [`error.js`](/docs/app/api-reference/file-conventions/error) boundary catches it and renders the error UI in place of the failed component. The rest of the page remains intact, only the section that errored is replaced.
Because the HTTP status code (`200 OK`) has already been sent with the first chunk, it cannot be changed to a `4xx` or `5xx`. The error is handled entirely within the streamed HTML. See [The HTTP contract](#the-http-contract) for more on this constraint. Because the HTTP status code (`200 OK`) has already been sent with the first chunk, it cannot be changed to a `4xx` or `5xx`. The error is handled entirely within the streamed HTML. See [The HTTP contract](#the-http-contract) for more on this constraint.
......
...@@ -367,6 +367,7 @@ Options to pass to the `<GoogleAnalytics>` component. ...@@ -367,6 +367,7 @@ Options to pass to the `<GoogleAnalytics>` component.
| --------------- | -------- | ------------------------------------------------------------------------------------------------------ | | --------------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `gaId` | Required | Your [measurement ID](https://support.google.com/analytics/answer/12270356). Usually starts with `G-`. | | `gaId` | Required | Your [measurement ID](https://support.google.com/analytics/answer/12270356). Usually starts with `G-`. |
| `dataLayerName` | Optional | Name of the data layer. Defaults to `dataLayer`. | | `dataLayerName` | Optional | Name of the data layer. Defaults to `dataLayer`. |
| `debugMode` | Optional | Enable Google Analytics [debug mode](https://support.google.com/analytics/answer/7201382). |
| `nonce` | Optional | A [nonce](/docs/app/guides/content-security-policy#nonces). | | `nonce` | Optional | A [nonce](/docs/app/guides/content-security-policy#nonces). |
### Google Maps Embed ### Google Maps Embed
......
...@@ -374,7 +374,7 @@ export async function generateMetadata(props) { ...@@ -374,7 +374,7 @@ export async function generateMetadata(props) {
const query = searchParams.query const query = searchParams.query
} }
export async function Page(props) { export default async function Page(props) {
const params = await props.params const params = await props.params
const searchParams = await props.searchParams const searchParams = await props.searchParams
const slug = params.slug const slug = params.slug
......
...@@ -5,6 +5,8 @@ description: Learn how to use the use server directive to execute code on the se ...@@ -5,6 +5,8 @@ description: Learn how to use the use server directive to execute code on the se
The `use server` directive designates a function or file to be executed on the **server side**. It can be used at the top of a file to indicate that all functions in the file are server-side, or inline at the top of a function to mark the function as a [Server Function](https://19.react.dev/reference/rsc/server-functions). This is a React feature. The `use server` directive designates a function or file to be executed on the **server side**. It can be used at the top of a file to indicate that all functions in the file are server-side, or inline at the top of a function to mark the function as a [Server Function](https://19.react.dev/reference/rsc/server-functions). This is a React feature.
For Next.js-specific Server Action behaviors (response model, security, configuration, deployment), see [Server Actions and Mutations](/docs/app/guides/server-actions).
## Using `use server` at the top of a file ## Using `use server` at the top of a file
The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server. The following example shows a file with a `use server` directive at the top. All functions in the file are executed on the server.
......
--- ---
title: Dynamic Route Segments title: Dynamic Route Segments
nav_title: Dynamic Segments nav_title: Dynamic Segments
description: Dynamic Route Segments can be used to programmatically generate route segments from dynamic data. description: Use Dynamic Segments to read URL path params and generate routes from dynamic data.
related: related:
title: Next Steps title: Next Steps
description: For more information on what to do next, we recommend the following sections description: For more information on what to do next, we recommend the following sections
...@@ -9,7 +9,9 @@ related: ...@@ -9,7 +9,9 @@ related:
- app/api-reference/functions/generate-static-params - app/api-reference/functions/generate-static-params
--- ---
When you don't know the exact route segment names ahead of time and want to create routes from dynamic data, you can use Dynamic Segments that are filled in at request time or prerendered at build time. A URL path is a sequence of path segments. In the App Router, a segment may be **static** (a literal value matched exactly) or **dynamic** (a placeholder that captures a value from the URL). When you don't know a segment's value ahead of time, define a Dynamic Segment to create routes from dynamic data. Next.js passes the captured values to your page via the path `params` prop, either filled in at request time or prerendered at build time.
> **Good to know**: Dynamic Segments are often referred to as path params, route params, or URL params.
## Convention ## Convention
......
...@@ -48,10 +48,17 @@ export const onRequestError: Instrumentation.onRequestError = async ( ...@@ -48,10 +48,17 @@ export const onRequestError: Instrumentation.onRequestError = async (
request, request,
context context
) => { ) => {
const message = err instanceof Error ? err.message : String(err)
const digest =
typeof err === 'object' && err !== null && 'digest' in err
? String(err.digest)
: undefined
await fetch('https://.../report-error', { await fetch('https://.../report-error', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
message: err.message, message,
digest,
request, request,
context, context,
}), }),
...@@ -64,10 +71,17 @@ export const onRequestError: Instrumentation.onRequestError = async ( ...@@ -64,10 +71,17 @@ export const onRequestError: Instrumentation.onRequestError = async (
```js filename="instrumentation.js" switcher ```js filename="instrumentation.js" switcher
export async function onRequestError(err, request, context) { export async function onRequestError(err, request, context) {
const message = err instanceof Error ? err.message : String(err)
const digest =
typeof err === 'object' && err !== null && 'digest' in err
? String(err.digest)
: undefined
await fetch('https://.../report-error', { await fetch('https://.../report-error', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
message: err.message, message,
digest,
request, request,
context, context,
}), }),
...@@ -84,7 +98,7 @@ The function accepts three parameters: `error`, `request`, and `context`. ...@@ -84,7 +98,7 @@ The function accepts three parameters: `error`, `request`, and `context`.
```ts filename="Types" ```ts filename="Types"
export function onRequestError( export function onRequestError(
error: { digest: string } & Error, error: unknown,
request: { request: {
path: string // resource path, e.g. /blog?name=foo path: string // resource path, e.g. /blog?name=foo
method: string // request method. e.g. GET, POST, etc method: string // request method. e.g. GET, POST, etc
...@@ -104,7 +118,7 @@ export function onRequestError( ...@@ -104,7 +118,7 @@ export function onRequestError(
): void | Promise<void> ): void | Promise<void>
``` ```
- `error`: The caught error itself (type is always `Error`), and a `digest` property which is the unique ID of the error. - `error`: The caught value is typed as `unknown`. Narrow it before reading properties like `message` or `digest`.
- `request`: Read-only request information associated with the error. - `request`: Read-only request information associated with the error.
- `context`: The context in which the error occurred. This can be the type of router (App or Pages Router), and/or (Server Components (`'render'`), Route Handlers (`'route'`), Server Actions (`'action'`), or Proxy (`'proxy'`)). - `context`: The context in which the error occurred. This can be the type of router (App or Pages Router), and/or (Server Components (`'render'`), Route Handlers (`'route'`), Server Actions (`'action'`), or Proxy (`'proxy'`)).
......
...@@ -91,10 +91,11 @@ The order Next.js routes are checked is: ...@@ -91,10 +91,11 @@ The order Next.js routes are checked is:
1. [headers](/docs/app/api-reference/config/next-config-js/headers) are checked/applied 1. [headers](/docs/app/api-reference/config/next-config-js/headers) are checked/applied
2. [redirects](/docs/app/api-reference/config/next-config-js/redirects) are checked/applied 2. [redirects](/docs/app/api-reference/config/next-config-js/redirects) are checked/applied
3. [proxy](/docs/app/api-reference/file-conventions/proxy) 3. [proxy](/docs/app/api-reference/file-conventions/proxy)
4. `beforeFiles` rewrites are checked/applied 4. `beforeFiles` rewrites: for each entry, if `source`, `has`, and `missing` matches the request, it's rewritten to `destination`.
5. static files from the [public directory](/docs/app/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served 5. static files from the [public directory](/docs/app/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served
6. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match 6. `afterFiles` rewrites are tried in order. If a `source`, `has`, and `missing` matches the request, it's rewritten to `destination`; the first rewrite that resolves to a static file, page, or dynamic route is served.
7. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use [fallback: true/'blocking'](/docs/pages/api-reference/functions/get-static-paths#fallback-true) in `getStaticPaths`, the fallback `rewrites` defined in your `next.config.js` will _not_ be run. 7. dynamic routes (e.g., `app/blog/[slug]/page.tsx`) are matched against the current path
8. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use [fallback: true/'blocking'](/docs/pages/api-reference/functions/get-static-paths#fallback-true) in `getStaticPaths`, those dynamic routes take priority over the fallback `rewrites` defined in your `next.config.js`.
</AppOnly> </AppOnly>
...@@ -102,10 +103,11 @@ The order Next.js routes are checked is: ...@@ -102,10 +103,11 @@ The order Next.js routes are checked is:
1. [headers](/docs/pages/api-reference/config/next-config-js/headers) are checked/applied 1. [headers](/docs/pages/api-reference/config/next-config-js/headers) are checked/applied
2. [redirects](/docs/pages/api-reference/config/next-config-js/redirects) are checked/applied 2. [redirects](/docs/pages/api-reference/config/next-config-js/redirects) are checked/applied
3. `beforeFiles` rewrites are checked/applied 3. `beforeFiles` rewrites: for each entry, if `source` matches the request, it's rewritten to `destination`.
4. static files from the [public directory](/docs/pages/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served 4. static files from the [public directory](/docs/pages/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served
5. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match 5. `afterFiles` rewrites are tried in order. If a `source` matches the request, it's rewritten to `destination`; the first rewrite that resolves to a static file, page, or dynamic route is served.
6. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use [fallback: true/'blocking'](/docs/pages/api-reference/functions/get-static-paths#fallback-true) in `getStaticPaths`, the fallback `rewrites` defined in your `next.config.js` will _not_ be run. 6. dynamic routes (e.g., `pages/blog/[slug].tsx`) are matched against the current path
7. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use [fallback: true/'blocking'](/docs/pages/api-reference/functions/get-static-paths#fallback-true) in `getStaticPaths`, the fallback `rewrites` defined in your `next.config.js` will _not_ be run.
</PagesOnly> </PagesOnly>
......
...@@ -39,6 +39,8 @@ module.exports = { ...@@ -39,6 +39,8 @@ module.exports = {
} }
``` ```
The limit applies to the raw HTTP request body, including the bytes that `multipart/form-data` adds for boundaries, part headers, and field metadata. If you expect uploads close to the configured value, leave some room for this overhead. For typical multipart uploads, an additional 10–20 KB is a reasonable rule of thumb.
## Enabling Server Actions (v13) ## Enabling Server Actions (v13)
Server Actions became a stable feature in Next.js 14, and are enabled by default. However, if you are using an earlier version of Next.js, you can enable them by setting `experimental.serverActions` to `true`. Server Actions became a stable feature in Next.js 14, and are enabled by default. However, if you are using an earlier version of Next.js, you can enable them by setting `experimental.serverActions` to `true`.
......
--- ---
title: transpilePackages title: transpilePackages
description: Automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (`node_modules`). description: Transpile and bundle dependencies from monorepo workspace packages or `node_modules` libraries that ship TypeScript, JSX, or modern syntax.
--- ---
{/* 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 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. */}
Next.js can automatically transpile and bundle dependencies from local packages (like monorepos) or from external dependencies (`node_modules`). This replaces the `next-transpile-modules` package. Use `transpilePackages` to compile and bundle a dependency instead of treating it as untouched runtime code. Values are package names, including scoped names like `@scope/pkg`. Paths and glob patterns are not supported.
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
transpilePackages: ['package-name'], transpilePackages: ['package-name', '@scope/pkg'],
} }
module.exports = nextConfig module.exports = nextConfig
``` ```
This replaces the `next-transpile-modules` package.
## When you need it
Turbopack transpiles workspace packages (npm, pnpm, or Yarn workspaces) in your monorepo automatically under both routers. Webpack does the same for the App Router. Add a package to `transpilePackages` when:
- **A `node_modules` dependency ships raw TypeScript or JSX.** Next.js does not compile code inside `node_modules` by default. Listing the package opts it in, or you can build the package to plain JavaScript and point its `main`/`exports` at the compiled output.
- **You build with webpack for the Pages Router and the dependency's source lives outside the next app's directory.** For example, an `apps/web` app importing `packages/ui` in the same monorepo.
- **You use the Pages Router and want a `node_modules` dependency bundled into the route.** Pages Router loads `node_modules` server-side dependencies through Node.js `require` at runtime. List the package to bundle its source into the route instead. App Router already bundles Server Component and Route Handler dependencies unless the package is listed in [`serverExternalPackages`](/docs/app/api-reference/config/next-config-js/serverExternalPackages).
> **Good to know**: A package cannot appear in both `transpilePackages` and [`serverExternalPackages`](/docs/app/api-reference/config/next-config-js/serverExternalPackages); Next.js throws at build start if it does. Packages listed in [`optimizePackageImports`](/docs/app/api-reference/config/next-config-js/optimizePackageImports) and the entries in [`default-transpiled-packages.json`](https://github.com/vercel/next.js/blob/canary/packages/next/src/lib/default-transpiled-packages.json) are added automatically; you do not need to repeat them.
## Version History ## Version History
| Version | Changes | | Version | Changes |
......
...@@ -88,7 +88,7 @@ Running `next dev`, `next build`, or [`next typegen`](/docs/app/api-reference/cl ...@@ -88,7 +88,7 @@ Running `next dev`, `next build`, or [`next typegen`](/docs/app/api-reference/cl
> **Good to know**: > **Good to know**:
> >
> - We recommend adding `next-env.d.ts` to your `.gitignore` file. > - `next-env.d.ts` is managed by Next.js. Its contents are an implementation detail and may change over time. Add it to `.gitignore`. If your project already tracks the file, remove it from Git. Do not edit this file manually.
> - The file must be in your `tsconfig.json` `include` array (`create-next-app` does this automatically). > - The file must be in your `tsconfig.json` `include` array (`create-next-app` does this automatically).
## Examples ## Examples
......
...@@ -223,7 +223,7 @@ The default component type in the App Router. Server Components render on the se ...@@ -223,7 +223,7 @@ The default component type in the App Router. Server Components render on the se
## Server Action ## Server Action
A [Server Function](#server-function) that is passed to a Client Component as a prop or bound to a form action. Server Actions are commonly used for form submissions and data mutations. Learn more in [Server Actions and Mutations](/docs/app/getting-started/mutating-data). A [Server Function](#server-function) that is passed to a Client Component as a prop or bound to a form action. Server Actions are commonly used for form submissions and data mutations. Learn more in [Server Actions and Mutations](/docs/app/guides/server-actions).
## Server Function ## Server Function
......
...@@ -50,7 +50,7 @@ Next.js now uses the Rust-based compiler [SWC](https://swc.rs/) to compile JavaS ...@@ -50,7 +50,7 @@ Next.js now uses the Rust-based compiler [SWC](https://swc.rs/) to compile JavaS
Next.js provides full backward compatibility with applications that have [custom Babel configuration](/docs/pages/guides/babel). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust. Next.js provides full backward compatibility with applications that have [custom Babel configuration](/docs/pages/guides/babel). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust.
When an application has a custom Babel configuration, Next.js will automatically opt-out of using SWC for compiling JavaScript/Typescript and will fall back to using Babel in the same way that it was used in Next.js 11. When an application has a custom Babel configuration, Next.js will automatically opt-out of using SWC for compiling JavaScript/TypeScript and will fall back to using Babel in the same way that it was used in Next.js 11.
Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to: Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to:
......
...@@ -34,7 +34,7 @@ The docs are written in [MDX](https://mdxjs.com/), a markdown format that suppor ...@@ -34,7 +34,7 @@ The docs are written in [MDX](https://mdxjs.com/), a markdown format that suppor
VSCode has a built-in markdown previewer that you can use to see your edits locally. To enable the previewer for MDX files, you'll need to add a configuration option to your user settings. VSCode has a built-in markdown previewer that you can use to see your edits locally. To enable the previewer for MDX files, you'll need to add a configuration option to your user settings.
Open the command palette (`⌘ + ⇧ + P` on Mac or `Ctrl + Shift + P` on Windows) and search from `Preferences: Open User Settings (JSON)`. Open the command palette (`⌘ + ⇧ + P` on Mac or `Ctrl + Shift + P` on Windows) and search for `Preferences: Open User Settings (JSON)`.
Then, add the following line to your `settings.json` file: Then, add the following line to your `settings.json` file:
...@@ -396,7 +396,7 @@ While we don't have a strict template for pages, there are page sections you'll ...@@ -396,7 +396,7 @@ While we don't have a strict template for pages, there are page sections you'll
- **Overview:** The first paragraph of a page should tell the user what the feature is and what it's used for. Followed by a minimum working example or its API reference. - **Overview:** The first paragraph of a page should tell the user what the feature is and what it's used for. Followed by a minimum working example or its API reference.
- **Convention:** If the feature has a convention, it should be explained here. - **Convention:** If the feature has a convention, it should be explained here.
- **Examples**: Show how the feature can be used with different use cases. - **Examples**: Show how the feature can be used with different use cases.
- **API Tables**: API Pages should have an overview table at the of the page with jump-to-section links (when possible). - **API Tables**: API Pages should have an overview table at the top of the page with jump-to-section links (when possible).
- **Next Steps (Related Links)**: Add links to related pages to guide the user's learning journey. - **Next Steps (Related Links)**: Add links to related pages to guide the user's learning journey.
Feel free to add these sections as needed. Feel free to add these sections as needed.
......
...@@ -8,8 +8,6 @@ related: ...@@ -8,8 +8,6 @@ related:
- app/getting-started - app/getting-started
--- ---
{/* AI agent hint: If fixing slow client-side navigations, Suspense alone is not enough. You must also export `unstable_instant` from the route. Read docs/01-app/02-guides/instant-navigation.mdx before making changes. */}
Welcome to the Next.js documentation! Welcome to the Next.js documentation!
## What is Next.js? ## What is Next.js?
......
...@@ -4,9 +4,9 @@ title: ESM packages need to be imported ...@@ -4,9 +4,9 @@ title: ESM packages need to be imported
## Why This Error Occurred ## Why This Error Occurred
Packages in node_modules that are published as EcmaScript Module, need to be `import`ed via `import ... from 'package'` or `import('package')`. Packages in node_modules that are published as ECMAScript Module, need to be `import`ed via `import ... from 'package'` or `import('package')`.
You get this error when using a different way to reference the package, e. g. `require()`. You get this error when using a different way to reference the package, e.g. `require()`.
## Possible Ways to Fix It ## Possible Ways to Fix It
......
...@@ -197,7 +197,7 @@ export default async function handler(req: NextRequest) { ...@@ -197,7 +197,7 @@ export default async function handler(req: NextRequest) {
### Explanation ### Explanation
Based on beta feedback, we are changing the Cookies API in `NextRequest` and `NextResponse` to align more to a `get`/`set` model. The `Cookies` API extends Map, including methods like [entries](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map/entries) and [values](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map/entries). Based on beta feedback, we are changing the Cookies API in `NextRequest` and `NextResponse` to align more to a `get`/`set` model. The `Cookies` API extends Map, including methods like [entries](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map/entries) and [values](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map/values).
### How to upgrade ### How to upgrade
......
...@@ -52,7 +52,7 @@ export default async function ComponentThatWillBeExportedAsPage({ params, search ...@@ -52,7 +52,7 @@ export default async function ComponentThatWillBeExportedAsPage({ params, search
export * from '.../some-file' export * from '.../some-file'
``` ```
It is unexpected that you would run the codemod and not successfully convert all instances of `params` and `searchParams` to async or have a marker string to help you locate unconverted cases. If you do find yourself in this situation please report this to [Next.js on Github](https://github.com/vercel/next.js/issues). It is unexpected that you would run the codemod and not successfully convert all instances of `params` and `searchParams` to async or have a marker string to help you locate unconverted cases. If you do find yourself in this situation please report this to [Next.js on GitHub](https://github.com/vercel/next.js/issues).
## Useful Links ## Useful Links
......
...@@ -33,7 +33,7 @@ export default async function GET(request) { ...@@ -33,7 +33,7 @@ export default async function GET(request) {
} }
``` ```
It is unexpected that you would run the codemod and not successfully convert all instances of `params` and `searchParams` to async or have a marker string to help you locate unconverted cases. If you do find yourself in this situation please report this to [Next.js on Github](https://github.com/vercel/next.js/issues). It is unexpected that you would run the codemod and not successfully convert all instances of `params` and `searchParams` to async or have a marker string to help you locate unconverted cases. If you do find yourself in this situation please report this to [Next.js on GitHub](https://github.com/vercel/next.js/issues).
## Useful Links ## Useful Links
......
...@@ -8,7 +8,7 @@ Next.js now uses Rust-based compiler [SWC](https://swc.rs/) to compile JavaScrip ...@@ -8,7 +8,7 @@ Next.js now uses Rust-based compiler [SWC](https://swc.rs/) to compile JavaScrip
Next.js provides full backwards compatibility with applications that have [custom Babel configuration](/docs/pages/guides/babel). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust. Next.js provides full backwards compatibility with applications that have [custom Babel configuration](/docs/pages/guides/babel). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust.
When an application has custom Babel configuration Next.js will automatically opt-out of using SWC for compiling JavaScript/Typescript and will fall back to using Babel in the same way that it was used in Next.js 11. When an application has custom Babel configuration Next.js will automatically opt-out of using SWC for compiling JavaScript/TypeScript and will fall back to using Babel in the same way that it was used in Next.js 11.
Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to: Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to:
......
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