Bookmarks
ReferenceFrontendVerified

Next.js

Next.js is a React framework for websites and web applications. This reference covers the App Router, server rendering, Server Actions, caching, proxy and deployment.

checked 6 Nov · next check 13 Nov · 64 min read

Sections
14
Reading
64 min
Current version
16.4.5
Written from
nextjs.org/docs

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Next.js is and how it works

Next.js is a React framework for websites and web applications. On top of React components it adds file-based routing, rendering on the server and at build time, caching and the Turbopack bundler. The browser receives a page as ready-made HTML, and data is loaded on the server.

Choose Next.js when a fast first load, search visibility and data access without a separate API matter: a Server Component reads the database directly, and only the JavaScript for interactive parts is sent to the browser. Plain React with just a bundler is the choice when no framework fits your project’s constraints or when you are learning the basics of React.

Next.js has two routers. The App Router uses the app/ directory, was introduced in version 13 and is built on React Server Components; the older Pages Router uses the pages/ directory. This reference describes the App Router, which create-next-app recommends and sets up.

The path of a request

The core of Next.js is that a page is rendered on the server, and the browser receives HTML for a fast first paint plus the RSC payload, a compact description of the component tree that React uses to build the interface. JavaScript is loaded only for Client Components, and later navigations within the app happen without a full page reload.

How a page loads the first time and when you follow a link inside the app.
  1. The browser requests a URL, for example /blog/hello.
  2. If the project has a proxy.ts, it runs first and can redirect the request, rewrite the URL or add headers.
  3. Next.js matches the route from the folders in app/ and renders its layouts and page on the server. Server Components read data straight from the database or an API.
  4. The server responds with HTML and the RSC payload, a serialised tree of Server Components with placeholders for Client Components.
  5. The browser shows the HTML immediately, and React performs hydration: it attaches event handlers to the existing markup.
  6. When you follow a <Link>, the browser requests only the RSC payload of the new route from the server, without HTML; often it has already been prefetched.
  7. React updates the page in place: shared layouts and their state are preserved.

Static and dynamic

In Next.js the line between static and dynamic runs through components, not routes. A single page can consist of a static shell that is ready at build time and served immediately, cached parts with their own lifetime, and dynamic parts that are streamed in at request time. So “static site or server-rendered” is not a choice for the whole project: the decision is made per component.

How it differs from React with a bundler

What you needReact and ViteNext.js
Routinga separate library, such as React Routerfolders in app/
Renderingin the browser: a single-page application (SPA)on the server and at build time; the browser receives ready-made HTML
Data fetchingin the browser, with libraries such as TanStack Query or SWRin Server Components, straight from the database or an API
Server Components, SSR and SSGyou have to build it yourselfbuilt in
Cachingin the data-fetching library'use cache', lifetimes and tags
BundlerViteTurbopack, built in

Choose Next.js if you need server-generated HTML, server-side data fetching and routing out of the box. React with Vite fits when the app lives entirely in the browser and you are ready to assemble routing and data fetching yourself.

What to know beforehand

  • JavaScript and TypeScript: modules, promises, async/await (see the JavaScript and TypeScript references)
  • React: components, props, state, hooks (see the React reference)
  • The Server Components model and the 'use client' and 'use server' directives (see the React reference, section “Server Components and Server Functions”)
  • HTTP: methods, status codes, headers, cookies (see the HTTP and REST reference)

Section sources

the section is written from these pages

Cheat sheet: files and commands

Files, folders, functions and commands for everyday use; each line is explained in detail in its own section.

Special files

TaskFile
Make a URL serve a pagepage.tsx
Shared wrapper for a folder’s pages: header, menulayout.tsx
Placeholder while the page rendersloading.tsx
Catch an error in a segmenterror.tsx
Catch an error in the root layoutglobal-error.tsx
“Not found” pagenot-found.tsx
A custom HTTP endpointroute.ts
A wrapper that is re-created on every navigationtemplate.tsx
Fallback page for a parallel route slotdefault.tsx
Code that runs before a request is handled: redirects, headersproxy.ts in the project root or in src/
Next.js configurationnext.config.ts

Folders and segments

FolderWhat it means
blogthe URL segment /blog
[slug]dynamic segment: /blog/hello → { slug: 'hello' }
[...slug]all following segments: /shop/a/b → { slug: ['a', 'b'] }
[[...slug]]the same, plus the URL without the segment: /shop → { slug: undefined }
(marketing)route group: not part of the URL
_componentsprivate folder: not a route
@modalparallel route slot
(.)photointercepts a route at the same level

Functions

TaskHow to write it
Read a cookie on the server(await cookies()).get('theme')
Read a request header(await headers()).get('user-agent')
Redirectredirect('/login')
Show the 404 pagenotFound()
Expire a cache tag immediately, in a Server ActionupdateTag('posts')
Refresh a cache tag in the backgroundrevalidateTag('posts', 'max')
Revalidate a pathrevalidatePath('/blog')
Re-render the current page from a Server Actionrefresh()
Page title and description based on dataexport async function generateMetadata()
Dynamic segment values for the buildexport async function generateStaticParams()

Directives

TaskHow to write it
A component with state and events'use client' as the first line of the file
Server Function'use server' at the top of a function or file
Cache a function or component'use cache' and cacheLife('hours')
Cache for a function that reads cookies itself'use cache: private'
Prevent a module from being imported into client codeimport 'server-only'

Commands

TaskCommand
Create a projectnpx create-next-app@latest my-app --yes
Start the development servernpm run dev
Development server on a different portnpm run dev -- -p 4000
Build for productionnpm run build
Run the built appnpm run start
Generate route types without a buildnpx next typegen
System information for a bug reportnpx next info
Upgrade Next.jsnpx next upgrade
Debug server codenpm run dev -- --inspect

Section sources

the section is written from these pages

Installation and first run

create-next-app creates a new project: npx create-next-app@latest my-app --yes uses the recommended settings and installs dependencies straight away. To check the result, run npm run dev in the project directory and open http://localhost:3000 in a browser.

Requirements

You need Node.js 20.9 or later; macOS, Windows (including WSL) and Linux are supported. TypeScript must be 5.1 or later. For how to install Node.js, see the Node.js reference, section “Installation and first run”.

bashin a terminal
node --version

Browsers supported without extra configuration: Chrome, Edge and Firefox 111+, Safari 16.4+.

Creating a project

bashin a terminal
npx create-next-app@latest my-app --yescd my-appnpm run dev

The --yes flag skips the prompts and uses your saved or the recommended settings. Without it, the wizard asks about TypeScript, the linter, React Compiler, Tailwind CSS, the src/ directory, the App Router, Cache Components and the import alias.

SettingRecommended value
TypeScriptenabled
LinterESLint; Biome or no linter as alternatives
Tailwind CSSenabled
RouterApp Router
Cache Components and Partial Prefetchingenabled: cacheComponents and partialPrefetching in next.config.ts
BundlerTurbopack
React Compilerdisabled
src/ directoryno
Import alias@/*

Your first project

textproject structure
my-app/├── app/│   ├── favicon.ico│   ├── globals.css│   ├── layout.tsx│   └── page.tsx├── public/├── eslint.config.mjs├── next-env.d.ts├── next.config.ts├── package.json├── postcss.config.mjs└── tsconfig.json
FilePurpose
app/layout.tsxthe root layout: required, and contains the <html> and <body> tags
app/page.tsxthe home page, at /
public/static files: public/logo.png is served at /logo.png
next.config.tsNext.js configuration
package.jsondependencies and scripts
next-env.d.tsNext.js types for TypeScript; generated automatically and not committed to Git

You can move the application code, together with app/, into a src/ directory to keep it separate from the configuration files in the project root.

Scripts

jsonpackage.json
{  "scripts": {    "dev": "next dev",    "build": "next build",    "start": "next start",    "lint": "eslint"  }}

npm run dev starts the development server with Turbopack, and the page updates when you save a file. npm run build creates a production build and npm run start runs it; next start does not work without a build. Run the linter yourself: since Next.js 16, next build no longer does.

The default port is 3000. Set another one with the -p flag or the PORT environment variable, but not in a .env file: the server starts before those variables are loaded. With npm run, pass flags for next after --:

bashin the project directory
npm run dev -- -p 4000

Configuration

Next.js is configured in next.config.ts in the project root. In a new project, Cache Components and Partial Prefetching are already enabled there:

typescriptnext.config.ts
import type { NextConfig } from 'next' const nextConfig: NextConfig = {  cacheComponents: true,  partialPrefetching: true,} export default nextConfig

Other next commands

  • npx next info prints details about your OS, the Node.js version, package managers and the next, react and react-dom packages. Attach the output to a bug report.
  • npx next typegen generates route types without a full build, for example before tsc --noEmit in CI.
  • npx next upgrade updates Next.js to the latest version in the release channel you have installed.

Manual installation

To skip the wizard, install the packages with npm install next@latest react@latest react-dom@latest, add the dev, build and start scripts, and create app/layout.tsx and app/page.tsx. If there is no root layout, next dev creates one for you.

Section sources

the section is written from these pages

Routes, layouts and navigation

In the App Router, routes are defined by folders: each folder inside app/ is a URL segment, and a page.tsx file makes the URL accessible. A layout in layout.tsx wraps all pages in its folder and does not re-render on navigation, so it keeps its state.

Nested folders create nested UI. The root app/layout.tsx is required and contains <html> and <body>; it wraps app/blog/layout.tsx, which in turn wraps the pages of that section. So /blog/hello gets both layouts, while / gets only the root one.

Each folder’s layout wraps everything below it; the dynamic segment is highlighted.
tsxapp/blog/layout.tsx
export default function BlogLayout({  children,}: {  children: React.ReactNode}) {  return (    <section>      <nav>Blog sections</nav>      {children}    </section>  )}

Dynamic segments

A folder in square brackets is a dynamic segment: app/blog/[slug]/page.tsx handles /blog/hello and any other URL of the form /blog/…. The value arrives in the params prop. It is a Promise, so make the component async and await it.

tsxapp/blog/[slug]/page.tsx
import { notFound } from 'next/navigation'import { getPost } from '@/lib/posts' export default async function PostPage({  params,}: {  params: Promise<{ slug: string }>}) {  const { slug } = await params  const post = await getPost(slug)  if (!post) notFound()   return (    <article>      <h1>{post.title}</h1>      <p>{post.content}</p>    </article>  )}

Put a loading.tsx next to it. Next.js wraps the page in a <Suspense> boundary, shows the fallback immediately on navigation and can prefetch the shared layouts. Without such a boundary, in a project with Cache Components a page that awaits params or data causes an error; see the section “Common errors and troubleshooting”.

tsxapp/blog/[slug]/loading.tsx
export default function Loading() {  return <p>Loading post...</p>}

If the segment values are known in advance, return them from generateStaticParams: Next.js renders those pages at build time instead of at request time.

tsxapp/blog/[slug]/page.tsx
export async function generateStaticParams() {  const posts = await getPosts()  return posts.map((post) => ({ slug: post.slug }))}
FolderURLs
app/blog/[slug]//blog/my-first-post
app/shop/[...slug]//shop/clothing, /shop/clothing/shirts
app/docs/[[...slug]]//docs and everything below it
app/(marketing)/about//about: the group is not part of the URL
app/blog/_components/none: a private folder

Groups, slots and interception

  • (marketing) is a route group: it organises folders and gives some pages their own layout without changing the URL.
  • _components is a private folder: Next.js excludes it and everything inside from routing. Handy for a section’s components and utilities.
  • @modal is a parallel route slot: the parent layout renders it alongside the main page.
  • (.)photo is an intercepting route: it shows another route inside the current layout while the URL changes to match, for example a detail card in a modal over a list.
  • template.tsx is like a layout, but it is re-created on every navigation.
  • default.tsx is the fallback page for a parallel route slot.

Links and navigation

Use the <Link> component from next/link for navigation: it is an <a> tag with prefetching and client-side transitions. Shared layouts are not re-rendered, and the page changes without a full reload.

tsxapp/ui/post-list.tsx
import Link from 'next/link' export function PostList({  posts,}: {  posts: { slug: string; title: string }[]}) {  return (    <ul>      {posts.map((post) => (        <li key={post.slug}>          <Link href={`/blog/${post.slug}`}>{post.title}</Link>        </li>      ))}    </ul>  )}

<Link> prefetches a route when the link enters the viewport; a plain <a> does not. A static route is prefetched in full, a dynamic one up to the nearest loading.tsx, and without one prefetching is skipped. For long lists of links, turn it off with prefetch={false}. In projects with Partial Prefetching the default behaviour differs; see the section “Caching and revalidation”.

Client Components have hooks from next/navigation: usePathname returns the current path, useSearchParams returns the query string parameters, and useRouter is for navigating from code. In server code, redirect() from the same module does the job: it throws a special exception and stops the segment from rendering. For details, see the section “Fetching and mutating data”.

A server page receives the query string in the searchParams prop, which is also a Promise. Reading it makes the page dynamic: it renders on every request. If you only need the parameters to filter a list that is already loaded, read them in a Client Component with useSearchParams.

Loading, errors and 404

FileWhen it is shown
loading.tsxwhile the segment’s page renders: Next.js wraps it in <Suspense>
error.tsxon an unhandled error in the segment or its nested segments
not-found.tsxwhen a page calls notFound()
global-error.tsxon an error in the root layout; contains its own <html> and <body>
tsxapp/blog/error.tsx
'use client' import { useEffect } from 'react' export default function BlogError({  error,  retry,}: {  error: unknown  retry: () => void}) {  useEffect(() => {    // send the error to your monitoring system    console.error(error)  }, [error])   return (    <div>      <p>Could not load the blog.</p>      <button onClick={() => retry()}>Try again</button>    </div>  )}

error.tsx is always a Client Component. The retry() function re-fetches and re-renders the segment’s content. An error bubbles up to the nearest error.tsx above it in the tree, so these files are placed at different levels. Expected errors, such as invalid form input, are returned as values rather than thrown.

Metadata and OG images

Set the page title and the description for search engines with a metadata object exported from layout.tsx or page.tsx, or with a generateMetadata function if they depend on data. Both work only in Server Components. Next.js adds the charset and viewport tags itself.

tsxapp/blog/[slug]/page.tsx
import type { Metadata } from 'next'import { getPost } from '@/lib/posts' export async function generateMetadata({  params,}: {  params: Promise<{ slug: string }>}): Promise<Metadata> {  const { slug } = await params  const post = await getPost(slug)  return { title: post.title, description: post.excerpt }}

If getPost is called in both the metadata and the page, wrap it in React’s cache so the data is fetched once. Put a social sharing image in the route folder as opengraph-image.jpg, or generate it in opengraph-image.tsx with ImageResponse from next/og; a file in a deeper folder takes precedence over one higher up.

Section sources

the section is written from these pages

Rendering: server, client and prerendering

Components in app/ are Server Components by default: they run on the server, read data and add no JavaScript to the browser. Mark a Client Component with the 'use client' directive when you need state, event handlers or browser APIs.

What you needComponent
Fetch data from a database or APIServer
Use API keys and other secretsServer
Reduce JavaScript in the browserServer
State and handlers: useState, onClickClient
Effects: useEffectClient
Browser APIs: localStorage, windowClient

How it works in Next.js

On the server, Next.js renders each route segment separately. Server Components become the RSC payload (React Server Component Payload), a compact description of the tree: the output of the Server Components, placeholders for Client Components with references to their JavaScript, and the props passed to them. The HTML is built from the RSC payload and the Client Components.

On the first load, the browser shows this HTML straight away, still non-interactive. The RSC payload reconciles the Server and Client Component trees, and JavaScript performs hydration, attaching the event handlers. On later navigations the RSC payload is prefetched and cached, and Client Components render in the browser without server HTML.

ComponentOn the serverIn the browser
Serveryesno: its code never reaches the browser
Clientyes: HTML on the first loadyes: hydration and updates

“Client” does not mean “browser only”: when a page is requested directly, a Client Component is rendered to HTML on the server and again in the browser during hydration.

The 'use client' boundary

Put the 'use client' directive on the first line of the file, before any imports. It draws a boundary: everything the file imports ends up in the client bundle, so you don’t need to add it to every file. To keep the bundle small, mark only the interactive parts: the search bar, not the whole header.

tsxapp/ui/like-button.tsx
'use client' import { useState } from 'react' export default function LikeButton({ likes }: { likes: number }) {  const [count, setCount] = useState(likes)  return (    <button onClick={() => setCount(count + 1)}>      {count} likes    </button>  )}
tsxapp/page.tsx
import LikeButton from '@/app/ui/like-button' export default function Page() {  return (    <main>      <h1>Hello, Next.js</h1>      <LikeButton likes={0} />    </main>  )}

A Server Component passes data to a Client Component through props, and the data must be serialisable: strings, numbers, plain objects and arrays, promises. You can’t pass a handler function; Next.js reports an error. The exception is a Server Function marked with 'use server', which is passed to the client as a reference to the server.

A Server Component inside a Client Component

A Client Component can’t import a Server Component, but it can receive one already rendered through children or another prop. The Server Component is rendered on the server, and the Client Component gets only the result and places it in its own output.

tsxapp/ui/modal.tsx
'use client' import { useState } from 'react' export function Modal({ children }: { children: React.ReactNode }) {  const [open, setOpen] = useState(false)  return (    <>      <button onClick={() => setOpen(true)}>Open cart</button>      {open && <div role="dialog">{children}</div>}    </>  )}
tsxapp/page.tsx
import { Modal } from './ui/modal'import { Cart } from './ui/cart' // Cart is a Server Component, Modal is a Client Componentexport default function Page() {  return (    <Modal>      <Cart />    </Modal>  )}

Context providers work the same way. React context doesn’t work in Server Components, so make the provider a Client Component that takes children, and place it in the layout as deep as possible: around {children}, not around the whole <html>.

Prerendering and the static shell

With Cache Components (enabled in new projects), Next.js renders a route ahead of time, at build time. This is prerendering. Everything that doesn’t depend on the request goes into the static shell: layouts, navigation, cached data and the fallbacks of <Suspense> boundaries. The shell is sent immediately, and the content of boundaries that need request data is streamed in the same response.

Green marks what goes into the static shell at build time.
tsxapp/shop/page.tsx
import { Suspense } from 'react'import { cookies } from 'next/headers'import { cacheLife } from 'next/cache' async function Catalogue() {  'use cache'  cacheLife('hours')  const res = await fetch('https://api.example.com/products')  const products: { id: string; name: string }[] = await res.json()  return (    <ul>      {products.map((p) => <li key={p.id}>{p.name}</li>)}    </ul>  )} async function Cart() {  const count = (await cookies()).get('cart-count')?.value ?? '0'  return <p>Cart: {count}</p>} export default function ShopPage() {  return (    <>      <nav>Logo · Menu</nav>      <Catalogue />      <Suspense fallback={<p>Cart: …</p>}>        <Cart />      </Suspense>    </>  )}

If you take Cart out of <Suspense>, the build stops: when Next.js meets work that needs the request, it looks up the tree for the nearest <Suspense> boundary and reports an error if there isn’t one. This forces you to decide explicitly whether to cache the data with 'use cache' or to stream it.

The deeper in the tree you read cookies(), headers(), params or searchParams, the more of the page ends up in the shell. Don’t await them at the top of a layout: pass the promise down and await it inside a <Suspense> boundary.

Streaming: loading.tsx and <Suspense>

Streaming sends the page in pieces as they become ready. loading.tsx wraps the whole segment page in a single <Suspense> boundary: the layout appears immediately, with a fallback in place of the page. Your own <Suspense> boundaries are more precise: each fills in independently, in the order its data is ready.

Aspectloading.tsx<Suspense>
Scopethe whole segment pageany component
How to add itput the file next to page.tsxwrap the component
On navigationthe fallback is prefetched and shown at oncenot prefetched by default
When to use itthe page has nothing to show without dataalmost always: more precise, and more goes into the shell

server-only: protection against leaks

A module with secrets can accidentally be imported into a Client Component. Environment variables without the NEXT_PUBLIC_ prefix become an empty string in the browser, so the code simply fails. The line import 'server-only' at the top of a module turns such an import into a build error; for code that runs only in the browser, there is client-only.

typescriptlib/stats.ts
import 'server-only' export async function getStats() {  const res = await fetch('https://api.example.com/stats', {    headers: { authorization: `Bearer ${process.env.API_KEY}` },  })  return res.json()}

You don’t have to install the server-only package: Next.js handles this import itself. Install it with npm install server-only if your linter complains about an unknown dependency.

Section sources

the section is written from these pages

Fetching and mutating data

Fetch data for a page directly in a Server Component: make it async and await a fetch or a database query. Mutate data with Server Functions, which are asynchronous functions marked 'use server' that the browser calls from a form or an event handler.

Fetching in a Server Component

tsxapp/blog/page.tsx
import { Suspense } from 'react'import { db, posts } from '@/lib/db' async function PostList() {  const allPosts = await db.select().from(posts)  return (    <ul>      {allPosts.map((post) => (        <li key={post.id}>{post.title}</li>      ))}    </ul>  )} export default function BlogPage() {  return (    <main>      <h1>Blog</h1>      <Suspense fallback={<p>Loading posts...</p>}>        <PostList />      </Suspense>    </main>  )}

Credentials and the text of database queries stay on the server and never reach the browser. Still check the user’s permissions; see the “Security” section for details. While the list loads, <Suspense> shows a fallback and the rest of the page is already visible.

Identical fetch calls within a single render run only once, so you can load data in the component that needs it instead of passing it through props. fetch is not cached between requests by default; for how to cache a result, see “Caching and revalidation”.

Sequential and parallel requests

Two awaits in a row run sequentially: the second request waits for the first. If the requests don’t depend on each other, start both at once and wait for them together with Promise.all.

tsxapp/artist/[id]/artist-info.tsx
async function ArtistInfo({ id }: { id: string }) {  // both requests start at once; we wait for them together  const [artist, albums] = await Promise.all([    getArtist(id),    getAlbums(id),  ])  return (    <section>      <h1>{artist.name}</h1>      <p>{albums.length} albums</p>    </section>  )}

If one of the requests fails, Promise.all rejects as a whole. When you also need partial results, use Promise.allSettled.

React.cache for repeated calls

Requests that don’t go through fetch, such as an ORM or a database client, aren’t deduplicated on their own. Wrap the function in React’s cache: within a single request, calls with the same arguments return one result, so you can call the function from several components. cache stores nothing between requests.

typescriptlib/user.ts
import { cache } from 'react'import { db } from '@/lib/db' export const getUser = cache(async (id: string) => {  return db.user.findUnique({ where: { id } })})

Fetching in a Client Component

A Client Component can read a promise started by a Server Component: the server calls the function without await and passes the promise as a prop, and the client reads it with React’s use inside <Suspense>. Load data that depends on user actions or browser APIs in the browser, using a library such as SWR or React Query.

tsxapp/blog/page.tsx
import { Suspense } from 'react'import { Posts } from '@/app/ui/posts'import { getPosts } from '@/lib/posts' export default function Page() {  // no await: the promise goes to the Client Component  const posts = getPosts()  return (    <Suspense fallback={<p>Loading...</p>}>      <Posts posts={posts} />    </Suspense>  )}
tsxapp/ui/posts.tsx
'use client' import { use } from 'react' export function Posts({  posts,}: {  posts: Promise<{ id: string; title: string }[]>}) {  const allPosts = use(posts)  return (    <ul>      {allPosts.map((post) => (        <li key={post.id}>{post.title}</li>      ))}    </ul>  )}

Mutating data: Server Functions

A Server Function is an asynchronous function that runs on the server and is called from the browser with a network POST request. It is marked with the 'use server' directive at the top of the function or file. When such a function is passed to a form’s action or called inside a transition, it is called a Server Action.

typescriptapp/actions.ts
'use server' import { revalidatePath } from 'next/cache'import { redirect } from 'next/navigation'import { auth } from '@/lib/auth'import { db } from '@/lib/db' export async function createPost(formData: FormData) {  const session = await auth()  if (!session?.user) throw new Error('Unauthorized')   const title = String(formData.get('title') ?? '')  const post = await db.post.create({    data: { title, authorId: session.user.id },  })   revalidatePath('/blog')  redirect(`/blog/${post.id}`)}
tsxapp/blog/new/page.tsx
import { createPost } from '@/app/actions' export default function NewPostPage() {  return (    <form action={createPost}>      <input name="title" required />      <button type="submit">Publish</button>    </form>  )}

A form with a Server Action in a Server Component works even without JavaScript: the browser submits it as an ordinary request. The function receives FormData; bind extra arguments, such as a record id, with bind: updatePost.bind(null, id).

In a Client Component, call a Server Function from an event handler or an effect. You can’t declare one in a client file, only import it from a file with 'use server'. The browser sends Server Actions one at a time: the next waits for the previous to finish, so they are not suitable for fetching data.

What to do after a mutation

CallWhat it does
updateTag('posts')immediately expires cache entries with that tag; the next render waits for fresh data. Server Actions only
revalidatePath('/blog')invalidates the cache for the whole path
refresh()re-renders the current page without touching the cache
redirect('/blog')sends the user to another URL; code after the call doesn’t run

After updateTag, revalidatePath, refresh and cookie changes, Next.js sends the updated page in the same response, so no separate request for fresh data is needed. Call redirect last: it throws a special exception, and everything after it is skipped.

React’s useActionState hook shows the pending state and form errors: it returns the function’s result and an isPending flag. For details, see the React reference, section “Actions and forms”.

Section sources

the section is written from these pages

Caching and revalidation

In the Cache Components model, Next.js caches nothing on its own: data is fetched on every request until you mark a function or component with the 'use cache' directive. cacheLife sets how long an entry lives, and after the data changes you can invalidate it by the tag set with cacheTag.

The model is enabled with cacheComponents: true in next.config.ts; the documentation also tells you to set partialPrefetching: true explicitly, otherwise Next.js prints a warning. In projects created with create-next-app, both settings are already in place. Without cacheComponents, the previous model applies: fetch with cache: 'force-cache', unstable_cache and segment options such as export const dynamic. It is described on the official “Caching and Revalidating (Previous Model)” page and isn’t covered here.

Where to put 'use cache'

The directive works at two levels. At the data level, put it on the first line of a function that fetches or computes data, so the result can serve several components. At the UI level, put it on the first line of a component, page or layout, and the rendered markup is cached. A directive at the top of a file caches all of its exports. A cached function must be async.

typescriptlib/products.ts
import { cacheLife, cacheTag } from 'next/cache'import { db } from '@/lib/db' export async function getProducts(category: string) {  'use cache'  cacheLife('hours')  cacheTag('products')  return db.product.findMany({ where: { category } })}

The cache key is built from the build ID, the function ID and the arguments. So getProducts('books') and getProducts('games') are stored separately, and variables captured from the outer scope are part of the key too. Arguments and the result must be serialisable: class instances, Symbol and URL don’t qualify.

How long an entry lives: cacheLife

cacheLife sets three lifetimes. stale is how long the browser uses an entry without asking the server. revalidate is the age after which the next request gets the old entry while the server refreshes it in the background. expire is the idle time after which a request waits for fresh data. Set cacheLife in every cached function: without it the default profile applies, and the lifetime isn’t visible in the code.

Profilestalerevalidateexpire
default5 min15 minnever
seconds30 s1 s1 min
minutes5 min1 min1 h
hours5 min1 h1 day
days5 min1 day1 week
weeks5 min1 week30 days
max5 min30 days1 year

Set a custom lifetime with an object in seconds, as in cacheLife({ stale: 300, revalidate: 3600, expire: 86400 }), or with a named profile in the cacheLife key of next.config.ts. A lifetime that is too short (the seconds profile, revalidate: 0, or expire under 5 minutes) excludes the entry from prerendering: such a block is computed on every request.

Invalidating by tag: updateTag and revalidateTag

Attach a tag inside the cached function: cacheTag('products'). You can invalidate all entries with that tag immediately or in the background:

AspectupdateTagrevalidateTag
Where to call itServer Actions onlyServer Actions and Route Handlers
What happensthe entry expires immediately, and the next request waits for fresh datathe entry becomes stale: it is still served while a new one is prepared in the background
CallupdateTag('products')revalidateTag('products', 'max')
When to use itthe user must see their own change straight awaya catalogue, articles, a CMS webhook: a small delay is acceptable

revalidatePath('/products') invalidates all cached data for a path, for when you don’t know which tags it uses. The documentation recommends tags where possible: they are more precise and don’t invalidate more than needed.

A worked example: a product catalogue

A list of books is cached for an hour and tagged products. When a user adds a product, the Server Action invalidates the tag immediately, and the response to the form already contains the new list.

updateTag invalidates the entry immediately; revalidateTag with the max profile would serve the old entry and refresh it in the background.
tsxapp/products/page.tsx
import { getProducts } from '@/lib/products'import { addProduct } from './actions' export default async function ProductsPage() {  const products = await getProducts('books')  return (    <main>      <ul>        {products.map((p) => (          <li key={p.id}>{p.name}</li>        ))}      </ul>      <form action={addProduct}>        <input name="name" required />        <button type="submit">Add</button>      </form>    </main>  )}
typescriptapp/products/actions.ts
'use server' import { updateTag } from 'next/cache'import { requireAdmin } from '@/lib/auth'import { db } from '@/lib/db' export async function addProduct(formData: FormData) {  await requireAdmin()  await db.product.create({    data: { name: String(formData.get('name')), category: 'books' },  })  updateTag('products')}
  1. First request: there is no entry, so getProducts queries the database and stores the result with the products tag for the lifetime of the hours profile.
  2. Later requests within the hour get the list from the cache, without touching the database.
  3. The form calls addProduct, and the product is written to the database.
  4. updateTag('products') immediately expires all entries with that tag.
  5. Next.js re-renders the page in the same response: the old entry isn’t used, and the render waits for a fresh list from the database.

If products are added not by a user but by an import or a CMS webhook, call revalidateTag('products', 'max') in a Route Handler: visitors get the old list while a new one is built in the background.

What not to cache

Inside 'use cache' you can’t call cookies() or headers(), or read searchParams, either in the function itself or in anything it calls. Read the value outside and pass it as an argument: it becomes part of the cache key, and each value gets its own entry.

For a function that reads cookies or headers itself, there is 'use cache: private'. Its result isn’t kept in the server cache between requests and lives only in the browser’s memory for the stale period, so personal data never ends up in a cache shared by all readers.

Math.random(), Date.now() and crypto.randomUUID() return a new value every time, so Next.js requires an explicit decision: cache the result, or call await connection() from next/server before them, inside <Suspense>, so that the value is computed on every request.

Prefetching with Partial Prefetching

With partialPrefetching: true, the <Link> component by default prefetches not the whole page but the route’s App Shell: the static and cached content that doesn’t depend on URL parameters. One shell serves all links to the route. To prefetch data that depends on a particular link’s params or searchParams, set prefetch={true}: this is a separate server call for each such link.

Where the cache is stored

By default, 'use cache' entries live in the memory of each server instance; on serverless platforms they may not survive until the next request. A new deployment starts with an empty cache, because the build ID is part of the key. 'use cache: remote' with the platform’s cache handler provides a cache shared across instances, but every access to it is a network request.

Section sources

the section is written from these pages

Route Handlers

A Route Handler is your own HTTP endpoint inside the app: a route.ts file in the app/ folder that exports functions named after HTTP methods, such as GET and POST. It takes a Web API Request and returns a Response, so it suits JSON APIs, webhooks and non-HTML responses.

typescriptapp/api/posts/route.ts
import { db } from '@/lib/db' export async function GET() {  const posts = await db.post.findMany({ take: 20 })  return Response.json(posts)} export async function POST(request: Request) {  const body = await request.json()  // check the session and the body fields before writing  const post = await db.post.create({ data: { title: body.title } })  return Response.json(post, { status: 201 })}

The supported methods are GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS; for any other method Next.js responds with 405 Method Not Allowed. If OPTIONS isn’t declared, Next.js adds it automatically with an Allow header. A route.ts and a page.tsx can’t be in the same folder, because that is a conflict at one route level; in nested folders, such as app/api/route.ts next to app/page.tsx, both files coexist.

The request: parameters, body, cookies

The handler’s first argument is a NextRequest, an extension of Request. Query string parameters are in request.nextUrl.searchParams, and cookies in request.cookies. Read the body with the standard methods request.json(), request.formData() or request.text().

typescriptapp/api/search/route.ts
import type { NextRequest } from 'next/server' export function GET(request: NextRequest) {  const query = request.nextUrl.searchParams.get('q') ?? ''  const theme = request.cookies.get('theme')?.value ?? 'light'  return Response.json({ query, theme })}

You can also read cookies and headers with the cookies() and headers() functions from next/headers. Headers from headers() are read-only: to set response headers, return a new Response that includes them.

Dynamic segments

The second argument is the context. It holds params, a promise with the dynamic segment parameters of the URL. Next.js generates the context type itself, through the global RouteContext helper.

typescriptapp/api/users/[id]/route.ts
import type { NextRequest } from 'next/server' export async function GET(  _request: NextRequest,  ctx: RouteContext<'/api/users/[id]'>) {  const { id } = await ctx.params  return Response.json({ id })}

The response: Response and NextResponse

The response is an ordinary Response: Response.json(data, { status }) for JSON, and new Response(body, { headers }) for text, XML or a stream. NextResponse from next/server adds conveniences: NextResponse.json(), NextResponse.redirect() and handling of response cookies.

typescriptapp/api/theme/route.ts
import { NextResponse } from 'next/server' export async function POST(request: Request) {  const { theme } = await request.json()  if (theme !== 'light' && theme !== 'dark') {    return NextResponse.json({ error: 'unknown theme' }, { status: 400 })  }  const response = NextResponse.json({ theme })  response.cookies.set('theme', theme)  return response}

Caching GET

Route Handlers aren’t cached by default, and methods other than GET are never cached. With Cache Components, GET follows the same prerendering model as pages: a handler that uses no request data and no uncached data runs at build time. Reading request, cookies() or headers(), querying a database, or calling Math.random() moves it to request time. To cache data, use a helper function with 'use cache': the directive doesn’t work directly in the handler body.

typescriptapp/api/products/route.ts
import { cacheLife } from 'next/cache'import { db } from '@/lib/db' async function getProducts() {  'use cache'  cacheLife('hours')  return db.product.findMany()} export async function GET() {  return Response.json(await getProducts())}

Route Handler or Server Function

TaskWhat to choose
A form or button in your interface changes dataServer Function
A mobile app, another service or a partner calls your APIRoute Handler
A webhook from a payment system or CMSRoute Handler
The response isn’t HTML: JSON, RSS, a file, a streamRoute Handler
A Server Component fetches dataneither: query the source directly

Don’t call your own Route Handlers from Server Components. At request time this is an extra HTTP request, and at build time the server isn’t running yet, so prerendering fails. Server Actions run one at a time, so they aren’t suitable for fetching data either.

Section sources

the section is written from these pages

Proxy (formerly middleware)

Proxy is a function in a proxy.ts file that runs on the server before a route is rendered. For an incoming request, it can redirect it, rewrite the URL, modify request or response headers, or respond directly. In Next.js 16 it is the new name for middleware; the capabilities are the same.

typescriptproxy.ts
import { NextResponse } from 'next/server'import type { NextRequest } from 'next/server' export function proxy(request: NextRequest) {  const session = request.cookies.get('session')?.value  if (!session) {    return NextResponse.redirect(new URL('/login', request.url))  }  return NextResponse.next()} export const config = {  matcher: ['/dashboard/:path*', '/settings/:path*'],}

There is one file per project, located in the root next to app/, or inside src/ if you use that folder. Export the function either as a named proxy export or as the default export. You can split the logic into modules and import them into proxy.ts.

matcher: which URLs proxy runs on

Without matcher, proxy runs on every request, including those for _next/static, _next/image and files in public/, so a sign-in check can block CSS and images. Specify paths as a string, an array or a regular expression with exclusions. matcher values must be constants, because Next.js reads them at build time.

typescriptproxy.ts
export const config = {  matcher: [    // all paths except the API, static files, images and the favicon    '/((?!api|_next/static|_next/image|favicon.ico).*)',  ],}
PatternMatches
'/about'only /about and /about/: the whole path is compared, not just the start
'/about/:path'/about/a, but not /about/a/c
'/about/:path*'/about/a/b/c: * means zero or more segments
['/about', '/contact']both URLs

What to do in proxy, and what not to

  • Good fits: redirects and rewrites based on request properties, A/B tests, headers for all pages or some of them, a quick check of the session cookie with a redirect to the sign-in page.
  • Poor fits: slow database and API queries, because proxy runs on every route, including link prefetching, and full permission checks.
  • Simple redirects that don’t depend on the request are easier to define in redirects in next.config.ts.
  • fetch with the cache, next.revalidate or next.tags options caches nothing in proxy.

Rewrites and headers

typescriptproxy.ts
import { NextResponse } from 'next/server'import type { NextRequest } from 'next/server' export function proxy(request: NextRequest) {  // the URL in the browser stays the same; /about-v2 serves the response  if (request.nextUrl.pathname === '/about') {    return NextResponse.rewrite(new URL('/about-v2', request.url))  }  const headers = new Headers(request.headers)  headers.set('x-pathname', request.nextUrl.pathname)  // the app receives the header, but the browser does not  return NextResponse.next({ request: { headers } })}

NextResponse.next({ request: { headers } }) passes the modified headers on to the app. The NextResponse.next({ headers }) form would send them to the browser, which you must not do with internal data. A web server may reject headers that are too large with a 431 error.

Request processing order

  1. headers from next.config.ts
  2. redirects from next.config.ts
  3. Proxy: rewrites, redirects, responses
  4. beforeFiles rewrites from next.config.ts
  5. File-system routes: public/, _next/static/, app/
  6. afterFiles rewrites
  7. Dynamic routes, such as /blog/[slug]
  8. fallback rewrites

Migrating from middleware

In Next.js 16 the middleware convention is deprecated and renamed to proxy: the new name makes clear that this is a network boundary in front of the app, not Express-style middleware. A codemod renames the file and the function:

bashin the project folder
npx @next/codemod@canary middleware-to-proxy .

Options with middleware in their names have been renamed too: for example, skipMiddlewareUrlNormalize is now skipProxyUrlNormalize. If you keep middleware.ts, Next.js warns that the convention is deprecated; the “Renaming Middleware to Proxy” page explains why.

Runtime

Proxy runs in the Node.js runtime. The runtime option is not available in a proxy file: if you set it, Next.js throws an error. Any authorisation and session libraries you call in proxy must work in Node.js.

Section sources

the section is written from these pages

Images, fonts and scripts

The next/image, next/font and next/script components load images, fonts and third-party scripts so that the page doesn’t jump around or wait for anything unnecessary. <Image> resizes an image for the screen and serves it as WebP, next/font hosts fonts on your own domain, and <Script> defers other people’s JavaScript.

Images: next/image

tsxapp/page.tsx
import Image from 'next/image'import hero from './hero.jpg' export default function Page() {  return (    <>      <Image src={hero} alt="Our office" loading="eager" />      <Image        src="/team.png"        alt="Our team"        width={800}        height={533}      />    </>  )}

alt is required. Dimensions are needed so the browser can reserve space in advance and the page doesn’t jump: with a static import, Next.js works them out itself, while for a string URL you set width and height, or fill. Images are lazy-loaded by default, when they approach the viewport.

For the main image above the fold (the LCP element), turn off lazy loading with loading="eager" or fetchPriority="high". The preload prop inserts a <link> into <head> and is useful when an image needs to start loading before its markup is reached. The priority prop is deprecated as of Next.js 16; use preload instead.

tsxapp/ui/card.tsx
import Image from 'next/image' export function Card({ src, title }: { src: string; title: string }) {  return (    <div style={{ position: 'relative', aspectRatio: '4 / 3' }}>      <Image        src={src}        alt={title}        fill        sizes="(max-width: 768px) 100vw, 33vw"        style={{ objectFit: 'cover' }}      />    </div>  )}

fill stretches the image to its parent, and the parent must have position: relative, fixed or absolute. sizes tells the browser how wide the image will be on different screens: without it, the browser assumes the image is full screen width (100vw) and may download more than it needs.

Remote images: remotePatterns

Next.js optimises an image from another server only if its URL is allowed in images.remotePatterns. Make the patterns as narrow as possible: protocol, host and path. A URL that matches no pattern gets a 400 Bad Request response.

typescriptnext.config.ts
import type { NextConfig } from 'next' const nextConfig: NextConfig = {  images: {    remotePatterns: [new URL('https://cdn.example.com/photos/**')],  },} export default nextConfig

In patterns, * matches a single path segment or a single subdomain, and ** matches any number of segments at the end of a path or subdomains at the start of a host. Replace the deprecated images.domains with remotePatterns.

Fonts: next/font

next/font serves fonts from your own domain as static files: the browser doesn’t contact Google, and the page doesn’t jump when the fallback font is swapped. Load a font in the root layout so that it applies across the whole app. Import Google Fonts from next/font/google, and use the localFont function from next/font/local for your own files.

tsxapp/layout.tsx
import { Inter } from 'next/font/google'import localFont from 'next/font/local' const inter = Inter({ subsets: ['latin', 'cyrillic'] })const brand = localFont({  src: './fonts/brand.woff2',  variable: '--font-brand',}) export default function RootLayout({  children,}: {  children: React.ReactNode}) {  return (    <html lang="ru" className={`${inter.className} ${brand.variable}`}>      <body>{children}</body>    </html>  )}

display is 'swap' by default: while the font loads, the text is shown in a fallback font. variable declares a CSS variable, which you use in CSS or Tailwind instead of className. For a font without a variable version, set weight.

Third-party scripts: next/script

Load analytics, widgets and other external scripts with the <Script> component from next/script, in the layout or page that needs them: Next.js loads the script only once, even when users navigate between pages of that layout. The strategy prop sets when to load it.

strategyWhen it loads
beforeInteractivebefore any Next.js code and before hydration
afterInteractivethe default: early, but after some of hydration
lazyOnloadlater, when the browser is idle
workerin a web worker; experimental and does not yet work with the App Router
tsxapp/dashboard/layout.tsx
import Script from 'next/script' export default function DashboardLayout({  children,}: {  children: React.ReactNode}) {  return (    <>      <section>{children}</section>      <Script src="https://example.com/chat.js" strategy="lazyOnload" />    </>  )}

The onLoad, onReady and onError handlers work only in a Client Component. An inline script, whose code is written directly inside <Script>, requires an id.

Section sources

the section is written from these pages

Build and deployment

next build creates a production build, and next start runs it on a Node.js server, which supports every Next.js feature. For Docker, enable output: 'standalone': the build puts a minimal server.js server, with only the files it needs, in .next/standalone.

MethodWhat is supported
Node.js server: next starteverything
Docker containereverything
Static export: output: 'export'only features that don’t need a server
Platform adapterdepends on the platform; verified adapters pass the Next.js test suite
bashon the server
npm run buildnpm run start

standalone for Docker

With output: 'standalone', Next.js works out which files the server needs and copies them, along with the required part of node_modules, into .next/standalone, and puts server.js next to them. The .next/static and public folders are not included: serve them from a CDN or copy them manually. NEXT_PUBLIC_ variables are inlined into JavaScript at build time; all others are read when the server starts.

The .next/static and public folders can be served from a CDN instead of being copied into the image.
typescriptnext.config.ts
import type { NextConfig } from 'next' const nextConfig: NextConfig = {  cacheComponents: true,  partialPrefetching: true,  output: 'standalone',} export default nextConfig
bashafter next build
cp -r public .next/standalone/cp -r .next/static .next/standalone/.next/PORT=8080 HOSTNAME=0.0.0.0 node .next/standalone/server.js

These three parts are enough for the container image: .next/standalone, .next/static and public. The server takes its port and address from the PORT and HOSTNAME variables. For how to write the Dockerfile itself and build the image in multiple stages, see the Docker reference, section “Dockerfile and its instructions”.

Environment variables

Next.js loads variables from .env* files into process.env. The lookup order is process.env, .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV), .env; the first value found wins. The files live in the project root, even if you use a src/ folder. The create-next-app template adds them to .gitignore, because they don’t belong in Git.

VariableWhere it is availableWhen it is substituted
DATABASE_URLon the server onlywhen server code reads it
NEXT_PUBLIC_API_URLon the server and in the browserat next build: the value is inlined into JavaScript

NEXT_PUBLIC_ values are frozen at build time: if one image runs in several environments, such a variable will have the value it had at next build everywhere. Access through a variable, such as process.env[name], is not inlined. Read a server variable that must change from run to run while rendering at request time, after await connection():

tsxapp/page.tsx
import { Suspense } from 'react'import { connection } from 'next/server' async function Region() {  await connection()  // read at request time, not at build time  return <p>Region: {process.env.APP_REGION}</p>} export default function Page() {  return (    <Suspense fallback={<p>Loading...</p>}>      <Region />    </Suspense>  )}

Static export

output: 'export' turns the app into a set of HTML, CSS and JavaScript files in the out folder, which any web server can serve. Anything computed at request time doesn’t work without a server:

  • Dynamic routes without generateStaticParams(), or with dynamicParams: true
  • Cookies, headers, redirects and rewrites, proxy
  • Server Actions and Route Handlers that read the request
  • ISR, Draft Mode and intercepting routes
  • Image optimisation with the default loader; next/image does work with a custom loader

Your own server: what to configure

  • Put a reverse proxy such as nginx in front of Next.js: it filters out malformed requests and slow connections, and limits body size and request rate. For how to configure nginx, see the nginx reference, section “Reverse proxy”.
  • Turn off response buffering in the proxy and the load balancer, otherwise streaming doesn’t work. For nginx, Next.js can send the X-Accel-Buffering: no header.
  • With several instances, give them all the same NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, a base64 key of 16, 24 or 32 bytes; otherwise you will get Failed to find Server Action errors.
  • Set deploymentId in next.config.ts: if the client and server come from different releases, Next.js does a full page reload instead of a client-side navigation.
  • By default each instance has its own cache, in memory and on disk. A shared cache needs a custom handler (cacheHandler, or cacheHandlers for 'use cache') backed by a store such as Redis.
  • Stop the server with SIGTERM or SIGINT and give it 10–30 seconds: Next.js finishes in-flight requests and after() callbacks.

Image optimisation works with next start without any configuration. Platforms such as Vercel and Bun plug in through adapters; verified adapters pass the full Next.js compatibility test suite.

Section sources

the section is written from these pages

Security

The two main threats in a Next.js app are leaking server data into client code and calling Server Functions without checking permissions. A Server Component can see the database and secrets, and everything it passes to a Client Component goes to the browser; a Server Function is open to anyone who sends a POST.

Data access layer

For new projects, the documentation recommends a data access layer (DAL): a dedicated server module through which all data requests go. It checks the session and permissions and returns only the necessary fields (DTOs). A check next to the data works wherever the request comes from: a page, a Server Function or a Route Handler.

typescriptlib/dal.ts
import 'server-only'import { cache } from 'react'import { cookies } from 'next/headers'import { redirect } from 'next/navigation'import { db } from '@/lib/db'import { decrypt } from '@/lib/session' export const verifySession = cache(async () => {  const token = (await cookies()).get('session')?.value  const session = await decrypt(token)  if (!session?.userId) redirect('/login')  return { userId: session.userId }}) export async function getProfile(id: string) {  const { userId } = await verifySession()  const user = await db.user.findUnique({ where: { id } })  if (!user) return null  // only the fields the UI needs  return {    name: user.name,    email: user.id === userId ? user.email : null,  }}

Don’t rely on checks in a layout: it doesn’t re-render on navigation, and nested segments render independently of it. Proxy is fine for a quick cookie check and a redirect to the sign-in page, but not as your only protection.

Server Functions are public endpoints

Every Server Function can be reached with a direct POST request, not just through your form, and a check on a page doesn’t cover functions declared on it. Inside each function:

  • Check authentication: is there a session?
  • Check permissions on the specific record: does it belong to the user? Otherwise anyone can modify other people’s data by substituting an id (IDOR).
  • Validate the input: FormData, parameters and headers come from the client. A schema library such as zod checks the shape of the data, but not permissions.
  • Return only what the UI needs: the result is serialised and sent to the browser.
  • Rate-limit expensive operations such as sending emails and writing to the database.
typescriptapp/actions.ts: don’t do this
'use server' import { db } from '@/lib/db' export async function deletePost(postId: string) {  await db.post.delete({ where: { id: postId } })}
typescriptapp/actions.ts: do this
'use server' import { auth } from '@/lib/auth'import { db } from '@/lib/db' export async function deletePost(postId: string) {  const session = await auth()  if (!session?.user) throw new Error('Unauthorized')   const post = await db.post.findUnique({ where: { id: postId } })  // only the author can delete  if (post?.authorId !== session.user.id) throw new Error('Forbidden')   await db.post.delete({ where: { id: postId } })}

What to send to the browser

Everything a Server Component passes to a Client Component through props is serialised and visible in the browser. Pass only the fields you need, not the whole database record: <Profile name={user.name} />, not <Profile user={user} />. Mark modules that access the database and secrets with import 'server-only': importing them into client code then becomes a build error.

React’s taint API provides an extra safeguard: experimental_taintObjectReference and experimental_taintUniqueValue, with experimental.taint: true in next.config.ts. A tainted object or value can’t be passed to the client, but this doesn’t replace filtering in the DAL.

Built-in Server Actions protection

  • Server Actions can only be invoked with the POST method, and Next.js compares the Origin header with Host or X-Forwarded-Host and rejects the request if they differ. This protects against CSRF.
  • If the app is accessed through a proxy or CDN on a different domain, add that domain to serverActions.allowedOrigins.
  • The request body is limited to 1 MB; serverActions.bodySizeLimit allows a larger size.
  • Action IDs are encrypted, and unused Server Actions are removed from the client bundle and get no URL.
  • Variables captured by a function declared inside a component are encrypted before being sent to the client; don’t rely on this encryption alone.
typescriptnext.config.ts
import type { NextConfig } from 'next' const nextConfig: NextConfig = {  experimental: {    serverActions: {      allowedOrigins: ['shop.example.com', '*.shop.example.com'],      bodySizeLimit: '2mb',    },  },} export default nextConfig

Behind a reverse proxy, no entry is needed if the proxy passes the public host in X-Forwarded-Host. Next.js lets through a request with no Origin header at all, with a warning.

Secrets

Keep secrets in environment variables without the NEXT_PUBLIC_ prefix: they are available only on the server. Anything with the NEXT_PUBLIC_ prefix ends up in JavaScript for the browser, so never put API keys there. Read process.env only in the data access layer, so that secrets don’t spread through the rest of the code.

Content Security Policy with a nonce

A Content Security Policy (CSP) restricts where a page may load scripts, styles and images from, and protects against XSS and clickjacking. The strict option is a nonce: for each request, proxy generates a random value and puts it in the Content-Security-Policy header, and Next.js adds it to its own scripts and styles. A nonce works only with dynamic rendering: a page built in advance has no request to put it in.

typescriptproxy.ts
import { NextResponse } from 'next/server'import type { NextRequest } from 'next/server' export function proxy(request: NextRequest) {  const nonce = Buffer.from(crypto.randomUUID()).toString('base64')  const isDev = process.env.NODE_ENV === 'development'  const devEval = isDev ? " 'unsafe-eval'" : ''  const csp = [    "default-src 'self'",    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${devEval}`,    `style-src 'self' 'nonce-${nonce}'`,    "object-src 'none'",    "frame-ancestors 'none'",  ].join('; ')   const headers = new Headers(request.headers)  headers.set('x-nonce', nonce)  headers.set('Content-Security-Policy', csp)  const response = NextResponse.next({ request: { headers } })  response.headers.set('Content-Security-Policy', csp)  return response}

'unsafe-eval' is needed only in development: React uses eval for debugging information, but not in production. For a proxy like this, set a matcher that excludes static files, images and link prefetches.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the message in the next dev terminal and the error overlay in the browser: they name the route and the component. Most Next.js errors have their own documentation page with the cause and the fixes. next info produces a system report, and you can step through server code with a debugger after starting with --inspect.

  1. Read the message in the next dev terminal and in the browser overlay.
  2. Find the error text below, or on the error’s page in the Next.js documentation.
  3. If the error appears only during the build, reproduce it with next build --debug-prerender.
  4. If the cause is still unclear, step through the server code with a debugger: npm run dev -- --inspect.

Uncached data was accessed outside of <Suspense>

Cause: Cache Components is enabled, and a component without a parent <Suspense> boundary is waiting for params, searchParams, cookies(), headers(), connection() or data without 'use cache'. Next.js treats such data as needed on every request and has nothing to show while it loads.

To find it, check the overlay in next dev, which points to the component. If the error appears only in CI builds, build with prerender debugging to get a trace:

bashin the project directory
npx next build --debug-prerender
  • The data is the same for everyone and rarely changes: cache the function with 'use cache' and cacheLife('hours').
  • The data must be fresh on every request: wrap the component in <Suspense fallback={…}> or put a loading.tsx next to the page.
  • The page waits for params: pass the promise to a child component inside <Suspense>, or list the values in generateStaticParams.
  • A cache lifetime that is too short, such as cacheLife('seconds'), also makes the block dynamic: lengthen it or add <Suspense>.
tsxapp/product/[id]/page.tsx
import { Suspense } from 'react' export default function ProductPage({  params,}: {  params: Promise<{ id: string }>}) {  return (    <Suspense fallback={<p>Loading product...</p>}>      <ProductDetails params={params} />    </Suspense>  )} async function ProductDetails({  params,}: {  params: Promise<{ id: string }>}) {  const { id } = await params  const product = await getProduct(id)  return <h1>{product.name}</h1>}

Text content does not match server-rendered HTML

Cause: the markup the server rendered to HTML did not match the first render in the browser during hydration. Common sources are Date() in the render, typeof window !== 'undefined' checks, reading window and localStorage, invalid tag nesting (<div> inside <p>, <a> inside <a>), and browser extensions or CDNs that modify the HTML.

  • Read browser-only values in useEffect: the first render matches the server, and the value is filled in after hydration.
  • Load a component that cannot render on the server with dynamic() from next/dynamic and the { ssr: false } option.
  • Fix the nesting of HTML tags.
  • If a mismatch is unavoidable, such as a timestamp, add suppressHydrationWarning to the element. It works one level deep and is a last resort.
  • iOS turns phone numbers, dates and addresses into links; disable this with the tag <meta name="format-detection" content="telephone=no, date=no, email=no, address=no" />.
tsxapp/ui/local-time.tsx
'use client' import { useEffect, useState } from 'react' export function LocalTime() {  const [time, setTime] = useState<string | null>(null)   useEffect(() => {    // runs only in the browser, after hydration    setTime(new Date().toLocaleTimeString())  }, [])   return <span>{time ?? '--:--'}</span>}

Dynamic APIs are Asynchronous

Cause: the code accesses params, searchParams, cookies(), headers() or draftMode() synchronously, as in Next.js 14: params.id, {...params}, cookies().get('a'). Since Next.js 15, these APIs return promises. A codemod fixes most cases:

bashin the project directory
npx @next/codemod@canary next-async-request-api .

Anything the codemod cannot fix is marked with a @next-codemod-error comment; while such comments remain, next dev and next build fail. In a Server Component, wait for the value with await; in a synchronous Client Component, unwrap the promise with use from React:

tsxapp/[id]/page.tsx
'use client' import { use } from 'react' export default function Page({  params,}: {  params: Promise<{ id: string }>}) {  const { id } = use(params)  return <p>ID: {id}</p>}

next/image Un-configured Host

Cause: the src of an <Image> component points to a host that is not in images.remotePatterns. The match is strict and case-sensitive: the protocol, host, port, path and query string must all match the pattern.

  • https in src but http in the pattern, or the other way round.
  • The image comes from the subdomain assets.example.com, but only example.com is allowed.
  • The port is missing in local development: http://localhost:3000.
  • The path is too narrow: /images/ instead of /images/**.
  • A pattern built with new URL() and no query string forbids any parameters: ?v=1 is rejected.
typescriptnext.config.ts
import type { NextConfig } from 'next' const nextConfig: NextConfig = {  images: {    remotePatterns: [      new URL('https://assets.example.com/account123/**'),      // an object without search allows any query parameters      {        protocol: 'https',        hostname: 'assets.example.com',        port: '',        pathname: '/uploads/**',      },    ],  },} export default nextConfig

DynamicServerError - Dynamic Server Usage

Cause: during static generation, cookies(), headers() or another dynamic function is called outside its execution context, for example inside setTimeout, setInterval or after a promise that was not awaited. Next.js catches DynamicServerError and switches the page to dynamic rendering; an unhandled error fails the build.

  • Call the dynamic function before setTimeout, setInterval and promise creation: these operations create a new execution context, and reading the request from inside them loses the context.
  • Await promises that read the request: a missing await defers the call until the operation finishes, detached from its context.
tsxapp/page.tsx
import { cookies } from 'next/headers' async function getCookieData() {  const cookieStore = await cookies()  const cookieData = cookieStore.getAll()  return new Promise((resolve) =>    setTimeout(() => {      resolve(cookieData)    }, 1000)  )}

Debugging server code

Debug server code with the Node.js inspector: start the development server with the --inspect flag and attach from Chrome (chrome://inspect, the Remote Target section) or Firefox (about:debugging). Debug client code in the browser DevTools: a debugger statement or a breakpoint in a file pauses execution.

bashin the project directory
npm run dev -- --inspect

In Docker, allow connections from outside with --inspect=0.0.0.0. To pause on the first line, set NODE_OPTIONS=--inspect-brk before next dev. In the error overlay, below the version indicator, there is a Node.js icon that copies the DevTools address of the server process.

json.vscode/launch.json
{  "version": "0.2.0",  "configurations": [    {      "name": "Next.js: debug server-side",      "type": "node-terminal",      "request": "launch",      "command": "npm run dev -- --inspect"    }  ]}

After upgrading to Next.js 16, the most common errors come from the rename of middleware to proxy and from removed APIs. What to change and which codemods to use is covered in the sections “Proxy (formerly middleware)” and “Versions and what’s new”.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Next.js 16.4. The latest release is 16.4.5, from 3 November 2026. A major version receives new features and fixes (Active LTS) until the next one ships, and then only critical fixes and security updates (Maintenance LTS) for two years from its release.

BranchStatusLatest releaseSupported until
16.xActive LTS, covered here16.4.5 — 3 November 2026Active until Next.js 17 is released, Maintenance until 21 October 2027
15.xMaintenance LTS15.5.29 — 3 November 202631 January 2027: extended from the original 21 October 2026
14.xUnsupported14.2.35 — 12 December 2025Support has ended

canary releases ship daily and are not recommended for production. On a Maintenance LTS branch, updates arrive as minor versions, even when they include breaking changes.

What changed in 16.4

  • Caching and revalidation: Cache Components is recommended for all applications and is enabled by default in new create-next-app projects, together with Partial Prefetching.
  • Rendering: exporting ensureStatic with the value 'navigation', 'prefetch' or 'shell' from a page or layout fails the build if dynamic content ends up in the route.
  • Routes, layouts and navigation: await navigation() and await prefetch() from next/cache exclude cached content from prefetching and defer it until navigation or an explicit prefetch.
  • Rendering: React 19.3 is bundled, with stable View Transitions and Fragment Refs and a new browser() API.
  • Build and deployment: the Turbopack disk cache is 20–25% smaller, server code in development is recompiled only for requested routes, and CSS Modules class names are shorter in production.

Deprecated and removed

  • middleware was deprecated in 16.0 and renamed proxy; the codemod is middleware-to-proxy. Proxy runs only on Node.js: if you need the Edge Runtime, keep middleware for now.
  • Synchronous access to cookies(), headers(), draftMode(), params and searchParams was removed in 16.0: use only await or use. The codemod is next-async-request-api.
  • Turbopack is the default bundler for next dev and next build. With a custom webpack configuration the build fails: migrate it to Turbopack or run with --webpack.
  • Removed: AMP, the next lint command (run ESLint or Biome directly), serverRuntimeConfig and publicRuntimeConfig (use environment variables), and the experimental.dynamicIO and experimental.useCache flags (use cacheComponents).
  • revalidateTag with a single argument is deprecated: pass a profile as the second argument, for example revalidateTag('posts', 'max'), or call updateTag in a Server Action.
  • Images: images.domains and next/legacy/image are deprecated. New defaults: minimumCacheTTL is 4 hours, qualities is [75], size 16 is gone from imageSizes, at most 3 redirects, and local IPs are blocked without dangerouslyAllowLocalIP.
  • Every parallel route slot needs its own default.js, or the build fails.
  • Minimum versions: Node.js 20.9 and TypeScript 5.1; browsers are Chrome, Edge and Firefox 111+, and Safari 16.4+.

Security updates

IdentifierWhat is affectedFixed in
GHSA-mfr8-8qww-v76hCache Components: cache leak between tenants when one use cache function is called both directly and through unstable_cache. High16.4.5, 15.5.29
GHSA-vc7v-qv4w-wrv8, GHSA-rhh4-g77r-r9qj, GHSA-vvgp-ww4w-46vfuse cache: cache leak between root param values in nested functions, cache key collisions with binary arguments, and poisoning of the shared page shell under next start. Medium16.4.5, 15.5.29
GHSA-pc58-hwjq-p385, GHSA-f3mh-rxg3-f5g2, GHSA-7qx7-33qx-rqx2Response spoofing between clients in self-hosting, cookie values in an internal header of Edge routes, and a bypass of the SVG ban in image optimisation. Medium16.4.5, 15.5.29
GHSA-673q-mjm6-r5xrCache Components: remote code execution when a use cache function returns several typed arrays. Critical16.4.1
CVE-2026-96889, GHSA-2464-fhr4-w9xwImage optimisation: remote code execution through SVG on Linux with glibc. Critical16.4.1, 15.5.28
GHSA-p3m5-59mp-jv5rServer Actions: denial of service. High16.4.1, 15.5.28
CVE-2026-94483, GHSA-cjq9-62q9-8jv4Image optimisation: SSRF through an address from remotePatterns. High16.3.8
CVE-2026-94544, GHSA-h694-7cp9-m8p3use cache: leak of Draft Mode drafts and of entries for another root param. Medium16.3.8
GHSA-vcvr-r3jv-pc5jImageResponse from next/og on Node.js: remote code execution, versions 16.2.0–16.3.5. Critical16.3.6
CVE-2026-75604, GHSA-p293-qw3h-jr36Servers on Windows: remote code execution. Critical16.3.3, 15.5.24
GHSA-2xp9-vwfh-vxw4, GHSA-g89c-p67h-r497AVIF image optimisation: remote code execution; AVIF optimisation disabled. Critical16.3.3, 15.5.24
CVE-2026-64641, CVE-2026-64642, CVE-2026-64645, CVE-2026-64649Denial of service in Server Actions, proxy bypass with Turbopack and a single locale, SSRF in rewrites and Server Actions. High16.2.11, 15.5.21
CVE-2025-66478 (CVE-2025-55182 in React)React Server Components protocol: remote code execution, CVSS 10.016.0.7, 15.5.7 and patches for other 15.x branches

Security releases ship almost every month and are announced in advance on the Next.js blog. Update to the latest patch of your branch, even if you do not use the affected feature.

How to upgrade

The “How to upgrade to version 16” page runs the upgrade together with the codemods using pnpm dlx @next/codemod@canary upgrade latest; with npm, npx does the same:

bashin the project directory
npx @next/codemod@canary upgrade latest
  1. Run npx @next/codemod@canary next-async-request-api . if synchronous params or cookies() remain in the code.
  2. Work through the breaking changes listed above and update @types/react and @types/react-dom.
  3. Run next build and next start, then check the terminal warnings and that the pages work: a successful build does not mean the application works.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Next.js” topic
13 sections
Another reference · Backend

HTTP and REST

Verified 1 Nov
All references · 61