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

Backport/docs fixes 16.1.5 (#88916)

Back porting docs updates into 16-1 (canary now contains changes that
shouldn't show in 16.1)

---------
Co-authored-by: 's avatarEng Zer Jun <engzerjun@gmail.com>
Co-authored-by: 's avatarRich Haines <hello@richardhaines.dev>
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarDelba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <lukesandberg@users.noreply.github.com>
Co-authored-by: 's avatargraphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
parent 60de6c21
......@@ -328,7 +328,7 @@ function HoverPrefetchLink({ href, children }) {
React mitigates this with Selective Hydration and you can further improve this by:
- Using the [`@next/bundle-analyzer`](/docs/app/guides/package-bundling#analyzing-javascript-bundles) plugin to identify and reduce bundle size by removing large dependencies.
- Using the [`@next/bundle-analyzer`](/docs/app/guides/package-bundling#nextbundle-analyzer-for-webpack) plugin to identify and reduce bundle size by removing large dependencies.
- Moving logic from the client to the server where possible. See the [Server and Client Components](/docs/app/getting-started/server-and-client-components) docs for guidance.
## Examples
......
......@@ -32,7 +32,7 @@ Use **Server Components** when you need:
For example, the `<Page>` component is a Server Component that fetches data about a post, and passes it as props to the `<LikeButton>` which handles client-side interactivity.
```tsx filename="app/[id]/page.tsx" highlight={1,12} switcher
```tsx filename="app/[id]/page.tsx" highlight={1,17} switcher
import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data'
......@@ -241,7 +241,7 @@ export default function Search() {
You can pass data from Server Components to Client Components using props.
```tsx filename="app/[id]/page.tsx" highlight={1,7} switcher
```tsx filename="app/[id]/page.tsx" highlight={1,12} switcher
import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data'
......
......@@ -86,7 +86,7 @@ export default async function Page() {
}
```
> **Good to know**: You can verify that a route was fully prerendered by checking the build output summary. Alternatively see what content was added to the static shell of any page by viewing the page source in your browser.
> **Good to know**: You can verify that a route was fully prerendered by checking the build output summary. Alternatively, see what content was added to the static shell of any page by viewing the page source in your browser.
## Defer rendering to request time
......@@ -102,12 +102,11 @@ External systems provide content asynchronously, which often takes an unpredicta
In general, when you need the latest data from the source on each request (like real-time feeds or personalized content), defer rendering by providing fallback UI with a Suspense boundary.
For example the `DynamicContent` component below uses multiple operations that are not automatically prerendered.
For example, the `DynamicContent` component below uses multiple operations that are not automatically prerendered.
```tsx filename="page.tsx"
import { Suspense } from 'react'
import fs from 'node:fs/promises'
import { setTimeout } from 'node:timers/promises'
async function DynamicContent() {
// Network request
......@@ -120,7 +119,7 @@ async function DynamicContent() {
const file = await fs.readFile('..', 'utf-8')
// Simulating external system delay
await setTimeout(100) // from 'node:timers/promises'
await new Promise((resolve) => setTimeout(resolve, 100))
return <div>Not in the static shell</div>
}
......@@ -174,7 +173,7 @@ async function RuntimeData({ searchParams }) {
}
```
To use the `RuntimeData` component in, wrap it in a `<Suspense>` boundary:
To use the `RuntimeData` component, wrap it in a `<Suspense>` boundary:
```tsx filename="page.tsx"
export default async function Page(props) {
......@@ -504,6 +503,12 @@ During prerendering the header (static) and the blog posts fetched from the API
When a user visits the page, they instantly see this prerendered shell with the header and blog posts. Only the personalized preferences need to stream in at request time since they depend on the user's cookies. This ensures fast initial page loads while still providing personalized content.
## Metadata and Viewport
`generateMetadata` and `generateViewport` are part of rendering your page or layout. During prerendering, their access to runtime data or uncached dynamic data is tracked separately from the rest of the page.
If a page or layout is prerenderable but only metadata or viewport accesses uncached dynamic data or runtime data, Next.js requires an explicit choice: cache the data if possible, or signal that deferred rendering is intentional. See [Metadata with Cache Components](/docs/app/api-reference/functions/generate-metadata#with-cache-components) and [Viewport with Cache Components](/docs/app/api-reference/functions/generate-viewport#with-cache-components) for how to handle this.
## Enabling Cache Components
You can enable Cache Components (which includes PPR) by adding the [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) option to your Next config file:
......@@ -569,7 +574,7 @@ export default function Page() {
### `dynamic = "force-static"`
Start by removing it. When unhandled dynamic or runtime data access is detected during development and built time, Next.js raises an error. Otherwise, the [prerendering](#automatically-prerendered-content) step automatically extracts the static HTML shell.
Start by removing it. When unhandled dynamic or runtime data access is detected during development and build time, Next.js raises an error. Otherwise, the [prerendering](#automatically-prerendered-content) step automatically extracts the static HTML shell.
For dynamic data access, add [`use cache`](#using-use-cache) as close to the data access as possible with a long [`cacheLife`](/docs/app/api-reference/functions/cacheLife) like `'max'` to maintain cached behavior. If needed, add it at the top of the page or layout.
......
......@@ -12,6 +12,8 @@ The [`next/font`](/docs/app/api-reference/components/font) module automatically
It includes **built-in self-hosting** for any font file. This means you can optimally load web fonts with no layout shift.
<AppOnly>
To start using `next/font`, import it from [`next/font/local`](#local-fonts) or [`next/font/google`](#google-fonts), call it as a function with the appropriate options, and set the `className` of the element you want to apply the font to. For example:
```tsx filename="app/layout.tsx" highlight={1,3-5,9} switcher
......@@ -48,12 +50,99 @@ export default function Layout({ children }) {
Fonts are scoped to the component they're used in. To apply a font to your entire application, add it to the [Root Layout](/docs/app/api-reference/file-conventions/layout#root-layout).
</AppOnly>
<PagesOnly>
To start using `next/font`, import it from [`next/font/local`](#local-fonts) or [`next/font/google`](#google-fonts), call it as a function with the appropriate options, and set the `className` of the element you want to apply the font to. For example, you can apply fonts globally in your [Custom App](/docs/pages/building-your-application/routing/custom-app) (`pages/_app`):
```tsx filename="pages/_app.tsx" highlight={1,4-6,10} switcher
import { Geist } from 'next/font/google'
import type { AppProps } from 'next/app'
const geist = Geist({
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<main className={geist.className}>
<Component {...pageProps} />
</main>
)
}
```
```jsx filename="pages/_app.js" highlight={1,3-5,9} switcher
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={geist.className}>
<Component {...pageProps} />
</main>
)
}
```
If you want to apply the font to the `<html>` element, you can use a [Custom Document](/docs/pages/building-your-application/routing/custom-document) (`pages/_document`):
```tsx filename="pages/_document.tsx" highlight={2,4-6,10} switcher
import { Html, Head, Main, NextScript } from 'next/document'
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Document() {
return (
<Html lang="en" className={geist.className}>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
```jsx filename="pages/_document.js" highlight={2,4-6,10} switcher
import { Html, Head, Main, NextScript } from 'next/document'
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Document() {
return (
<Html lang="en" className={geist.className}>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
</PagesOnly>
## 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.
To start using a Google Font, import your chosen font from `next/font/google`:
<AppOnly>
```tsx filename="app/layout.tsx" switcher
import { Geist } from 'next/font/google'
......@@ -90,8 +179,49 @@ export default function RootLayout({ children }) {
}
```
</AppOnly>
<PagesOnly>
```tsx filename="pages/_app.tsx" switcher
import { Geist } from 'next/font/google'
import type { AppProps } from 'next/app'
const geist = Geist({
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<main className={geist.className}>
<Component {...pageProps} />
</main>
)
}
```
```jsx filename="pages/_app.js" switcher
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={geist.className}>
<Component {...pageProps} />
</main>
)
}
```
</PagesOnly>
We recommend using [variable fonts](https://fonts.google.com/variablefonts) for the best performance and flexibility. But if you can't use a variable font, you will need to specify a weight:
<AppOnly>
```tsx filename="app/layout.tsx" highlight={4} switcher
import { Roboto } from 'next/font/google'
......@@ -130,8 +260,51 @@ export default function RootLayout({ children }) {
}
```
</AppOnly>
<PagesOnly>
```tsx filename="pages/_app.tsx" highlight={5} switcher
import { Roboto } from 'next/font/google'
import type { AppProps } from 'next/app'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<main className={roboto.className}>
<Component {...pageProps} />
</main>
)
}
```
```jsx filename="pages/_app.js" highlight={4} switcher
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={roboto.className}>
<Component {...pageProps} />
</main>
)
}
```
</PagesOnly>
## Local fonts
<AppOnly>
To use a local font, import your font from `next/font/local` and specify the [`src`](/docs/app/api-reference/components/font#src) of your local font file. Fonts can be stored in the [`public`](/docs/app/api-reference/file-conventions/public-folder) folder or co-located inside the `app` folder. For example:
```tsx filename="app/layout.tsx" switcher
......@@ -170,6 +343,47 @@ export default function RootLayout({ children }) {
}
```
</AppOnly>
<PagesOnly>
To use a local font, import your font from `next/font/local` and specify the [`src`](/docs/pages/api-reference/components/font#src) of your local font file. Fonts can be stored in the [`public`](/docs/pages/api-reference/file-conventions/public-folder) folder or inside the `pages` folder. For example:
```tsx filename="pages/_app.tsx" switcher
import localFont from 'next/font/local'
import type { AppProps } from 'next/app'
const myFont = localFont({
src: './my-font.woff2',
})
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<main className={myFont.className}>
<Component {...pageProps} />
</main>
)
}
```
```jsx filename="pages/_app.js" switcher
import localFont from 'next/font/local'
const myFont = localFont({
src: './my-font.woff2',
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={myFont.className}>
<Component {...pageProps} />
</main>
)
}
```
</PagesOnly>
If you want to use multiple files for a single font family, `src` can be an array:
```js
......
......@@ -52,7 +52,6 @@ export function proxy(request: NextRequest) {
// Alternatively, you can use a default export:
// export default function proxy(request: NextRequest) { ... }
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
......@@ -69,10 +68,11 @@ export function proxy(request) {
// Alternatively, you can use a default export:
// export default function proxy(request) { ... }
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
```
The `matcher` config allows you to filter Proxy to run on specific paths. See the [Matcher](/docs/app/api-reference/file-conventions/proxy#matcher) documentation for more details on path matching.
Read more about [using `proxy`](/docs/app/guides/backend-for-frontend#proxy), or refer to the `proxy` [API reference](/docs/app/api-reference/file-conventions/proxy).
......@@ -415,9 +415,11 @@ Consider nonces when:
For applications that do not require nonces, you can set the CSP header directly in your [`next.config.js`](/docs/app/api-reference/config/next-config-js) file:
```js filename="next.config.js"
const isDev = process.env.NODE_ENV === 'development'
const cspHeader = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
script-src 'self' 'unsafe-inline'${isDev ? " 'unsafe-eval'" : ''};
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data:;
font-src 'self';
......
This diff is collapsed.
......@@ -142,7 +142,7 @@ Before going to production, you can run `next build` to build your application l
### Analyzing bundles
Use the [`@next/bundle-analyzer` plugin](/docs/app/guides/package-bundling#analyzing-javascript-bundles) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance.
Use the [`@next/bundle-analyzer` plugin](/docs/app/guides/package-bundling#nextbundle-analyzer-for-webpack) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance.
Additionally, the following tools can help you understand the impact of adding new dependencies to your application:
......
......@@ -14,9 +14,11 @@ If you're using an AI coding assistant that supports the [Model Context Protocol
#### Setup
Add the following configuration to your MCP client, example:
Add the following configuration to your MCP client, for each coding agent you can read [this section](https://github.com/vercel/next-devtools-mcp#mcp-client-configuration) for configuration details.
```json
**example:**
```json filename=".mcp.json"
{
"mcpServers": {
"next-devtools": {
......@@ -27,7 +29,7 @@ Add the following configuration to your MCP client, example:
}
```
For more information, visit the [`next-devtools-mcp`](https://www.npmjs.com/package/next-devtools-mcp) package on npm to configure with your MCP client.
For more information, visit the [`next-devtools-mcp`](https://github.com/vercel/next-devtools-mcp) documentation to configure with your MCP client.
> **Note:** Using `next-devtools-mcp@latest` ensures that your MCP client will always use the latest version of the Next.js DevTools MCP server.
......
---
title: 'use cache: private'
description: 'Learn how to use the `"use cache: private"` directive to enable runtime prefetching of personalized content in your Next.js application.'
description: 'Learn how to use the "use cache: private" directive to cache functions that access runtime request APIs.'
version: experimental
related:
title: Related
description: View related API references.
links:
- app/api-reference/directives/use-cache
- app/api-reference/config/next-config-js/cacheComponents
- app/api-reference/config/next-config-js/cacheHandlers
- app/api-reference/functions/cacheLife
- app/api-reference/functions/cacheTag
- app/guides/prefetching
---
The `'use cache: private'` directive works just like [`use cache`](/docs/app/api-reference/directives/use-cache), but allows you to use runtime APIs like cookies, headers, or search params.
The `'use cache: private'` directive allows functions to access runtime request APIs like `cookies()`, `headers()`, and `searchParams` within a cached scope. However, results are **never stored on the server**, they're cached only in the browser's memory and do not persist across page reloads.
> **Good to know:** Unlike `use cache`, private caches are not prerendered statically as they contain personalized data that is not shared between users.
Reach for `'use cache: private'` when:
- You want to cache a function that already accesses runtime data, and refactoring to [move the runtime access outside and pass values as arguments](/docs/app/getting-started/cache-components#with-runtime-data) is not practical.
- Compliance requirements prevent storing certain data on the server, even temporarily
Because this directive accesses runtime data, the function executes on every server render and is excluded from running during [static shell](/docs/app/getting-started/cache-components#how-rendering-works-with-cache-components) generation.
It is **not** possible to configure custom cache handlers for `'use cache: private'`.
For a comparison of the different cache directives, see [How `use cache: remote` differs from `use cache` and `use cache: private`](/docs/app/api-reference/directives/use-cache-remote#how-use-cache-remote-differs-from-use-cache-and-use-cache-private).
> **Good to know**: This directive is marked as `experimental` because it depends on runtime prefetching, which is not yet stable. Runtime prefetching is an upcoming feature that will let the router prefetch past the [static shell](/docs/app/getting-started/cache-components#how-rendering-works-with-cache-components) into **any** cached scope, not just private caches.
## Usage
......@@ -42,13 +52,21 @@ export default nextConfig
Then add `'use cache: private'` to your function along with a `cacheLife` configuration.
> **Good to know**: This directive is not available in Route Handlers.
### Basic example
In this example, we demonstrate that you can access cookies within a `'use cache: private'` scope:
```tsx filename="app/product/[id]/page.tsx" switcher
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag } from 'next/cache'
export async function generateStaticParams() {
return [{ id: '1' }]
}
export default async function ProductPage({
params,
}: {
......@@ -81,7 +99,7 @@ async function Recommendations({ productId }: { productId: string }) {
async function getRecommendations(productId: string) {
'use cache: private'
cacheTag(`recommendations-${productId}`)
cacheLife({ stale: 60 }) // Minimum 30 seconds required for runtime prefetch
cacheLife({ stale: 60 })
// Access cookies within private cache functions
const sessionId = (await cookies()).get('session-id')?.value || 'guest'
......@@ -95,6 +113,10 @@ import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife, cacheTag } from 'next/cache'
export async function generateStaticParams() {
return [{ id: '1' }]
}
export default async function ProductPage({ params }) {
const { id } = await params
......@@ -123,7 +145,7 @@ async function Recommendations({ productId }) {
async function getRecommendations(productId) {
'use cache: private'
cacheTag(`recommendations-${productId}`)
cacheLife({ stale: 60 }) // Minimum 30 seconds required for runtime prefetch
cacheLife({ stale: 60 })
// Access cookies within private cache functions
const sessionId = (await cookies()).get('session-id')?.value || 'guest'
......@@ -132,6 +154,8 @@ async function getRecommendations(productId) {
}
```
> **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work. See [`cacheLife` client router cache behavior](/docs/app/api-reference/functions/cacheLife#client-router-cache-behavior) for details.
## Request APIs allowed in private caches
The following request-specific APIs can be used inside `'use cache: private'` functions:
......
---
title: use cache
description: Learn how to use the use cache directive to cache data in your Next.js application.
description: Learn how to use the "use cache" directive to cache data in your Next.js application.
related:
title: Related
description: View related API references.
......
......@@ -195,7 +195,7 @@ Provide params ahead of time to prerender pages at build time. You can prerender
During the build process, the route is executed with each sample param to collect the HTML result. If dynamic content or runtime data are accessed incorrectly, the build will fail.
```tsx filename="app/blog/[slug]/page.tsx" highlight={5-7,10,22,24}
```tsx filename="app/blog/[slug]/page.tsx" highlight={3-5,8,19}
import { Suspense } from 'react'
export async function generateStaticParams() {
......
......@@ -137,8 +137,10 @@ export default function RootLayout({ children }) {
- The root layout **must** define `<html>` and `<body>` tags.
- You should **not** manually add `<head>` tags such as `<title>` and `<meta>` to root layouts. Instead, you should use the [Metadata API](/docs/app/getting-started/metadata-and-og-images) which automatically handles advanced requirements such as streaming and de-duplicating `<head>` elements.
- You can use [route groups](/docs/app/api-reference/file-conventions/route-groups) to create **multiple root layouts**.
- Navigating **across multiple root layouts** will cause a **full page load** (as opposed to a client-side navigation). For example, navigating from `/cart` that uses `app/(shop)/layout.js` to `/blog` that uses `app/(marketing)/layout.js` will cause a full page load. This **only** applies to multiple root layouts.
- You can create **multiple root layouts**. Any layout without a `layout.js` above it is a root layout. Two common approaches:
- Using [route groups](/docs/app/api-reference/file-conventions/route-groups) like `app/(shop)/layout.js` and `app/(marketing)/layout.js`
- Omitting `app/layout.js` so layouts in subdirectories like `app/dashboard/layout.js` and `app/blog/layout.js` each become root layouts for their respective directories.
- Navigating **across multiple root layouts** will cause a **full page load** (as opposed to a client-side navigation).
- The root layout can be under a **dynamic segment**, for example when implementing [internationalization](/docs/app/guides/internationalization) with `app/[lang]/layout.js`.
## Caveats
......
......@@ -7,6 +7,8 @@ related:
links:
- app/api-reference/file-conventions/metadata
- app/api-reference/functions/generate-viewport
- app/getting-started/cache-components
- app/api-reference/config/next-config-js/cacheComponents
---
You can use the `metadata` object or the `generateMetadata` function to define metadata.
......@@ -1202,6 +1204,68 @@ Streaming metadata improves perceived performance by reducing [TTFB](https://dev
Overriding `htmlLimitedBots` could lead to longer response times. Streaming metadata is an advanced feature, and the default should be sufficient for most cases.
### With Cache Components
When [Cache Components](/docs/app/getting-started/cache-components) is enabled, `generateMetadata` follows the same rules as other components. If metadata accesses runtime data (`cookies()`, `headers()`, `params`, `searchParams`) or performs uncached data fetching, it defers to request time.
How Next.js handles this depends on the rest of your page:
- **If other parts also defer to request time**: Prerendering generates a static shell, and metadata streams in with other deferred content.
- **If the page or layout is otherwise fully prerenderable**: Next.js requires an explicit choice: cache the data if possible, or signal that deferred rendering is intentional.
Streaming metadata at runtime while the rest of the page is fully prerenderable is not common. To ensure this behavior is intentional, an error is raised indicating which page or layout needs to be handled.
To resolve this, you have two options. If metadata depends on external data but not runtime data, use `use cache`:
```tsx filename="app/page.tsx" highlight={2}
export async function generateMetadata() {
'use cache'
const { title, description } = await db.query('site-metadata')
return { title, description }
}
```
If metadata genuinely requires runtime data, add a dynamic marker component to your page:
```tsx filename="app/page.tsx" highlight={11-14,19,28}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export async function generateMetadata() {
const token = (await cookies()).get('token')?.value
// ... use token to fetch personalized metadata
return { title: 'Personalized Title' }
}
const Connection = async () => {
await connection()
return null
}
async function DynamicMarker() {
return (
<Suspense>
<Connection />
</Suspense>
)
}
export default function Page() {
// DO NOT place await connection() here
// doing so prevents the article tag content from
// being included in the static shell
return (
<>
<article>Static content</article>
<DynamicMarker />
</>
)
}
```
The `DynamicMarker` component renders nothing but tells Next.js the page has intentional dynamic content. By wrapping it in Suspense, the static content still prerenders normally.
### Ordering
Metadata is evaluated in order, starting from the root segment down to the segment closest to the final `page.js` segment. For example:
......
......@@ -6,6 +6,8 @@ related:
description: View all the Metadata API options.
links:
- app/api-reference/file-conventions/metadata
- app/getting-started/cache-components
- app/api-reference/config/next-config-js/cacheComponents
---
You can customize the initial viewport of the page with the static `viewport` object or the dynamic `generateViewport` function.
......@@ -174,6 +176,50 @@ export const viewport = {
<meta name="color-scheme" content="dark" />
```
## With Cache Components
When [Cache Components](/docs/app/getting-started/cache-components) is enabled, `generateViewport` follows the same rules as other components. If viewport accesses runtime data (`cookies()`, `headers()`, `params`, `searchParams`) or performs uncached data fetching, it defers to request time.
Unlike metadata, viewport cannot be streamed because it affects initial page load UI. If `generateViewport` defers to request time, the page would need to block until resolved.
If viewport depends on external data but not runtime data, use `use cache`:
```tsx filename="app/layout.tsx" highlight={2}
export async function generateViewport() {
'use cache'
const { width, initialScale } = await db.query('viewport-size')
return { width, initialScale }
}
```
If viewport genuinely requires runtime data, wrap the document `<body>` in a Suspense boundary to signal that the entire route should be dynamic:
```tsx filename="app/layout.tsx" highlight={1,11-15}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
export async function generateViewport() {
const cookieJar = await cookies()
return {
themeColor: cookieJar.get('theme-color')?.value,
}
}
export default function RootLayout({ children }) {
return (
<Suspense>
<html>
<body>{children}</body>
</html>
</Suspense>
)
}
```
Caching is preferred because it allows static shell generation. Wrapping the document `body` in Suspense means there is no static shell or content to immediately send when a request arrives, making the entire route block until ready on every request.
> **Good to know**: Use [multiple root layouts](/docs/app/api-reference/file-conventions/layout#root-layout) to isolate fully dynamic viewport to specific routes, while still letting other routes in your application generate a static shell.
## Types
You can add type safety to your viewport object by using the `Viewport` type. If you are using the [built-in TypeScript plugin](/docs/app/api-reference/config/typescript) in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
......
---
title: optimizePackageImports
description: API Reference for optimizePackageImports Next.js Config Option
version: experimental
---
{/* 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. */}
......
......@@ -26,15 +26,16 @@ The following options are available:
The following commands are available:
| Command | Description |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more. |
| [`build`](#next-build-options) | Creates an optimized production build of your application. Displaying information about each route. |
| [`start`](#next-start-options) | Starts Next.js in production mode. The application should be compiled with `next build` first. |
| [`info`](#next-info-options) | Prints relevant details about the current system which can be used to report Next.js bugs. |
| [`telemetry`](#next-telemetry-options) | Allows you to enable or disable Next.js' completely anonymous telemetry collection. |
| [`typegen`](#next-typegen-options) | Generates TypeScript definitions for routes, pages, layouts, and route handlers without running a full build. |
| [`upgrade`](#next-upgrade-options) | Upgrades your Next.js application to the latest version. |
| Command | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| [`dev`](#next-dev-options) | Starts Next.js in development mode with Hot Module Reloading, error reporting, and more. |
| [`build`](#next-build-options) | Creates an optimized production build of your application. Displaying information about each route. |
| [`start`](#next-start-options) | Starts Next.js in production mode. The application should be compiled with `next build` first. |
| [`info`](#next-info-options) | Prints relevant details about the current system which can be used to report Next.js bugs. |
| [`telemetry`](#next-telemetry-options) | Allows you to enable or disable Next.js' completely anonymous telemetry collection. |
| [`typegen`](#next-typegen-options) | Generates TypeScript definitions for routes, pages, layouts, and route handlers without running a full build. |
| [`upgrade`](#next-upgrade-options) | Upgrades your Next.js application to the latest version. |
| [`experimental-analyze`](#next-experimental-analyze-options) | Analyzes bundle output using Turbopack. Does not produce build artifacts. |
> **Good to know**: Running `next` without a command is an alias for `next dev`.
......@@ -200,6 +201,43 @@ The following options are available for the `next upgrade` command:
| `--revision <revision>` | Specify a Next.js version or tag to upgrade to (e.g., `latest`, `canary`, `15.0.0`). Defaults to the release channel you have currently installed. |
| `--verbose` | Show verbose output during the upgrade process. |
### `next experimental-analyze` options
`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"
npx 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:
- Filter bundles by route and switch between client and server views
- View the full import chain showing why a module is included
- Trace imports across server-to-client component boundaries and dynamic imports
See [Package Bundling](/docs/app/guides/package-bundling#optimizing-large-bundles) for optimization strategies.
To write the analysis output to disk without starting the server, use the `--output` flag. The output is written to `.next/diagnostics/analyze` and contains static files that can be copied elsewhere or shared with others:
```bash filename="Terminal"
# Write output to .next/diagnostics/analyze
npx next experimental-analyze --output
# Copy the output for comparison with a future analysis
cp -r .next/diagnostics/analyze ./analyze-before-refactor
```
The following options are available for the `next experimental-analyze` command:
| Option | Description |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `-h, --help` | Show all available options. |
| `[directory]` | A directory on which to analyze the application. If not provided, the current directory will be used. |
| `--no-mangling` | Disables [mangling](https://en.wikipedia.org/wiki/Name_mangling). This may affect performance and should only be used for debugging purposes. |
| `--profile` | Enables production [profiling for React](https://react.dev/reference/react/Profiler). This may affect performance. |
| `-o, --output` | Write analysis files to disk without starting the server. Output is written to `.next/diagnostics/analyze`. |
| `--port <port>` | Specify a port number to serve the analyzer on. (default: 4000, env: PORT) |
## Examples
### Debugging prerender errors
......@@ -298,6 +336,7 @@ NODE_OPTIONS='--inspect' next
| Version | Changes |
| --------- | ------------------------------------------------------------------------------- |
| `v16.1.0` | Add the `next experimental-analyze` command |
| `v16.0.0` | The JS bundle size metrics have been removed from `next build` |
| `v15.5.0` | Add the `next typegen` command |
| `v15.4.0` | Add `--debug-prerender` option for `next build` to help debug prerender errors. |
---
title: useParams
description: API Reference for the useParams hook in the Pages Router.
---
`useParams` is a hook that lets you read a route's [dynamic params](/docs/pages/building-your-application/routing/dynamic-routes) filled in by the current URL.
```tsx filename="pages/shop/[slug].tsx" switcher
import { useParams } from 'next/navigation'
export default function ShopPage() {
const params = useParams<{ slug: string }>()
if (!params) {
// Render fallback UI while params are not yet available
return null
}
// Route -> /shop/[slug]
// URL -> /shop/shoes
// `params` -> { slug: 'shoes' }
return <>Shop: {params.slug}</>
}
```
```jsx filename="pages/shop/[slug].js" switcher
import { useParams } from 'next/navigation'
export default function ShopPage() {
const params = useParams()
if (!params) {
// Render fallback UI while params are not yet available
return null
}
// Route -> /shop/[slug]
// URL -> /shop/shoes
// `params` -> { slug: 'shoes' }
return <>Shop: {params.slug}</>
}
```
## Parameters
```tsx
const params = useParams()
```
`useParams` does not take any parameters.
## Returns
`useParams` returns an object containing the current route's filled in [dynamic parameters](/docs/pages/building-your-application/routing/dynamic-routes), or `null` during [pre-rendering](#behavior-during-pre-rendering).
- Each property in the object is an active dynamic segment.
- The property name is the segment's name, and the property value is what the segment is filled in with.
- The property value will either be a `string` or array of `string`s depending on the [type of dynamic segment](/docs/pages/building-your-application/routing/dynamic-routes).
- If the route contains no dynamic parameters, `useParams` returns an empty object.
For example:
| Route | URL | `useParams()` |
| ---------------------------- | ----------- | ------------------------- |
| `pages/shop/page.js` | `/shop` | `{}` |
| `pages/shop/[slug].js` | `/shop/1` | `{ slug: '1' }` |
| `pages/shop/[tag]/[item].js` | `/shop/1/2` | `{ tag: '1', item: '2' }` |
| `pages/shop/[...slug].js` | `/shop/1/2` | `{ slug: ['1', '2'] }` |
> **Good to know**: `useParams` is a [React Hook](https://react.dev/learn#using-hooks) and cannot be used with classes.
## Behavior
### Behavior during pre-rendering
For pages that are [statically optimized](/docs/pages/building-your-application/rendering/automatic-static-optimization), `useParams` will return `null` on the initial render. After hydration, the value will be updated to the actual params once the router is ready.
This is because params cannot be known during static generation for dynamic routes.
```tsx filename="pages/shop/[slug].tsx" switcher
import { useParams } from 'next/navigation'
export default function ShopPage() {
const params = useParams<{ slug: string }>()
if (!params) {
// Return a fallback UI while params are loading
// This prevents hydration mismatches
return <ShopPageSkeleton />
}
return <>Shop: {params.slug}</>
}
```
```jsx filename="pages/shop/[slug].js" switcher
import { useParams } from 'next/navigation'
export default function ShopPage() {
const params = useParams()
if (!params) {
// Return a fallback UI while params are loading
// This prevents hydration mismatches
return <ShopPageSkeleton />
}
return <>Shop: {params.slug}</>
}
```
### Using with `getServerSideProps`
When using [`getServerSideProps`](/docs/pages/building-your-application/data-fetching/get-server-side-props), the page is server-rendered on each request and `useParams` will return the actual params immediately:
```tsx filename="pages/shop/[slug].tsx" switcher
import { useParams } from 'next/navigation'
export default function ShopPage() {
const params = useParams<{ slug: string }>()
// With getServerSideProps, this fallback is never rendered because
// params is always available on the server. However, keeping
// the fallback allows this component to be reused on other pages
// that may not use getServerSideProps.
if (!params) {
return null
}
return <>Shop: {params.slug}</>
}
export async function getServerSideProps() {
return { props: {} }
}
```
```jsx filename="pages/shop/[slug].js" switcher
import { useParams } from 'next/navigation'
export default function ShopPage() {
const params = useParams()
// With getServerSideProps, this fallback is never rendered because
// params is always available on the server. However, keeping
// the fallback allows this component to be reused on other pages
// that may not use getServerSideProps.
if (!params) {
return null
}
return <>Shop: {params.slug}</>
}
export async function getServerSideProps() {
return { props: {} }
}
```
### Comparison with `router.query`
`useParams` only returns the dynamic route parameters, whereas [`router.query`](/docs/pages/api-reference/functions/use-router#router-object) from `useRouter` includes both dynamic parameters and query string parameters.
```tsx filename="pages/shop/[slug].tsx" switcher
import { useRouter } from 'next/router'
import { useParams } from 'next/navigation'
export default function ShopPage() {
const router = useRouter()
const params = useParams()
// URL -> /shop/shoes?color=red
// router.query -> { slug: 'shoes', color: 'red' }
// params -> { slug: 'shoes' }
// ...
}
```
```jsx filename="pages/shop/[slug].js" switcher
import { useRouter } from 'next/router'
import { useParams } from 'next/navigation'
export default function ShopPage() {
const router = useRouter()
const params = useParams()
// URL -> /shop/shoes?color=red
// router.query -> { slug: 'shoes', color: 'red' }
// params -> { slug: 'shoes' }
// ...
}
```
## Examples
### Sharing components with App Router
`useParams` from `next/navigation` works in both the Pages Router and App Router. This allows you to create shared components that work in either context:
```tsx filename="components/breadcrumb.tsx" switcher
import { useParams } from 'next/navigation'
// This component works in both pages/ and app/
export function Breadcrumb() {
const params = useParams<{ slug: string }>()
if (!params) {
// Fallback for Pages Router during pre-rendering
return <nav>Home / ...</nav>
}
return <nav>Home / {params.slug}</nav>
}
```
```jsx filename="components/breadcrumb.js" switcher
import { useParams } from 'next/navigation'
// This component works in both pages/ and app/
export function Breadcrumb() {
const params = useParams()
if (!params) {
// Fallback for Pages Router during pre-rendering
return <nav>Home / ...</nav>
}
return <nav>Home / {params.slug}</nav>
}
```
> **Good to know**: When using this component in the App Router, `useParams` never returns `null`, so the fallback branch will not be rendered.
## Version History
| Version | Changes |
| --------- | ----------------------- |
| `v13.3.0` | `useParams` introduced. |
......@@ -2,6 +2,7 @@
title: optimizePackageImports
description: API Reference for optimizePackageImports Next.js Config Option
source: app/api-reference/config/next-config-js/optimizePackageImports
version: experimental
---
{/* 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. */}
......@@ -8,9 +8,9 @@ When `cacheComponents` is enabled, Next.js requires that Document Metadata not d
Next.js determines if a page is entirely static or partially static by looking at whether any part of the page cannot be prerendered.
Typically you control the which parts of a page can be prerendered by adding `"use cache"` to Components or data functions and by avoiding Runtime data like `cookies()` or `searchParams`. However, Metadata can be defined in functions (`generateMetadata()`) defined far from your Page content. Additionally Metadata can implicitly depend on Runtime data when using file-based Metadata such as an icon inside a route with a dynamic param. It would be easy for Metadata to accidentally make an otherwise entirely static page have a dynamic component.
You control which parts of a page can be prerendered by adding `"use cache"` to components or data functions and by avoiding Runtime data like `cookies()` or `searchParams`. Metadata, though, can be defined in functions (`generateMetadata()`) far from your Page content. It can also implicitly depend on Runtime data when using file-based Metadata such as an icon inside a route with a dynamic param. This makes it easy for Metadata to accidentally make an otherwise entirely static page partially dynamic.
To prevent anwanted partially dynamic pages, Next.js expects pages that are otherwise entirely prerenderable to also have prerenderable Metadata.
To prevent unwanted partially dynamic pages, Next.js expects pages that are otherwise entirely prerenderable to also have prerenderable Metadata.
## Possible Ways to Fix It
......@@ -80,7 +80,7 @@ export default async function Page() {
### If you must access Request Data or your external data is uncacheable
If your metadata requires Request data or depends on external data which is not cacheable then Next.js will need to render this page dynamically on every request. However if you got this error, the rest of your page is able to be completely static. This is generally pretty rare, but if this is your actual constraint, you can indicate to Next.js that the page should be allowed to be dynamic by rendering any other component that is dynamic. Since your route doesn't have any genuine need for Request data, you can indicate an intentional dependency on a Request with `await connection()`. This is like telling Next.js that this component is never prerenderable and must be rendered on every user request.
If your metadata requires Request data or depends on external data that is not cacheable, Next.js will need to render this page dynamically on every request. That said, if you got this error, the rest of your page is able to be completely static. This is generally pretty rare, but if this is your actual constraint, you can indicate to Next.js that the page should be allowed to be dynamic by rendering any other component that is dynamic. Since your route doesn't have any genuine need for Request data, you can indicate an intentional dependency on a Request with `await connection()`. This is like telling Next.js that this component is never prerenderable and must be rendered on every user request.
Before:
......@@ -91,7 +91,7 @@ import { getPersonalizedTitle } from './my-api'
export async function generateMetadata() {
// In this example, we are assuming we must fetch our title
// from a protected external API. While the response is potentially
// cacheable, the it still requires accessing a token from the Request cookies.
// cacheable, it still requires accessing a token from the Request cookies.
const token = (await cookies()).get('token')
const response = await getPersonalizedTitle(token)
return {
......
......@@ -10,11 +10,11 @@ When `cacheComponents` is enabled, Next.js requires that `generateViewport()` no
To fix this issue, you must first determine your goal for the affected route.
Normally, Next.js ensures every page can produce an initial UI that allows the page to start loading even before uncached data and Runtime data is available. This is accomplished by defining prerenderable UI with Suspense. However viewport metadata is not able to be deferred until after the page loads because it affects initial page load UI.
Next.js ensures every page can produce an initial UI before uncached data and Runtime data is available. This is accomplished by defining prerenderable UI with Suspense. Viewport metadata, though, cannot be deferred because it affects initial page load UI.
Ideally, you update `generateViewport` so it does not depend on any uncached data or Runtime data. This allows navigations to appear instant.
However if this is not possibl you can instruct Next.js to allow all navigations to be potentially blocking by wrapping your document `<body>` in a Suspense boundary.
If this is not possible, you can instruct Next.js to allow all navigations to be potentially blocking by wrapping your document `<body>` in a Suspense boundary.
### Caching External Data
......@@ -69,7 +69,7 @@ import { cookies } from 'next/headers'
export async function generateViewport() {
const cookieJar = await cookies()
return {
themeColor: cookieJar.get('theme-color'),
themeColor: cookieJar.get('theme-color')?.value,
}
}
......@@ -91,7 +91,7 @@ import { cookies } from 'next/headers'
export async function generateViewport() {
const cookieJar = await cookies()
return {
themeColor: cookieJar.get('theme-color'),
themeColor: cookieJar.get('theme-color')?.value,
}
}
......
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