# blade47/next.js Wiki ## Technical docs: Cache Miss Route Fetching URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/how-it-works/cache-miss-route-fetching
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/client/components/segment-cache/cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts) - [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts) - [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts)
## Overview The execution flow starting from `fetchRouteOnCacheMiss` down to `encodeCacheBustingSearchParam` coordinates fetching prefetch route information when a segment cache miss occurs, and ensures network requests bypass CDNs that fail to respect custom router headers. By encoding key request headers into a compact query parameter (often `_rsc`), Next.js guarantees cache uniqueness across diverse hosting environments. Sources: [packages/next/src/client/components/segment-cache/cache.ts:1825-1846](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts#L1825-L1846), [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts:53-59](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts#L53-L59), [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts:6-13](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts#L6-L13) --- ### Step 1: `fetchRouteOnCacheMiss` When a route is requested and results in a cache miss, `fetchRouteOnCacheMiss` initializes headers specifying the RSC prefetch type and segment path (`/_tree`). It prepares the target URL for fetching the route tree structure. Sources: [packages/next/src/client/components/segment-cache/cache.ts:1825-1846](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts#L1825-L1846) --- ### Step 2: `fetchPrefetchResponse` Next, `fetchPrefetchResponse` executes the network call using underlying fetch utilities. It wraps request creation and configures prefetch priorities without instantly decoding the binary stream. Sources: [packages/next/src/client/components/segment-cache/cache.ts:3663-3698](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts#L3663-L3698) --- ### Step 3: `createFetch` `createFetch` coordinates the outbound HTTP request. Depending on CDN capabilities and environment parameters, it may invoke cache-busting mechanisms to decorate the outgoing request URL with query parameters derived from headers. Sources: [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts:53-59](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts#L53-L59) --- ### Step 4: `setCacheBustingSearchParam` To handle static hosting providers and CDNs that ignore custom headers like `Next-Router-Prefetch`, `setCacheBustingSearchParam` computes a unique hash from the request headers and appends it to the URL query string. Sources: [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts:53-59](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts#L53-L59) --- ### Step 5: `computeClientCacheBustingSearchParam` This function verifies whether the browser environment supports the modern `Crypto` API. If cryptographic digest operations are available via `globalThis.crypto.subtle`, it proceeds with the secure hashing path; otherwise, it falls back to a legacy hashing mechanism. Sources: [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts:16-34](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts#L16-L34) --- ### Step 6: `computeCacheBustingSearchParam` `computeCacheBustingSearchParam` aggregates relevant prefetch headers (such as prefetch flags, segment prefetch identifiers, state tree paths, and next URLs) into a normalized input string before passing it down for digest computation. Sources: [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts:60-77](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts#L60-L77) --- ### Step 7: `computeCacheBustingSearchParamFromInput` Using the Web Crypto API, this function computes a SHA-256 hash of the header input string. It truncates the resulting digest to a compact 96-bit window (12 bytes) to keep the generated `_rsc` search query short and clean. Sources: [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts:47-58](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts#L47-L58) --- ### Step 8: `encodeCacheBustingSearchParam` Finally, `encodeCacheBustingSearchParam` takes the binary digest buffer, converts it to a standard base64 string, and replaces URL-unsafe characters (swapping `+` for `-`, `/` for `_`, and stripping padding `=` characters) to produce a safe cache-busting token. Sources: [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts:6-13](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts#L6-L13) --- ## Architectural Diagrams ### Sequence Diagram ```mermaid sequenceDiagram participant Cache as cache.ts participant Reducer as set-cache-busting-search-param.ts participant Utils as cache-busting-search-param.ts Cache->>Cache: fetchRouteOnCacheMiss() Cache->>Cache: fetchPrefetchResponse() Cache->>Reducer: setCacheBustingSearchParam(url, headers) Reducer->>Reducer: computeClientCacheBustingSearchParam(headers) Reducer->>Utils: computeCacheBustingSearchParam(...) Utils->>Utils: computeCacheBustingSearchParamFromInput(input) Utils->>Utils: encodeCacheBustingSearchParam(bytes) Utils-->>Reducer: return hash string Reducer->>Reducer: setCacheBustingSearchParamWithHash(url, hash) Reducer-->>Cache: URL mutated with query parameter ``` Sources: [packages/next/src/client/components/segment-cache/cache.ts:1825-1846](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts#L1825-L1846), [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts:16-59](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts#L16-L59), [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts:6-13](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts#L6-L13) ### Flowchart ```mermaid flowchart TD A[Cache Miss] --> B[fetchRouteOnCacheMiss] B --> C[fetchPrefetchResponse] C --> D[setCacheBustingSearchParam] D --> E{Crypto API Available?} E -- Yes --> F[computeCacheBustingSearchParam] E -- No --> G[computeLegacyCacheBustingSearchParam] F --> H[computeCacheBustingSearchParamFromInput] H --> I[encodeCacheBustingSearchParam] I --> J[Append _rsc Hash to URL] G --> J J --> K[Execute HTTP Request] ``` Sources: [packages/next/src/client/components/segment-cache/cache.ts:1825-1846](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts#L1825-L1846), [packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts:16-34](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/set-cache-busting-search-param.ts#L16-L34), [packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts:47-77](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/cache-busting-search-param.ts#L47-L77) --- ## Key Observations - **Cross-Module Boundaries:** This execution path bridges high-level segment cache management (`cache.ts`), router action reducers (`set-cache-busting-search-param.ts`), and lower-level shared URL utilities (`cache-busting-search-param.ts`). - **Resilience on Static CDNs:** By hashing headers into a URL query parameter (`_rsc`), Next.js bypasses limitations on edge networks and proxies that strip custom routing headers or fail to evaluate `Vary` headers properly. - **Graceful Fallbacks:** The system checks for the presence of modern cryptographic APIs (`globalThis.crypto.subtle`) and smoothly falls back to legacy hashing strategies if needed, ensuring continuous operation across varied runtime runtimes. --- ## Technical docs: Overview URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/overview
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/build/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/index.ts) - [packages/next/src/client/next-dev.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/taskfile.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js) - [packages/next/src/api/server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/server.ts) - [packages/next/src/server/render.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx) - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/types.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/types.js) - [packages/next/src/shared/lib/constants.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/constants.ts) - [packages/next/src/build/templates/edge-ssr.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts) - [packages/next/src/cli/next-info.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/cli/next-info.ts) - [packages/next/src/server/route-modules/pages/module.compiled.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.compiled.js) - [packages/next/src/build/webpack-build/impl.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack-build/impl.ts) - [packages/next/src/server/lib/router-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-server.ts) - [packages/next/src/api/router.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/router.ts) - [packages/next/src/client/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx) - [packages/next/src/client/next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next.ts) - [packages/next/src/api/navigation.react-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/navigation.react-server.ts) - [packages/next/script.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/script.js) - [packages/next/src/client/components/app-router.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router.tsx) - [packages/next/src/server/next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts) - [packages/next/src/client/next-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-turbopack.ts) - [packages/next/src/client/app-index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx) - [packages/next/router.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/router.js) - [packages/next/app.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/app.js) - [packages/next/src/server/route-modules/app-page/module.compiled.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.compiled.js) - [packages/next/src/server/route-modules/pages/module.compiled.d.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.compiled.d.ts) - [packages/next/src/client/next-dev-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev-turbopack.ts) - [packages/next/src/server/route-modules/app-route/module.compiled.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.compiled.js) - [packages/next/package.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json)
## Subsystem Architecture Foundation Next.js orchestrates its architecture through a structured ecosystem comprising programmatic server entry points like [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) and [Development Server](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/development-server), public export facades, dual runtime routing compilation targets across Node and Edge environments, and dedicated client-side application bootstrap topologies. ```mermaid graph TD A[Build Pipeline] -->|SWC & Webpack/Turbopack| B[Dual Runtime Routing Targets] B -->|Node & Edge SSR| C[Server Execution] C -->|Manifests & Contracts| D[Client Application Bootstrap] ``` Sources: [packages/next/src/build/index.ts:188-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/index.ts#L188-L190) These subsystems rely on repository-level compilation tasks and build asset transformations managed via taskfile orchestration, alongside cross-cutting build manifest integration that governs runtime dispatch contracts [Build Pipeline](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/build-pipeline), [Turbopack Engine](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/turbopack-engine), and [Webpack Configuration](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/webpack-configuration). Sources: [packages/next/src/server/base-server.ts:30-41](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L30-L41), [packages/next/taskfile.js:2433-2436](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2433-L2436) ## Programmatic server entry points ### Custom Server API and Deprecations The public programmatic server entry point is provided via `packages/next/src/server/next.ts`, exporting the `NextServer` class alongside configuration options, handler signatures, and bundler choices [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture), [Development Server](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/development-server). Custom server implementations initialize an instance of `NextServer` to invoke lifecycle methods such as `prepare()`, `getRequestHandler()`, `getUpgradeHandler()`, and `close()` [CLI Commands](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/cli-telemetry/cli-commands). ```typescript export type NextServerOptions = Omit< ServerOptions | DevServerOptions, // This is assigned in this server abstraction. 'conf' | 'compileMode' > & Partial> export type NextBundlerOptions = { /** @deprecated Use `turbopack` instead */ turbo?: boolean /** Selects Turbopack as the bundler */ turbopack?: boolean /** Selects Webpack as the bundler */ webpack?: boolean } export type RequestHandler = ( req: IncomingMessage, res: ServerResponse, parsedUrl?: NextUrlWithParsedQuery | undefined ) => Promise export type UpgradeHandler = ( req: IncomingMessage, socket: Duplex, head: Buffer ) => Promise ``` Sources: [packages/next/src/server/next.ts:43-69](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L43-L69) The `NextServer` class implements `NextWrapperServer`, exposing standard HTTP request dispatching methods alongside legacy custom server operations that trigger formal warnings when invoked. | Method Name | Category | Status | Migration Guidance / Description | | :--- | :--- | :--- | :--- | | `getRequestHandler()` | Core Request Routing | Active | Returns a `RequestHandler` for `IncomingMessage` and `ServerResponse`. | | `getUpgradeHandler()` | Core WebSocket Upgrade | Active | Returns an `UpgradeHandler` for upgrading network sockets. | | `prepare()` | Server Lifecycle | Active | Asynchronously compiles and initializes application server fields. | | `close()` | Server Lifecycle | Active | Shuts down the underlying server instance and underlying caches. | | `setAssetPrefix()` | Configuration | Deprecated | Configure `assetPrefix` in `next.config.js` instead. | | `logError()` | Logging | Deprecated | Please use application logging instead. | | `logErrorWithOriginalStack()` | Logging | Deprecated | Please use application logging instead. | | `revalidate()` | Cache Management | Deprecated | Please use documented application revalidation APIs instead. | | `render()` | Rendering | Deprecated | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `renderToHTML()` | Rendering | Deprecated | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `renderError()` | Rendering | Deprecated | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `renderErrorToHTML()` | Rendering | Deprecated | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `render404()` | Rendering | Deprecated | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | Sources: [packages/next/src/server/next.ts:112-176](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L112-L176) ```typescript type DeprecatedCustomServerMethod = | 'setAssetPrefix' | 'logError' | 'logErrorWithOriginalStack' | 'revalidate' | 'render' | 'renderToHTML' | 'renderError' | 'renderErrorToHTML' | 'render404' const DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE: Record< DeprecatedCustomServerMethod, string > = { setAssetPrefix: 'Please configure `assetPrefix` in `next.config.js` instead.', logError: 'Please use application logging instead.', logErrorWithOriginalStack: 'Please use application logging instead.', revalidate: 'Please use documented application revalidation APIs instead.', render: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', renderToHTML: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', renderError: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', renderErrorToHTML: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', render404: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', } function warnDeprecatedCustomServerMethod( method: DeprecatedCustomServerMethod ) { log.warnOnce( `The \`app.${method}()\` method is deprecated in custom servers. ${DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE[method]}` ) } ``` Sources: [packages/next/src/server/next.ts:73-110](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L73-L110) > [!WARNING] > Invoking legacy methods like `app.render()` or `app.revalidate()` on a custom server instance logs a runtime warning via `log.warnOnce`, indicating that developers should switch to `app.getRequestHandler()` or native application revalidation utilities [Request Lifecycle](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/request-lifecycle). Sources: [packages/next/src/server/next.ts:104-110](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L104-L110) ```typescript interface NextWrapperServer { // NOTE: the methods/properties here are the public API for custom servers. // Consider backwards compatibilty when changing something here! options: NextServerOptions hostname: string | undefined port: number | undefined getRequestHandler(): RequestHandler prepare(serverFields?: ServerFields): Promise /** @deprecated Configure `assetPrefix` in `next.config.js` instead. */ setAssetPrefix(assetPrefix: string): void close(): Promise // used internally getUpgradeHandler(): UpgradeHandler // legacy methods that we left exposed in the past /** @deprecated Use application logging instead. */ logError(...args: Parameters): void /** @deprecated Use documented application revalidation APIs instead. */ revalidate( ...args: Parameters ): ReturnType /** @deprecated Use application logging instead. */ logErrorWithOriginalStack(err: unknown, type: string): void /** * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. */ render( ...args: Parameters ): ReturnType /** * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. */ renderToHTML( ...args: Parameters ): ReturnType /** * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. */ renderError( ...args: Parameters ): ReturnType /** * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. */ renderErrorToHTML( ...args: Parameters ): ReturnType /** * @deprecated Use `app.getRequestHandler()` with an adjusted parsed URL instead. */ render404( ...args: Parameters ): ReturnType } ``` Sources: [packages/next/src/server/next.ts:112-176](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L112-L176) ## Public module export facade ### Package Entrypoints and Re-exports The `next` package export structure maps top-level JavaScript files and API modules to their respective compiled targets within the `dist/` directory. These entry points provide stable external interfaces for client scripts, legacy routers, app renderers, and server-side web APIs. ```json "script.js", "script.d.ts", "server.js", "server.d.ts", "head.js", "head.d.ts", "image.js", "image.d.ts", "image-optimizer-transform.js", "image-optimizer-transform.d.ts", "link.js", "link.d.ts", "offline.js", "offline.d.ts", "form.js", "form.d.ts", "router.js", "router.d.ts", ``` Sources: [packages/next/package.json:34-51](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L34-L51) The table below maps the root package entry files to their underlying compiled output modules. | Root Entry File | Target Module Path | Purpose | | :--- | :--- | :--- | | `script.js` | `./dist/client/script` | External script loading and optimization facade | | `router.js` | `./dist/client/router` | Legacy client-side Pages router bindings | | `app.js` | `./dist/pages/_app` | Base application component for the Pages router | | `packages/next/src/api/router.ts` | `../client/router` | Re-export facade for client router bindings | | `packages/next/src/api/server.ts` | `../server/web/exports/index` | Re-export facade for web server primitives and helpers | | `packages/next/src/api/navigation.react-server.ts` | `../client/components/navigation.react-server` | React Server Component navigation primitives | Sources: [packages/next/script.js:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/script.js#L1-L1), [packages/next/router.js:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/router.js#L1-L1), [packages/next/app.js:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/app.js#L1-L1), [packages/next/src/api/router.ts:1-2](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/router.ts#L1-L2), [packages/next/src/api/server.ts:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/server.ts#L1-L1), [packages/next/src/api/navigation.react-server.ts:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/navigation.react-server.ts#L1-L1) ```javascript module.exports = require('./dist/client/script') ``` Sources: [packages/next/script.js:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/script.js#L1-L1) ```javascript module.exports = require('./dist/client/router') ``` Sources: [packages/next/router.js:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/router.js#L1-L1) ```javascript module.exports = require('./dist/pages/_app') ``` Sources: [packages/next/app.js:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/app.js#L1-L1) ```typescript export { default } from '../client/router' export * from '../client/router' ``` Sources: [packages/next/src/api/router.ts:1-2](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/router.ts#L1-L2) ```typescript export * from '../server/web/exports/index' ``` Sources: [packages/next/src/api/server.ts:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/server.ts#L1-L1) ```typescript export * from '../client/components/navigation.react-server' ``` Sources: [packages/next/src/api/navigation.react-server.ts:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/navigation.react-server.ts#L1-L1) > [!NOTE] > The top-level root modules delegate execution directly to compiled artifacts inside `dist/`, establishing strict boundary contracts between consumer-facing imports and internal compiler layouts. Sources: [packages/next/package.json:11-16](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L11-L16) ```json "files": [ "AGENTS.md", "analyze", "dist", "app.js", "app.d.ts", ] ``` Sources: [packages/next/package.json:11-16](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L11-L16) ## Dual runtime routing compilation targets ### Compiled Route Module Dispatch Next.js unifies server routing execution across Node.js and the [Edge Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime) by dynamically resolving route module implementations through environment-conditioned wrapper modules. Compiled route modules for pages (`packages/next/src/server/route-modules/pages/module.compiled.js`), app pages (`packages/next/src/server/route-modules/app-page/module.compiled.js`), and app routes (`packages/next/src/server/route-modules/app-route/module.compiled.js`) inspect `process.env.NEXT_RUNTIME` at runtime or build time. When `process.env.NEXT_RUNTIME === 'edge'`, these modules bypass Node-specific bundles and require the base edge route module directly from `next/dist/server/route-modules/.../module.js`. When running under Node.js, they branch across `process.env.NODE_ENV`, `process.env.TURBOPACK`, and experimental feature flags like `process.env.__NEXT_EXPERIMENTAL_REACT` to load the appropriate pre-compiled runtime artifact. ```javascript if (process.env.NEXT_RUNTIME === 'edge') { module.exports = require('next/dist/server/route-modules/pages/module.js') } else { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/pages-turbo.runtime.dev.js') } else { module.exports = require('next/dist/compiled/next-server/pages.runtime.dev.js') } } else { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/pages-turbo.runtime.prod.js') } else { module.exports = require('next/dist/compiled/next-server/pages.runtime.prod.js') } } } ``` Sources: [packages/next/src/server/route-modules/pages/module.compiled.js:1-17](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.compiled.js#L1-L17) ```javascript if (process.env.NEXT_RUNTIME === 'edge') { module.exports = require('next/dist/server/route-modules/app-page/module.js') } else { if (process.env.__NEXT_EXPERIMENTAL_REACT) { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.dev.js') } else { module.exports = require('next/dist/compiled/next-server/app-page-experimental.runtime.dev.js') } } else { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js') } else { module.exports = require('next/dist/compiled/next-server/app-page-experimental.runtime.prod.js') } } } else { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.dev.js') } else { module.exports = require('next/dist/compiled/next-server/app-page.runtime.dev.js') } } else { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-page-turbo.runtime.prod.js') } else { module.exports = require('next/dist/compiled/next-server/app-page.runtime.prod.js') } } } } ``` Sources: [packages/next/src/server/route-modules/app-page/module.compiled.js:1-33](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.compiled.js#L1-L33) The table below maps the runtime environment conditions and flag combinations in `app-page/module.compiled.js` and `app-route/module.compiled.js` to their respective loaded production and development runtime bundles. | `NEXT_RUNTIME` | `__NEXT_EXPERIMENTAL_REACT` | `NODE_ENV` | `TURBOPACK` | Target Runtime Bundle Module | | :--- | :--- | :--- | :--- | :--- | | `edge` | *any* | *any* | *any* | `next/dist/server/route-modules/app-page/module.js` (or `app-route/module.js`) | | `node` (default) | `true` | `development` | `true` | `next/dist/compiled/next-server/app-page-turbo-experimental.runtime.dev.js` | | `node` (default) | `true` | `development` | `false` | `next/dist/compiled/next-server/app-page-experimental.runtime.dev.js` | | `node` (default) | `true` | `production` | `true` | `next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js` | | `node` (default) | `true` | `production` | `false` | `next/dist/compiled/next-server/app-page-experimental.runtime.prod.js` | | `node` (default) | `false` | `development` | `true` | `next/dist/compiled/next-server/app-page-turbo.runtime.dev.js` | | `node` (default) | `false` | `development` | `false` | `next/dist/compiled/next-server/app-page.runtime.dev.js` | | `node` (default) | `false` | `production` | `true` | `next/dist/compiled/next-server/app-page-turbo.runtime.prod.js` | | `node` (default) | `false` | `production` | `false` | `next/dist/compiled/next-server/app-page.runtime.prod.js` | Sources: [packages/next/src/server/route-modules/app-page/module.compiled.js:1-33](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.compiled.js#L1-L33) ```javascript if (process.env.NEXT_RUNTIME === 'edge') { module.exports = require('next/dist/server/route-modules/app-route/module.js') } else { if (process.env.__NEXT_EXPERIMENTAL_REACT) { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js') } else { module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js') } } else { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js') } else { module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js') } } } else { if (process.env.NODE_ENV === 'development') { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js') } else { module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js') } } else { if (process.env.TURBOPACK) { module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js') } else { module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js') } } } } ``` Sources: [packages/next/src/server/route-modules/app-route/module.compiled.js:1-33](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.compiled.js#L1-L33) > [!WARNING] > Compiling code for `NEXT_RUNTIME === 'edge'` strips Node.js built-in modules (`fs`, `path`, `crypto`, etc.). Attempting to import Node-only APIs inside modules resolved via edge compiled targets triggers bundling and runtime sandbox faults. Sources: [packages/next/src/server/route-modules/pages/module.compiled.js:1-3](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.compiled.js#L1-L3) ### Edge SSR Templates Edge server-side rendering is orchestrated via code generation templates such as `packages/next/src/build/templates/edge-ssr.ts`. This template initializes global web APIs by importing `../../server/web/globals`, wraps incoming requests using `adapter` and `WebNextRequest`, and instantiates component modules for userland pages, error pages, and optional 500 pages (`userland500Page`). Each module instance is bound to a Pages route module (`RouteModule`) supplied with compiled component options (`pageRouteModuleOptions`, `errorRouteModuleOptions`, `user500RouteModuleOptions`), project paths (`distDir`, `relativeProjectDir`), and layout wrappers (`App`, `Document`). ```typescript import '../../server/web/globals' import { adapter, type EdgeHandler, type NextRequestHint, } from '../../server/web/adapter' import { IncrementalCache } from '../../server/lib/incremental-cache' import * as cacheHandlers from '../../server/use-cache/handlers' import Document from 'VAR_MODULE_DOCUMENT' import * as appMod from 'VAR_MODULE_APP' import * as userlandPage from 'VAR_USERLAND' import * as userlandErrorPage from 'VAR_MODULE_GLOBAL_ERROR' declare const userland500Page: any declare const incrementalCacheHandler: any // OPTIONAL_IMPORT:* as userland500Page // OPTIONAL_IMPORT:incrementalCacheHandler import RouteModule, { type PagesRouteHandlerContext, } from '../../server/route-modules/pages/module' import { WebNextRequest, WebNextResponse } from '../../server/base-http/web' import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event' import type RenderResult from '../../server/render-result' import type { RenderResultMetadata } from '../../server/render-result' import { getTracer, SpanKind, SpanStatusCode, type Span, } from '../../server/lib/trace/tracer' import { BaseServerSpan } from '../../server/lib/trace/constants' import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants' import type { RequestMeta } from '../../server/request-meta' import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' // injected by the loader afterwards. declare const pageRouteModuleOptions: any declare const errorRouteModuleOptions: any declare const user500RouteModuleOptions: any // INJECT:pageRouteModuleOptions // INJECT:errorRouteModuleOptions // INJECT:user500RouteModuleOptions // INJECT_RAW:cacheHandlerImports const pageMod = { ...userlandPage, routeModule: new RouteModule({ ...pageRouteModuleOptions, components: { App: appMod.default, Document, }, userland: userlandPage, distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', }), } const errorMod = { ...userlandErrorPage, routeModule: new RouteModule({ ...errorRouteModuleOptions, components: { App: appMod.default, Document, }, userland: userlandErrorPage, distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', }), } // FIXME: this needs to be made compatible with the template const error500Mod = userland500Page ? { ...userland500Page, routeModule: new RouteModule({ ...user500RouteModuleOptions, components: { App: appMod.default, Document, }, userland: userland500Page, distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', }), } : null ``` Sources: [packages/next/src/build/templates/edge-ssr.ts:1-91](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts#L1-L91) The `requestHandler` function in `edge-ssr.ts` parses incoming requests as `NextRequestHint` objects, constructs `WebNextRequest` wrappers, and invokes `pageRouteModule.prepare()` with source pathname definitions (`VAR_DEFINITION_PATHNAME`) and multizone draft mode flags. If `prepareResult` evaluates to null or falsy, the handler immediately returns an HTTP 400 Bad Request response. ```typescript async function requestHandler( req: NextRequestHint, _event: NextFetchEvent ): Promise { let srcPage = 'VAR_DEFINITION_PATHNAME' const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}` const baseReq = new WebNextRequest(req) const pageRouteModule = pageMod.routeModule as RouteModule const prepareResult = await pageRouteModule.prepare(baseReq, null, { srcPage, multiZoneDraftMode: false, }) if (!prepareResult) { return new Response('Bad Request', { status: 400, }) } ``` Sources: [packages/next/src/build/templates/edge-ssr.ts:95-113](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts#L95-L113) > [!CAUTION] > The optional `userland500Page` is conditionally instantiated via ternary check against `userland500Page` truthiness, whereas primary page and error modules are mandatory and statically instantiated upon template evaluation. Sources: [packages/next/src/build/templates/edge-ssr.ts:77-91](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts#L77-L91) ## Client application bootstrap variants ### Runtime Initialization Topologies Browser entry points govern how Next.js mounts application trees, coordinates hot module reloading, and consumes server-rendered Flight payloads across Webpack and Turbopack compiler runtimes. Production builds rely on `packages/next/src/client/next.ts`, which attaches `version`, `router`, and `emitter` to `window.next`, invokes `initialize({})`, and immediately calls `hydrate()` to attach React component trees to the DOM. ```typescript import './register-deployment-id-global' import './webpack' import '../lib/require-instrumentation-client' import { initialize, hydrate, version, router, emitter } from './' declare global { interface Window { next: any } } window.next = { version, // router is initialized later so it has to be live-binded get router() { return router }, emitter, } initialize({}) .then(() => hydrate()) .catch(console.error) ``` Sources: [packages/next/src/client/next.ts:1-24](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next.ts#L1-L24) Development entry points introduce hot module replacement middleware. `packages/next/src/client/next-dev.ts` initializes `devClient` via `initHMR()`, passes it to `initialize({ devClient })`, and resolves asset prefixes before invoking `pageBootstrap(assetPrefix)`. ```typescript // TODO: Remove use of `any` type. import './register-deployment-id-global' import './webpack' import { initialize, version, router, emitter } from './' import initHMR from './dev/hot-middleware-client' import { pageBootstrap } from './page-bootstrap' window.next = { version, // router is initialized later so it has to be live-binded get router() { return router }, emitter, } const devClient = initHMR() initialize({ devClient }) .then(({ assetPrefix }) => { return pageBootstrap(assetPrefix) }) .catch((err) => { ``` Sources: [packages/next/src/client/next-dev.ts:1-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev.ts#L1-L22) Turbopack environments use specialized entry files that define bundling hooks. `packages/next/src/client/next-turbopack.ts` sets `window.next.turbopack = true`, assigns empty dummy implementations for `__next_set_public_path__` and `__webpack_hash__`, and establishes `__turbopack_load_page_chunks__` to asynchronously resolve page chunks via `__turbopack_load__`. ```typescript // A client-side entry point for Turbopack builds. Includes logic to load chunks, // but does not include development-time features like hot module reloading. import './register-deployment-id-global' import '../lib/require-instrumentation-client' // TODO: Remove use of `any` type. import { initialize, version, router, emitter, hydrate } from './' window.next = { version, turbopack: true, // router is initialized later so it has to be live-binded get router() { return router }, emitter, } ;(self as any).__next_set_public_path__ = () => {} ;(self as any).__webpack_hash__ = '' // for the page loader declare let __turbopack_load__: any initialize({}) .then(() => { // for the page loader ;(self as any).__turbopack_load_page_chunks__ = ( page: string, chunksData: any ) => { const chunkPromises = chunksData.map((c: unknown) => __turbopack_load__(c) ) Promise.all(chunkPromises).catch((err) => console.error('failed to load chunks for page ' + page, err) ) } return hydrate() }) ``` Sources: [packages/next/src/client/next-turbopack.ts:1-42](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-turbopack.ts#L1-L42) Similarly, development under Turbopack (`packages/next/src/client/next-dev-turbopack.ts`) combines HMR middleware client connection logic with chunk loading functions and connects to the Turbopack WebSocket message broker using `connect()`. ```typescript // TODO: Remove use of `any` type. import './register-deployment-id-global' import { initialize, version, router, emitter } from './' import initHMR from './dev/hot-middleware-client' import { pageBootstrap } from './page-bootstrap' //@ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension import { connect } from '@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client.ts' import type { TurbopackMessageSentToBrowser } from '../server/dev/hot-reloader-types' window.next = { version, turbopack: true, // router is initialized later so it has to be live-binded get router() { return router }, emitter, } ;(self as any).__next_set_public_path__ = () => {} ;(self as any).__webpack_hash__ = '' // for the page loader declare let __turbopack_load__: any const devClient = initHMR() initialize({ devClient, }) .then(({ assetPrefix }) => { // for the page loader ;(self as any).__turbopack_load_page_chunks__ = ( page: string, chunksData: any ) => { const chunkPromises = chunksData.map((c: unknown) => __turbopack_load__(c) ) Promise.all(chunkPromises).catch((err) => console.error('failed to load chunks for page ' + page, err) ) } connect({ addMessageListener(cb: (message: TurbopackMessageSentToBrowser) => void) { devClient.addTurbopackMessageListener(cb) }, sendMessage: devClient.sendTurbopackMessage, onUpdateError: devClient.handleUpdateError, chunkUpdateListenersGlobal: process.env.__NEXT_TURBOPACK_CHUNK_UPDATE_LISTENERS_GLOBAL!, }) return pageBootstrap(assetPrefix) }) ``` Sources: [packages/next/src/client/next-dev-turbopack.ts:1-56](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev-turbopack.ts#L1-L56) | Bootstrap Variant | Entry File Path | HMR Client | Turbopack Flag | Chunk Loader Hook | Hydration Trigger | | :--- | :--- | :--- | :--- | :--- | :--- | | **Production Webpack** | `packages/next/src/client/next.ts` | No | `undefined` | Standard Webpack runtime | `hydrate()` | | **Development Webpack** | `packages/next/src/client/next-dev.ts` | Yes (`initHMR()`) | `undefined` | Standard Webpack runtime | `pageBootstrap(assetPrefix)` | | **Production Turbopack** | `packages/next/src/client/next-turbopack.ts` | No | `true` | `__turbopack_load_page_chunks__` | `hydrate()` | | **Development Turbopack** | `packages/next/src/client/next-dev-turbopack.ts` | Yes (`initHMR()`) | `true` | `__turbopack_load_page_chunks__` | `pageBootstrap(assetPrefix)` | Sources: [packages/next/src/client/next.ts:1-24](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next.ts#L1-L24), [packages/next/src/client/next-dev.ts:1-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev.ts#L1-L22), [packages/next/src/client/next-turbopack.ts:1-42](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-turbopack.ts#L1-L42), [packages/next/src/client/next-dev-turbopack.ts:1-56](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/next-dev-turbopack.ts#L1-L56) ### App Router Flight Stream Ingestion The [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) client initializes through `packages/next/src/client/app-index.tsx`, which processes streamed React Server Component (RSC) payloads from the global `window.__next_f` array (`NextFlight`). The runtime defines specific numeric segment identifiers via `FlightSegment` tuples to decode bootstrap data, text chunks, form state, and base64-encoded binary buffers. ```tsx type FlightSegment = | [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string] | [isFormState: 2, formState: any] | [isBinary: 3, responseBase64Partial: string] type NextFlight = Omit, 'push'> & { push: (seg: FlightSegment) => void } declare global { // If you're working in a browser environment interface Window { /** * request ID, dev-only */ __next_r?: string __next_f: NextFlight } } function nextServerDataCallback(seg: FlightSegment): void { if (seg[0] === 0) { initialServerDataBuffer = [] } else if (seg[0] === 1) { if (!initialServerDataBuffer) throw new Error('Unexpected server data: missing bootstrap script.') if (initialServerDataWriter) { initialServerDataWriter.enqueue(encoder.encode(seg[1])) } else { initialServerDataBuffer.push(seg[1]) } } else if (seg[0] === 2) { initialFormStateData = seg[1] } else if (seg[0] === 3) { if (!initialServerDataBuffer) throw new Error('Unexpected server data: missing bootstrap script.') // Decode the base64 string back to binary data. const binaryString = atob(seg[1]) const decodedChunk = new Uint8Array(binaryString.length) for (var i = 0; i < binaryString.length; i++) { decodedChunk[i] = binaryString.charCodeAt(i) } if (initialServerDataWriter) { initialServerDataWriter.enqueue(decodedChunk) } else { initialServerDataBuffer.push(decodedChunk) } } } ``` Sources: [packages/next/src/client/app-index.tsx:60-112](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L60-L112) > [!WARNING] > Accessing `window.__next_f` directly requires immediately draining existing entries and re-assigning the `push` method to `nextServerDataCallback`. Failing to clear the global array causes memory leaks, while failing to patch `push` drops subsequent incremental stream chunks pushed during server rendering streams. Sources: [packages/next/src/client/app-index.tsx:176-185](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L176-L185) ```tsx const nextServerDataLoadingGlobal = (self.__next_f = self.__next_f || []) // Consume all buffered chunks and clear the global data array right after to release memory. // Otherwise it will be retained indefinitely. nextServerDataLoadingGlobal.forEach(nextServerDataCallback) nextServerDataLoadingGlobal.length = 0 // Patch its push method so subsequent chunks are handled (but not actually pushed to the array). nextServerDataLoadingGlobal.push = nextServerDataCallback ``` Sources: [packages/next/src/client/app-index.tsx:176-185](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L176-L185) When `DOMContentLoaded` fires or when writers register via `nextServerDataRegisterWriter`, buffered chunks stream into React's parser. If an instant navigation test fetch (`self.__next_instant_test`) is active, the inline Flight stream is left open without erroring to prevent React from logging missing data warnings while separate static payloads hydrate. ```tsx function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) { if (initialServerDataBuffer) { initialServerDataBuffer.forEach((val) => { ctr.enqueue(typeof val === 'string' ? encoder.encode(val) : val) }) if (initialServerDataLoaded && !initialServerDataFlushed) { // Instant Navigation Testing API: don't close or error the inline // Flight stream. The static shell has no inline Flight data, so the // stream is empty. Closing it would cause React to log an error about // missing data. Leaving it open lets React treat any holes as // "still suspended." Hydration uses the separately fetched RSC payload // (self.__next_instant_test), not this stream. if (isStreamErrorOrUnfinished(ctr)) { if (!instantTestStaticFetch) { ctr.error( new Error( 'The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.' ) ) } } else { ctr.close() } initialServerDataFlushed = true initialServerDataBuffer = undefined } } initialServerDataWriter = ctr } ``` Sources: [packages/next/src/client/app-index.tsx:127-156](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L127-L156) ## Build asset transformation and taskfile orchestration ### Compilation Task Definitions Repository-level compilation and asset packaging are governed by taskfile specifications and build constants defined across workspace packages. The taskfile orchestrates parallelized compilation blocks, transforming source files through SWC bindings and bundling dependencies for server, client, and edge targets. ```javascript export async function next_compile(task, opts) { await task.parallel( [ 'cli', 'copy_bundle_analyzer_ui', 'bin', 'server', 'server_esm', 'api_esm', 'nextbuild', 'nextbuildjest', 'nextbuildstatic', 'nextbuildstatic_esm', 'nextbuild_esm', 'next_devtools_entrypoint', 'next_devtools_server', 'next_devtools_server_esm', 'next_devtools_shared', 'next_devtools_shared_esm', 'next_devtools_userspace', 'next_devtools_userspace_esm', 'pages', 'pages_esm', 'lib', 'lib_esm', 'client', 'client_esm', 'diagnostics', 'telemetry', 'trace', 'shared', 'shared_esm', 'shared_re_exported', 'shared_re_exported_esm', 'server_wasm', 'experimental_testing', 'experimental_testmode', ], opts ) } ``` Sources: [packages/next/taskfile.js:2433-2473](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2433-L2473) The taskfile exports specific compilation procedures including `bin`, `cli`, `lib`, `server`, `client`, and `nextbuild`, assigning appropriate [SWC Compiler](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/swc-compiler) targets and options to each directory. | Task Name | Source Pattern | SWC Target Mode | Output Destination | | :--- | :--- | :--- | :--- | | **bin** | `src/bin/*` | `server` (strip extension) | `dist/bin` (mode 0755) | | **cli** | `src/cli/**/*.+(js|ts|tsx)` | `server` | `dist/cli` | | **lib** | `src/lib/**/!(*.test).+(js|ts|tsx|json|jsonc)` | `server` | `dist/lib` | | **server** | `src/server/**/!(*.test).+(js|ts|tsx)` | `server` | `dist/server` | | **client** | `src/client/**/!(*.test|*.stories).+(js|ts|tsx|woff2)` | `client` (interop default) | `dist/client` | Sources: [packages/next/taskfile.js:2485-2518](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2485-L2518), [packages/next/taskfile.js:2581-2586](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2581-L2586) > [!WARNING] > Compilation tasks exclude test files and fixture directories using explicit glob negation patterns like `!(*.test)` and ignore arrays to prevent build pollution in distribution directories. Sources: [packages/next/taskfile.js:2539-2547](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2539-L2547) ```javascript .source('src/build/**/*.+(js|ts|tsx)', { ignore: [ '**/fixture/**', '**/tests/**', '**/jest/**', '**/*.test.d.ts', '**/*.test.+(js|ts|tsx)', ], }) ``` Sources: [packages/next/taskfile.js:2539-2547](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2539-L2547) ## Where to go next | I want to… | Read | | --- | --- | | How do you set up, build, and run a minimal Next.js application from source or templates using the repository entry points? | [Quick Start](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/quick-start) | | What do the directories and packages in this repository represent and how are responsibilities partitioned across the tree? | [Project Structure](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/project-structure) | | How are packages, build pipelines, dependencies, and internal linkages wired together across the pnpm and Turborepo workspace? | [Monorepo Workspace](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/monorepo-workspace) | | How is the core Next.js HTTP server constructed across BaseServer, NextNodeServer, and base HTTP abstractions? | [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) | | How does an incoming HTTP request flow through matching, middleware, routing normalizers, and response payload dispatch? | [Request Lifecycle](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/request-lifecycle) | | How are App Router HTTP method handlers (GET, POST, etc.) and Pages API routes executed and wrapped? | [Route Handlers](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers) | | How does Next.js package, isolate, and execute middleware and route handlers within the V8 edge sandbox and Web standard APIs? | [Edge Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime) | | How are server responses, data fetch results, tags, and ISR artifacts cached, retrieved, and invalidated across memory and disk backends? | [Incremental Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) | | How does Next.js isolate request headers, cookies, params, and draft mode state per request using Node.js AsyncLocalStorage? | [Async Storage](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/async-storage) | | How does the server track dynamic data access, detect un-cached parameters, and trigger Partial Prerendering (PPR) or dynamic bailouts? | [Dynamic Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering) | | How does the App Router construct React Server Component component trees from route segment layouts and pages on the server? | [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) | | How does Next.js serialize React Server Component trees, Flight data streams, client references, and server actions across the wire? | [RSC Transport](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/rsc-transport) | | How does the legacy Pages Router render HTML via _document and _app with getStaticProps, getServerSideProps, and getInitialProps? | [Pages Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/pages-rendering) | | How does Next.js manage Node.js readable streams, Web Streams, Uint8Array chunk buffering, and React streaming renders? | [Stream Handling](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/stream-handling) | | How are React Server Actions dispatched, validated with CSRF protection, invoked, and serialized back to the client router? | [Server Actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions) | | How does Next.js perform compile-time and runtime boundary verification and sample tracking for dynamic vs static code paths? | [Instant Validation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/instant-validation) | | How does Next.js initialize the browser runtime, mount the root React tree, and register global error handlers? | [Client Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/client-runtime) | | How does the client-side App Router maintain the component tree, handle link navigations, and coordinate layout rendering? | [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) | | How do state transitions (navigate, refresh, restore, server actions) update the client-side App Router cache and component tree? | [Router Reducer](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/router-reducer) | | How does the client cache individual route segments, prefetch links, manage back-forward cache (bfcache), and decode RSC responses? | [Segment Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/segment-cache) | | How does `next build` coordinate compiler stages, type checking, bundle creation, route extraction, and production compilation? | [Build Pipeline](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/build-pipeline) | | How does the build pipeline discover files, validate route segments, parse segment configurations, and generate manifest JSONs? | [Route Discovery](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/route-discovery) | | How are static HTML, dynamic route params, ISR fallback pages, and static site export bundles compiled during the build? | [Static Generation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/static-generation) | | How are Rust-based SWC bindings installed, configured, and invoked for JavaScript/TypeScript and JSX transformations? | [SWC Compiler](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/swc-compiler) | | How does Next.js integrate Turbopack for production compilation, entry point resolution, and manifest loading? | [Turbopack Engine](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/turbopack-engine) | | How does Next.js construct its multi-target Webpack configurations for client, server, and Edge Runtime targets? | [Webpack Configuration](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/webpack-configuration) | | How do Next.js internal loaders (next-app-loader, next-flight-loader, next-swc-loader, next-route-loader) transform application source code? | [Webpack Loaders](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/webpack-loaders) | | How do build manifest, flight manifest, pages manifest, and font manifest Webpack plugins produce runtime manifest tables? | [Manifest Plugins](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/manifest-plugins) | | How does NextDevServer manage on-demand compilation, route matching, and development request handling? | [Development Server](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/development-server) | | How do Webpack and Turbopack hot reloaders propagate file change events over WebSockets to update the running browser application? | [Hot Reloading](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/hot-reloading) | | How does the Next.js dev overlay capture, parse, source-map, and display runtime errors, build errors, and code frames? | [Developer Overlay](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/developer-overlay) | | How does the developer overlay collect, profile, and render network request waterfall timings and cache status? | [Request Insights](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/request-insights) | | How do the `next dev`, `next build`, `next start`, `next info`, and `next export` CLI command handlers parse arguments and bootstrap execution? | [CLI Commands](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/cli-telemetry/cli-commands) | | How does `next-codemod` and the upgrade CLI transform legacy user code to modern Next.js APIs using jscodeshift transforms? | [Upgrade and Codemods](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/cli-telemetry/upgrade-and-codemods) | | How are anonymous usage statistics, feature adoption events, and error metrics recorded, flushed, and controlled? | [Telemetry](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/cli-telemetry/telemetry) | | How does Next.js instrument build and server spans using OpenTelemetry-compatible tracing infrastructure? | [Trace Profiling](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/cli-telemetry/trace-profiling) | | How does `next/image` resize, format-convert (AVIF/WebP), optimize, and cache images on demand on the server? | [Image Optimization](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/built-in-features/image-optimization) | | How do `next/font/google` and `next/font/local` download, extract fallback metrics, and generate CSS @font-face rules at build time? | [Font Optimization](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/built-in-features/font-optimization) | | How are static and dynamic metadata, OpenGraph tags, sitemaps, robots.txt, and manifests resolved and rendered into HTML head tags? | [Metadata Generation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/built-in-features/metadata-generation) | | How does `@next/third-parties` optimize loading Google Analytics, Tag Manager, YouTube embeds, and Google Maps? | [Third Party Libraries](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/built-in-features/third-party-libraries) | | How does the Next.js TypeScript language service plugin enforce segment config types and validate Server/Client component boundaries? | [TypeScript Plugin](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/built-in-features/typescript-plugin) | | How does the `create-next-app` scaffolding CLI validate destination directories, select templates, and install dependencies? | [Create Next App](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/create-next-app) | | How does the standalone `bundle-analyzer` web application parse, layout, diff, and visualize Next.js build module graph treemaps? | [Bundle Analyzer](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/bundle-analyzer) | | How do `eslint-plugin-next` and internal lint rules detect anti-patterns such as sync scripts, invalid head tags, and unoptimized images? | [ESLint Rules](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/eslint-rules) | | How does `devlow-bench` benchmark Next.js performance across build and dev runs, generate snapshots, and export metrics? | [Benchmark Harness](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/benchmark-harness) | | How does the `@next/routing` utility library resolve routes, destinations, and `_next/data` requests independently of the server? | [Routing Utility](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/routing-utility) | ## Related - [Quick Start](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/quick-start) - [Project Structure](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/project-structure) - [Monorepo Workspace](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/monorepo-workspace) - [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) --- ## Technical docs: Middleware Request Cookie Parsing URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/how-it-works/middleware-request-cookie-parsing
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts) - [packages/next/src/shared/lib/router/utils/prepare-destination.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts) - [packages/next/src/server/api-utils/get-cookie-parser.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts)
## Overview ### Request Middleware and Cookie Parsing Execution Flow The `HandleCatchallMiddlewareRequest -> GetCookieParser` process describes how Next.js catches incoming requests intended for middleware handling, validates them against defined route matchers and conditional rules (such as checking headers, cookies, or queries), and extracts request cookies dynamically when evaluating routing conditions. This execution path begins inside `NextNodeServer` when a request flagged with metadata indicating a middleware invocation is intercepted. The server retrieves the middleware configuration, compiles or looks up its route matchers, evaluates any conditional `has` or `missing` rules—which may parse incoming request cookies on-demand—and prepares the environment to execute the middleware function. Sources: [packages/next/src/server/next-server.ts:1943-1952](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L1952) --- ## Step-by-Step Execution Trace ### 1. Handling Catchall Middleware Requests The entry point for this flow is `handleCatchallMiddlewareRequest` within `NextNodeServer`. When an HTTP request enters the Node server, it checks whether the `middlewareInvoke` request metadata flag is set. If the flag is absent, the handler returns `false` to let other route handlers process the request. Otherwise, it retrieves the active middleware item and normalizes the request pathname, taking into account any configured internationalization (`i18n`) segments and trailing slashes. Sources: [packages/next/src/server/next-server.ts:1943-1972](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L1972) ### 2. Retrieving Middleware Configuration Next, `getMiddleware` is called to fetch the active middleware routing item from the server's middleware manifest or fallback node environment. It checks if a root middleware exists at `['/']`, and if so, acquires its compiled route matcher functions. Sources: [packages/next/src/server/next-server.ts:1588-1612](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1588-L1612) ### 3. Fetching Middleware Matchers To determine whether the request path matches the middleware's configuration, `getMiddlewareMatcher` is invoked with the middleware manifest item. This function consults a weak cache (`MiddlewareMatcherCache`) to avoid recompiling regex patterns repeatedly for the same middleware info object. If a cached matcher is not found, it passes the configuration's matchers array to `getMiddlewareRouteMatcher`. Sources: [packages/next/src/server/next-server.ts:179-196](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L179-L196) ### 4. Executing Route Matching `getMiddlewareRouteMatcher` returns a closure that evaluates incoming pathnames against an array of proxy matchers. For each matcher, it attempts to execute its compiled regular expression against the request pathname. If the path matches and the matcher specifies conditional rules via `has` or `missing` properties, execution proceeds to evaluate those constraints. Sources: [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts#L14-L36) ### 5. Evaluating Conditional Route Match Constraints The `matchHas` function inspects additional constraints (`has` or `missing`) defined on the route matcher. It iterates over each constraint item, validating properties based on their declared type (such as `header`, `cookie`, `query`, or `host`). Sources: [packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-60](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L48-L60) ### 6. Checking Cookie and Header Values Inside `hasMatch`, when evaluating a constraint of type `'cookie'`, the code checks if a pre-parsed `cookies` object exists directly on the request. If cookies are not attached to the request object yet, it falls back to dynamically parsing them from request headers. Sources: [packages/next/src/shared/lib/router/utils/prepare-destination.ts:66-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L66-L75) ### 7. Parsing Request Cookies on Demand If cookie values are required for conditional matching and are missing from the request object, `getCookieParser` is invoked with `req.headers`. It returns a curried `parseCookie` function which extracts the `cookie` header, safely handles single or multi-value cookie arrays, and invokes Next.js's compiled cookie parser utility to return a dictionary of parsed cookies. Sources: [packages/next/src/server/api-utils/get-cookie-parser.ts:8-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts#L8-L21) --- ## Architectural Diagrams ### Sequence Diagram ```mermaid sequenceDiagram participant Server as NextNodeServer (next-server.ts) participant MatcherUtil as MiddlewareRouteMatcher (middleware-route-matcher.ts) participant PrepareDest as PrepareDestination (prepare-destination.ts) participant CookieParser as CookieParser (get-cookie-parser.ts) Server->>Server: handleCatchallMiddlewareRequest() Server->>Server: getMiddleware() Server->>Server: getMiddlewareMatcher() Server->>MatcherUtil: getMiddlewareRouteMatcher(matchers) MatcherUtil->>PrepareDest: matchHas(req, query, has, missing) alt type === 'cookie' PrepareDest->>CookieParser: getCookieParser(req.headers) CookieParser-->>PrepareDest: parseCookie() function PrepareDest->>PrepareDest: Extract cookie value end PrepareDest-->>MatcherUtil: returns match result (true/false) MatcherUtil-->>Server: returns boolean match status ``` Sources: [packages/next/src/server/next-server.ts:179-196](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L179-L196), [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts#L14-L36), [packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L48-L75), [packages/next/src/server/api-utils/get-cookie-parser.ts:8-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts#L8-L21) ### Flowchart ```mermaid flowchart TD A[Handle Request] --> B{Is Middleware Invoke?} B -- No --> C[Return false] B -- Yes --> D[Get Middleware & Matcher] D --> E[Evaluate Pathname Match] E --> F{Has match & conditional rules?} F -- No --> G[Finish / Skip] F -- Yes --> H[Evaluate matchHas] H --> I{Cookie Rule Present?} I -- No --> J[Match Success] I -- Yes --> K{Cookies on Request?} K -- Yes --> L[Read req.cookies] K -- No --> M[Call getCookieParser] M --> N[Parse Cookie Headers] N --> O[Check Condition Values] O --> P[Run Middleware Execution] ``` Sources: [packages/next/src/server/next-server.ts:1943-1988](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L1988), [packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts:14-36](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/middleware-route-matcher.ts#L14-L36), [packages/next/src/shared/lib/router/utils/prepare-destination.ts:48-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/prepare-destination.ts#L48-L75), [packages/next/src/server/api-utils/get-cookie-parser.ts:8-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/get-cookie-parser.ts#L8-L21) --- ## Key Observations > [!IMPORTANT] > **Lazy Cookie Parsing:** Cookies are not parsed preemptively for every incoming request. They are only parsed when a route matcher defines conditional `has` or `missing` rules relying on cookie values and those cookies are not already populated on the request object. > [!TIP] > **Matcher Caching:** `NextNodeServer` utilizes a `WeakMap` (`MiddlewareMatcherCache`) indexed by middleware manifest items, preventing redundant compilation of route regex and condition matchers across requests. - **Cross-Module Boundaries:** This flow bridges the core server execution logic (`next-server.ts`), routing utilities (`middleware-route-matcher.ts` and `prepare-destination.ts`), and HTTP API helper utilities (`get-cookie-parser.ts`). - **Error Resilience:** Malformed URI components encountered during pathname decoding are safely caught and treated as non-fatal, allowing the matcher to fall back gracefully or skip matching without crashing the server process. --- ## Technical docs: Quick Start URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/quick-start
Relevant source files The following files were used as context for generating this wiki page: - [packages/create-next-app/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts) - [packages/create-next-app/create-app.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/create-app.ts) - [packages/next/src/build/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/index.ts) - [packages/next/taskfile.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js) - [packages/next/src/bin/next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/bin/next.ts) - [packages/create-next-app/templates/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts) - [packages/create-next-app/helpers/examples.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/helpers/examples.ts) - [packages/next/src/cli/next-dev.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/cli/next-dev.ts) - [packages/create-next-app/templates/app/js/app/page.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js) - [packages/next/src/cli/next-build.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/cli/next-build.ts) - [packages/create-next-app/templates/default/js/pages/index.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/js/pages/index.js) - [run-evals.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/run-evals.js) - [packages/create-next-app/templates/default-tw/js/pages/index.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default-tw/js/pages/index.js) - [packages/create-next-app/templates/app-tw/js/app/page.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw/js/app/page.js) - [packages/next/src/cli/next-start.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/cli/next-start.ts) - [packages/next-codemod/bin/next-codemod.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/bin/next-codemod.ts) - [package.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/package.json) - [packages/next/app.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/app.js) - [packages/create-next-app/templates/app-empty/js/app/page.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-empty/js/app/page.js) - [packages/create-next-app/templates/app/ts/app/page.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/ts/app/page.tsx) - [packages/create-next-app/templates/default-tw/ts/pages/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default-tw/ts/pages/index.tsx) - [packages/create-next-app/templates/app-tw-empty/js/app/page.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw-empty/js/app/page.js) - [packages/next/package.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json) - [packages/create-next-app/templates/app-tw/ts/app/page.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw/ts/app/page.tsx) - [packages/create-next-app/templates/default/ts/pages/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/ts/pages/index.tsx) - [packages/create-next-app/templates/app/ts/tsconfig.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/ts/tsconfig.json)
## Overview Getting started with Next.js involves initializing development environments, configuring project scaffolding via [Create Next App](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/create-next-app), and compiling the framework packages from source. These foundational workflows establish clean architectural starting points for both modern [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) and classic Pages Router applications. Sources: [packages/create-next-app/index.ts:50-57](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L50-L57), [packages/create-next-app/create-app.ts:72-73](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/create-app.ts#L72-L73), [packages/next/taskfile.js:2785-2788](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2785-L2788) ## Bootstrapping with Create Next App ### CLI Invocation and Argument Parsing The [Create Next App](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/create-next-app) entry point is implemented in `packages/create-next-app/index.ts` using Commander. It configures the root command with version output (`-v, --version`), help options (`-h, --help`), and an optional positional argument `[directory]` for the target project path. Signal handlers for `SIGINT` and `SIGTERM` invoke `process.exit(0)`, while prompt state monitoring intercepts aborted prompts to restore the terminal cursor (`\x1B[?25h`) before exiting with status code `1`. Sources: [packages/create-next-app/index.ts:1-49](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L1-L49), [packages/create-next-app/index.ts:22-39](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L22-L39) > [!WARNING] > Commander does not natively support negated options. When users pass negated flags like `--no-agent-feedback`, Commander interprets them as the positional project name argument in the action handler, requiring explicit prefix checks against `--no-` to prevent misinterpreting flags as file paths. Sources: [packages/create-next-app/index.ts:124-130](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L124-L130) The CLI supports a broad range of boolean flags and options to configure project features prior to scaffolding: | Flag / Option | Description | Default | | :--- | :--- | :--- | | `--ts, --typescript` | Initialize as a TypeScript project | Enabled | | `--js, --javascript` | Initialize as a JavaScript project | Disabled | | `--tailwind` | Initialize with Tailwind CSS config | Enabled | | `--react-compiler` | Initialize with React Compiler enabled | Disabled | | `--cache-components` | Initialize with Cache Components enabled | Disabled | | `--eslint` | Initialize with ESLint config | Disabled | | `--biome` | Initialize with Biome config | Disabled | | `--app` | Initialize as an App Router project | Disabled | | `--src-dir` | Initialize inside a `src/` directory | Disabled | | `--rspack` | Enable Rspack as the bundler | Disabled | | `--import-alias ` | Specify import alias to use | `@/*` | | `--api` | Initialize a headless API using App Router | Disabled | | `--empty` | Initialize an empty project | Disabled | | `--use-npm` | Force scaffolding via npm | Disabled | | `--use-pnpm` | Force scaffolding via pnpm | Disabled | | `--use-yarn` | Force scaffolding via Yarn | Disabled | | `--use-bun` | Force scaffolding via Bun | Disabled | | `--reset, --reset-preferences` | Reset saved `create-next-app` preferences | Disabled | | `--skip-install` | Skip installing packages | Disabled | | `--yes` | Use saved preferences or defaults | Disabled | | `-e, --example ` | Bootstrap from example name or public GitHub URL | Disabled | | `--example-path ` | Specify subdirectory path for complex GitHub URLs | Disabled | | `--agents-md` | Include `AGENTS.md` for coding agents | Enabled | | `--agent-feedback` | Prepare anonymized Next.js feedback | Disabled | | `--disable-git` | Skip initializing a git repository | Disabled | Sources: [packages/create-next-app/index.ts:50-122](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L50-L122) ### Package Manager Resolution and Preference Management Package manager selection evaluates explicit CLI flags in sequence before falling back to environment detection. If none of `--use-npm`, `--use-pnpm`, `--use-yarn`, or `--use-bun` are passed, the CLI invokes `getPkgManager()` to inspect the invoking user agent environment. Sources: [packages/create-next-app/index.ts:137-146](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L137-L146) ```typescript const packageManager: PackageManager = !!opts.useNpm ? 'npm' : !!opts.usePnpm ? 'pnpm' : !!opts.useYarn ? 'yarn' : !!opts.useBun ? 'bun' : getPkgManager() ``` Sources: [packages/create-next-app/index.ts:137-146](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L137-L146) Preferences are persisted using the `conf` package with `projectName: 'create-next-app'`. Passing `--reset` or `--reset-preferences` prompts the user for confirmation via a `prompts` toggle before clearing the configuration store with `conf.clear()`. Sources: [packages/create-next-app/index.ts:148-165](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L148-L165) ### Interactive Setup and Project Validation If no positional project directory is provided via the command line, the `run()` function invokes an interactive `prompts` text prompt requesting a project name with an initial default of `my-app`. Input values are validated using `validateNpmName` wrapped around `basename(resolve(name))`. Sources: [packages/create-next-app/index.ts:167-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L167-L190) ```typescript if (!projectPath) { const res = await prompts({ onState: onPromptState, type: 'text', name: 'path', message: 'What is your project named?', initial: 'my-app', validate: (name) => { const validation = validateNpmName(basename(resolve(name))) if (validation.valid) { return true } return 'Invalid project name: ' + validation.problems[0] }, }) if (typeof res.path === 'string') { projectPath = res.path.trim() } } ``` Sources: [packages/create-next-app/index.ts:171-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L171-L190) If `projectPath` remains empty after prompting, the CLI prints usage instructions displaying the dynamic executable name (`opts.name()`) and terminates with exit code `1`. When a path is successfully resolved, `validateNpmName` runs again against the computed `appName` before proceeding to template generation and file extraction. Sources: [packages/create-next-app/index.ts:192-214](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/index.ts#L192-L214) ## Template Layout Selection and Generation ### Project Template Copying and Filtering The template generation pipeline is executed by the `installTemplate` function, which determines the target source directory by joining `__dirname`, the selected `template` string, and the `mode` identifier (`js` or `ts`). File copying relies on the `copy` utility with a base glob source of `["**"]`. Depending on user flags, specific configuration files are explicitly excluded from the copy operation: * If `eslint` is disabled, `!eslint.config.mjs` is appended to the exclusion array. * If `biome` is disabled, `!biome.json` is appended to the array. * If `tailwind` is disabled or `bundler` is set to `Bundler.Turbopack`, `!postcss.config.mjs` is excluded. ```typescript const isApi = template === "app-api"; const templatePath = path.join(__dirname, template, mode); const copySource = ["**"]; if (!eslint) copySource.push("!eslint.config.mjs"); if (!biome) copySource.push("!biome.json"); if (!tailwind || bundler === Bundler.Turbopack) { copySource.push("!postcss.config.mjs"); } ``` Sources: [packages/create-next-app/templates/index.ts:72-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L72-L80) The file renaming function maps specific source filenames to destination filenames during extraction. Specifically, `gitignore` is prefixed with a dot to become `.gitignore`, and `README-template.md` is renamed to `README.md` to avoid being ignored by asset relocation utilities. All other filenames pass through unchanged. ```typescript rename(name) { switch (name) { case "gitignore": { return `.${name}`; } // README.md is ignored by webpack-asset-relocator-loader used by ncc: // https://github.com/vercel/webpack-asset-relocator-loader/blob/e9308683d47ff507253e37c9bcbb99474603192b/src/asset-relocator.js#L227 case "README-template.md": { return "README.md"; } default: { return name; } } }, ``` Sources: [packages/create-next-app/templates/index.ts:84-98](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L84-L98) > [!NOTE] > `README-template.md` is renamed to `README.md` during copying specifically because `webpack-asset-relocator-loader` used by `ncc` ignores files matching `README.md` patterns in templates. > Sources: [packages/create-next-app/templates/index.ts:89-93](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L89-L93) ### Bundler and Compiler Configuration Modifiers Post-copy configuration injection modifies either `next.config.mjs` or `next.config.ts` depending on the project `mode`. When `bundler` is set to `Bundler.Rspack`, `next-rspack` is imported and wraps the exported configuration object. When `tailwind` is enabled alongside `Turbopack`, a `turbopack.rules` configuration block is inserted to register `@tailwindcss/turbopack` loader rules for CSS files. Additional feature flags like `reactCompiler`, `cacheComponents`, and `agentFeedback` inject their corresponding options into the next configuration file. | Feature Flag / Bundler | Target Config Property / Transformation | Source File & Line Range | | :--- | :--- | :--- | | `Bundler.Rspack` | Wraps config with `withRspack(nextConfig)` and imports `next-rspack` | [packages/create-next-app/templates/index.ts:101-114](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L101-L114) | | `tailwind` + `Turbopack` | Inserts `turbopack.rules["*.css"]` with `@tailwindcss/turbopack` loader | [packages/create-next-app/templates/index.ts:116-138](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L116-L138) | | `reactCompiler` | Inserts boolean property `reactCompiler: true` | [packages/create-next-app/templates/index.ts:140-153](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L140-L153) | | `cacheComponents` | Inserts `cacheComponents: true` and `partialPrefetching: true` | [packages/create-next-app/templates/index.ts:155-171](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L155-L171) | | `agentFeedback` | Inserts `experimental: { agentFeedback: true }` | [packages/create-next-app/templates/index.ts:173-186](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L173-L186) | Sources: [packages/create-next-app/templates/index.ts:101-186](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L101-L186) > [!TIP] > Enabling `cacheComponents` automatically forces `partialPrefetching: true` in the generated Next.js configuration because partial prefetching is a required runtime prerequisite for component caching. > Sources: [packages/create-next-app/templates/index.ts:155-168](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L155-L168) ### TypeScript and Import Alias Resolution TypeScript configuration files (`tsconfig.json` or `jsconfig.json`) are updated to reflect the chosen `srcDir` structure and custom `importAlias`. The compiler options path mapping for `@/*` is rewritten to either `"./*"` or `"./src/*"` depending on `srcDir`, and subsequently replaced entirely with the user-specified `importAlias`. ```json "paths": { "@/*": ["./*"] } }, ``` Sources: [packages/create-next-app/templates/app/ts/tsconfig.json:21-24](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/ts/tsconfig.json#L21-L24) If the selected `importAlias` differs from the default `@/*`, a glob traversal scans the project root excluding config files, `.git` directories, fonts, and favicon binaries. Using a concurrency semaphore capacity of 8, every matching file updates its internal import statements by replacing `@/` with the normalized custom alias prefix. ```typescript if (importAlias !== "@/*") { const files = await glob("**/*", { cwd: root, dot: true, stats: false, // We don't want to modify compiler options in [ts/js]config.json // and none of the files in the .git folder // TODO: Refactor this to be an allowlist, rather than a denylist, // to avoid corrupting files that weren't intended to be replaced ignore: [ "tsconfig.json", "jsconfig.json", ".git/**/*", "**/fonts/**", "**/favicon.ico", ], }); const writeSema = new Sema(8, { capacity: files.length }); await Promise.all( files.map(async (file) => { await writeSema.acquire(); const filePath = path.join(root, file); if ((await fs.stat(filePath)).isFile()) { await fs.writeFile( filePath, (await fs.readFile(filePath, "utf8")).replace( `@/`, `${importAlias.replace(/\*/g, "")}`, ), ); } writeSema.release(); }), ); } ``` Sources: [packages/create-next-app/templates/index.ts:203-238](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L203-L238) > [!WARNING] > When a custom import alias is configured, file contents across the workspace are mutated via string replacement. Config files like `tsconfig.json` and asset paths including fonts and favicons are explicitly excluded via glob ignore patterns to prevent corruption. > Sources: [packages/create-next-app/templates/index.ts:213-220](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts#L213-L220) ## App Router Starter Structures ### Default Component Layouts and Styling Variants The `create-next-app` scaffolding tool provides multiple starter page templates for the App Router, available in both JavaScript and TypeScript variants. Standard CSS Module templates import `styles from "./page.module.css"` and render container wrappers using modular class names such as `styles.page`, `styles.main`, and `styles.intro`, while Tailwind CSS templates rely directly on utility classes like `flex flex-col flex-1 items-center justify-center`. Empty starter variations simplify the page structure down to a single `main` element containing a greeting message. | Starter Template | File Path | Styling Mechanism | Root Element / Class | | :--- | :--- | :--- | :--- | | Standard JS | `packages/create-next-app/templates/app/js/app/page.js` | CSS Modules | `
` | | Standard TS | `packages/create-next-app/templates/app/ts/app/page.tsx` | CSS Modules | `
` | | Tailwind JS | `packages/create-next-app/templates/app-tw/js/app/page.js` | Tailwind CSS | `flex flex-col flex-1 items-center justify-center` | | Tailwind TS | `packages/create-next-app/templates/app-tw/ts/app/page.tsx` | Tailwind CSS | `flex flex-col flex-1 items-center justify-center` | | Empty JS | `packages/create-next-app/templates/app-empty/js/app/page.js` | None | `
` | | Tailwind Empty JS | `packages/create-next-app/templates/app-tw-empty/js/app/page.js` | None | `
` | Sources: [packages/create-next-app/templates/app/js/app/page.js:1-69](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L1-L69), [packages/create-next-app/templates/app/ts/app/page.tsx:1-69](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/ts/app/page.tsx#L1-L69), [packages/create-next-app/templates/app-tw/js/app/page.js:1-69](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw/js/app/page.js#L1-L69), [packages/create-next-app/templates/app-tw/ts/app/page.tsx:1-69](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw/ts/app/page.tsx#L1-L69), [packages/create-next-app/templates/app-empty/js/app/page.js:1-7](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-empty/js/app/page.js#L1-L7), [packages/create-next-app/templates/app-tw-empty/js/app/page.js:1-7](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw-empty/js/app/page.js#L1-L7) > [!NOTE] > The default starter component is always exported as a default function named `Home` (`export default function Home()`), serving as the React Server Component entry point for the App Router root segment. > Sources: [packages/create-next-app/templates/app/js/app/page.js:4-4](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L4-L4), [packages/create-next-app/templates/app-tw/ts/app/page.tsx:3-3](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw/ts/app/page.tsx#L3-L3) ### Asset Imports and External Links Standard and Tailwind templates integrate optimized image assets via `next/image`, rendering both the Next.js logo from `/next.svg` and the Vercel logomark from `/vercel.svg`. The Next.js logo image component explicitly includes the `priority` boolean attribute to optimize the Largest Contentful Paint (LCP) metric during initial page load. ```javascript Next.js logo ``` Sources: [packages/create-next-app/templates/app/js/app/page.js:8-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L8-L15), [packages/create-next-app/templates/app-tw/js/app/page.js:7-14](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app-tw/js/app/page.js#L7-L14) External anchor elements embedded within the starter pages link users directly to external resources, incorporating specific campaign query parameters across their `href` attributes. These links point to template galleries, learning centers, deployment platforms, and official documentation. | Link Target Purpose | Destination URL | Campaign Query Parameters | | :--- | :--- | :--- | | Templates Gallery | `https://vercel.com/templates` | `?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app` | | Learning Center | `https://nextjs.org/learn` | `?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app` | | Vercel Deployment | `https://vercel.com/new` | `?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app` | | Documentation | `https://nextjs.org/docs` | `?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app` | Sources: [packages/create-next-app/templates/app/js/app/page.js:23-38](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L23-L38), [packages/create-next-app/templates/app/js/app/page.js:42-64](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L42-L64) > [!WARNING] > External anchor elements targeting external documentation or deployment platforms explicitly set `target="_blank"` alongside `rel="noopener noreferrer"` to prevent tab-nabbing security vulnerabilities. > Sources: [packages/create-next-app/templates/app/js/app/page.js:25-26](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L25-L26), [packages/create-next-app/templates/app/js/app/page.js:45-46](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/app/js/app/page.js#L45-L46) ## Pages Router Starter Structures ### Typography and Font Configuration Classic Pages Router starter templates load variable fonts using `next/font/google`. Both JavaScript and TypeScript variants for default CSS modules and Tailwind CSS configure the `Geist` and `Geist_Mono` font loaders with latin subsets and custom CSS variables. ```javascript const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"], }); const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"], }); ``` Sources: [packages/create-next-app/templates/default/js/pages/index.js:6-14](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/js/pages/index.js#L6-L14), [packages/create-next-app/templates/default-tw/js/pages/index.js:4-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default-tw/js/pages/index.js#L4-L12) > [!NOTE] > Font configuration variables `--font-geist-sans` and `--font-geist-mono` are attached directly to the root container class string alongside layout styles or utility classes. > Sources: [packages/create-next-app/templates/default/js/pages/index.js:25-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/js/pages/index.js#L25-L27), [packages/create-next-app/templates/default-tw/js/pages/index.tsx:16-18](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default-tw/ts/pages/index.tsx#L16-L18) ### Metadata and Document Head Setup Default CSS module starter templates for the Pages Router include explicit document metadata using `next/head`. Within the exported `Home` component, the `` block injects the document title, meta description, viewport settings, and favicon link into the page header. ```javascript Create Next App ``` Sources: [packages/create-next-app/templates/default/js/pages/index.js:19-24](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/js/pages/index.js#L19-L24), [packages/create-next-app/templates/default/ts/pages/index.tsx:19-24](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/ts/pages/index.tsx#L19-L24) ### Component Layout and Asset Rendering All Pages Router starter templates export a default function named `Home` rendering the primary landing view. The layouts incorporate `next/image` to render the Next.js logo from `/next.svg` with the `priority` attribute enabled, alongside the Vercel logomark from `/vercel.svg`. Starter templates point to specific documentation targets depending on styling configuration. Tailwind templates link directly to the Pages Router documentation path (`https://nextjs.org/docs/pages/getting-started`), whereas default CSS module templates link to the general documentation root (`https://nextjs.org/docs`). | Template Variant | File Path | Documentation URL | | :--- | :--- | :--- | | Default CSS (JS) | `pages/index.js` | `https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app` | | Default CSS (TS) | `pages/index.tsx` | `https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app` | | Tailwind (JS) | `pages/index.js` | `https://nextjs.org/docs/pages/getting-started?utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app` | | Tailwind (TS) | `pages/index.tsx` | `https://nextjs.org/docs/pages/getting-started?utm_source=create-next-app&utm_medium=default-template-tw&utm_campaign=create-next-app` | Sources: [packages/create-next-app/templates/default/js/pages/index.js:16-16](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/js/pages/index.js#L16-L16), [packages/create-next-app/templates/default-tw/js/pages/index.js:70-76](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default-tw/js/pages/index.js#L70-L76), [packages/create-next-app/templates/default/ts/pages/index.tsx:78-85](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default/ts/pages/index.tsx#L78-L85), [packages/create-next-app/templates/default-tw/ts/pages/index.tsx:70-76](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/default-tw/ts/pages/index.tsx#L70-L76) ## Building Next.js from Source ### Workspace Compilation and Task Management Compiling internal repository packages and preparing runtime assets requires executing workspace build pipelines and taskfile configurations defined across package scripts. Root and package-level scripts orchestrate Turborepo and Taskr workflows to clear directories, compile typescript declarations, bundle server and client runtimes, and build native binaries. The root workspace orchestrates concurrent compilation across packages using Turborepo and pnpm scripts. Developers can execute a full system clean via `pnpm clean`, which filters through package directories to purge `dist` folders and intermediate artifacts. Building all packages from source utilizes `pnpm build` or `pnpm build-all`, triggering remote caching and task summarization. Within the `packages/next` workspace directory, local development and production releases rely on taskr workflows configured in `taskfile.js`. The package file declares taskr requirements loading webpack, ncc, swc, and watch plugins. | Script / Command | Target Action | Purpose | | :--- | :--- | :--- | | `pnpm clean` | `packages/**` | Purges `dist` outputs and intermediate build artifacts across workspace packages | | `pnpm build` | Turborepo | Executes root [build pipeline](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/build-pipeline) with remote caching and summarization | | `pnpm build-all` | Turborepo | Builds all packages including native auto binaries | | `pnpm dev` | `packages/next` | Invokes cross-env with `NEXT_SERVER_NO_MANGLE=1` running taskr in development mode | | `taskr release` | `packages/next` | Clears distribution directories and starts production build workflows | Sources: [package.json:12-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/package.json#L12-L15), [packages/next/package.json:87-104](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L87-L104) > [!WARNING] > Running `pnpm clean` deletes `dist` folders across all packages in the workspace; ensure any uncommitted build products are accounted for before purging intermediate artifacts. > Sources: [package.json:12-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/package.json#L12-L12) ### Taskfile Watch Workflows and Bundling The default taskfile export clears the `dist` directory and initiates watch workflows mapped to individual source directories inside `packages/next/src`. Each source subdirectory maps to specific bundle targets and compilation routines handling server runtimes, client entrypoints, api modules, shared modules, and experimental features. ```javascript export default async function (task) { const opts = { dev: true } await task.clear('dist') await task.start('build', opts) await task.watch('src/bin', 'bin', opts) await task.watch('src/pages', 'pages', opts) await task.watch('src/server', ['server', 'server_esm', 'server_wasm'], opts) await task.watch('src/api', 'api_esm', opts) await task.watch( 'src/build', ['nextbuild', 'nextbuild_esm', 'nextbuildjest'], opts ) await task.watch( 'src/next-devtools', [ 'next_devtools_entrypoint', 'next_devtools_server', 'next_devtools_server_esm', 'next_devtools_shared', 'next_devtools_shared_esm', 'next_devtools_userspace', 'next_devtools_userspace_esm', ], opts ) await task.watch('src/experimental/testing', 'experimental_testing', opts) await task.watch('src/experimental/testmode', 'experimental_testmode', opts) await task.watch('src/export', 'nextbuildstatic', opts) await task.watch('src/export', 'nextbuildstatic_esm', opts) await task.watch('src/client', 'client', opts) await task.watch('src/client', 'client_esm', opts) await task.watch('src/diagnostics', 'diagnostics', opts) await task.watch('src/lib', 'lib', opts) await task.watch('src/lib', 'lib_esm', opts) await task.watch('src/cli', 'cli', opts) await task.watch('src/telemetry', 'telemetry', opts) await task.watch('src/trace', 'trace', opts) await task.watch( 'src/shared', ['shared_re_exported', 'shared_re_exported_esm', 'shared', 'shared_esm'], opts ) } ``` Sources: [packages/next/taskfile.js:2785-2828](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L285-L2828) Production and development bundling for application runtimes utilize dedicated webpack configurations with turbo options enabled or disabled depending on the target task variant. For instance, `next_bundle_app_prod`, `next_bundle_app_dev`, `next_bundle_app_prod_turbo`, and `next_bundle_app_dev_turbo` invoke `next-runtime.webpack-config` with distinct parameters for bundle types and compilation flags. Type definitions are generated via `generate_types`, executing `pnpm run types` with optional watch flags and preserving watch output when requested. ```javascript export async function generate_types(task, opts) { const watchmode = opts.dev const typesPromise = execa( 'pnpm', [ 'run', 'types', ...(watchmode ? ['--watch', '--preserveWatchOutput'] : []), ], { stdio: 'inherit' } ) // In watch-mode the process never completes i.e. the Promise never resolve. // But taskr needs to know that it can start watching the files for the task it has to manually restart. if (!watchmode) { await typesPromise } } ``` Sources: [packages/next/taskfile.js:2767-2783](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2767-L2783), [packages/next/taskfile.js:2909-2952](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2909-L2952) ## Related - [Overview](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/overview) - [Project Structure](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/project-structure) - [CLI Commands](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/cli-telemetry/cli-commands) --- ## Technical docs: Project Structure URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/project-structure
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/build/turborepo-access-trace/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/turborepo-access-trace/index.ts) - [apps/bundle-analyzer/components/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/components/index.ts) - [apps/bundle-analyzer/app/page.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/app/page.tsx) - [packages/next/src/build/swc/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/swc/index.ts) - [packages/next/src/build/adapter/build-complete.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/adapter/build-complete.ts) - [packages/third-parties/src/google/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/third-parties/src/google/index.tsx) - [packages/next-routing/src/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-routing/src/index.ts) - [packages/next/src/build/webpack/loaders/next-app-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-app-loader/index.ts) - [apps/bundle-analyzer/components/analyzer.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/components/analyzer.tsx) - [packages/next/src/server/lib/app-dir-module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/app-dir-module.ts) - [packages/next/src/server/dev/hot-reloader-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/hot-reloader-turbopack.ts) - [packages/next/src/next-devtools/dev-overlay/components/dialog/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay/components/dialog/index.ts) - [apps/bundle-analyzer/lib/analyze-data.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/analyze-data.ts) - [packages/next-codemod/lib/agents-md.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts) - [packages/next/src/build/nft.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/nft.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/next-devtools/dev-overlay/components/overlay/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay/components/overlay/index.tsx) - [packages/next/src/next-devtools/entrypoint.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/entrypoint.ts) - [packages/next/src/experimental/testing/server/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/experimental/testing/server/index.ts) - [packages/next/src/server/app-render/instant-validation/instant-validation.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/instant-validation/instant-validation.tsx) - [apps/bundle-analyzer/lib/types.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/types.ts) - [packages/next/src/server/route-modules/app-route/shared-modules.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/shared-modules.ts) - [packages/next/src/build/analyze/graph-dump.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/analyze/graph-dump.ts) - [sgconfig.yml](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/sgconfig.yml) - [packages/next/src/next-devtools/dev-overlay/segment-explorer-trie.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay/segment-explorer-trie.ts) - [packages/next/src/bundles/webpack/packages/package.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/bundles/webpack/packages/package.js) - [apps/bundle-analyzer/lib/module-graph.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/module-graph.ts) - [packages/next/src/next-devtools/userspace/app/errors/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/index.ts) - [packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx) - [packages/next/src/next-devtools/dev-overlay.browser.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx)
## Overview The Next.js repository is structured as a monorepo containing standalone web applications, core core compiler and runtime packages, and specialized developer utilities. This architecture partitions code boundaries between the main runtime engine, build-time asset tracing and analysis subsystems, internal routing layers, and developer-facing overlays. Sources: [apps/bundle-analyzer/app/page.tsx:1-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/app/page.tsx#L1-L5), [packages/next/src/build/turborepo-access-trace/index.ts:1-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/turborepo-access-trace/index.ts#L1-L5) ## Repository Root and Workspace Layout ### Structural Search Configuration The repository root houses configuration infrastructure governing structural analysis and pattern matching across the [monorepo workspace](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/monorepo-workspace). Specifically, the configuration file `sgconfig.yml` defines paths for structural search rules, tests, and utility directories. ```yaml # yaml-language-server: $schema=https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/project.json ruleDirs: - .config/ast-grep/rules testConfigs: - testDir: .config/ast-grep/rule-tests utilDirs: - .config/ast-grep/rule-utils ``` Sources: [sgconfig.yml:1-8](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/sgconfig.yml#L1-L8) The ast-grep configuration maps custom rule definitions and verification suites to designated directory paths under the workspace root. | Configuration Key | Target Path | Purpose | | :--- | :--- | :--- | | `ruleDirs` | `.config/ast-grep/rules` | Houses structural search and lint rules | | `testConfigs[0].testDir` | `.config/ast-grep/rule-tests` | Locates test suites validating ast-grep rules | | `utilDirs` | `.config/ast-grep/rule-utils` | Contains shared utility scripts for custom rules | ```yaml ruleDirs: - .config/ast-grep/rules testConfigs: - testDir: .config/ast-grep/rule-tests utilDirs: - .config/ast-grep/rule-utils ``` Sources: [sgconfig.yml:3-8](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/sgconfig.yml#L3-L8) > [!NOTE] > The ast-grep language server schema is explicitly bound via the YAML comment header pointing to the official remote JSON schema definition. ```yaml # yaml-language-server: $schema=https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/project.json ``` Sources: [sgconfig.yml:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/sgconfig.yml#L1-L1) ## Standalone Applications in Apps ### Component Layer and UI Architecture The `apps` workspace tree houses independent internal web utilities designed to inspect and diagnose build outputs, such as the `bundle-analyzer` application. This standalone application partitions its architecture into web components, view controllers, binary parsing engines, and layout utilities to process Next.js build module graphs and treemaps. The [bundle analyzer](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/bundle-analyzer) web application exports core visualization and navigation components from its module index, including import chains, route typeaheads, treemap visualizers, and error states. ```typescript export { ImportChain } from './import-chain' export { RouteTypeahead } from './route-typeahead' export { TreemapVisualizer } from './treemap-visualizer' export { ErrorState } from './error-state' ``` Sources: [apps/bundle-analyzer/components/index.ts:1-4](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/components/index.ts#L1-L4) The application provides distinct entrypoints for single build analysis and multi-build comparison via `SingleAnalyzer` and `CompareAnalyzer` wrapper components, which wrap controllers in boundary error handlers with custom fallback skeletons. ```tsx export function SingleAnalyzer() { return ( ) } function SingleAnalyzerController() { const model = useAnalyzerModel(false) return } export function CompareAnalyzer() { return ( ) } function CompareAnalyzerController() { const model = useAnalyzerModel(true) return } ``` Sources: [apps/bundle-analyzer/components/analyzer.tsx:60-84](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/components/analyzer.tsx#L60-L84) > [!NOTE] > The top-level hooks read URL search parameters before rendering data hooks to allow static prerendering bailout in Next.js router navigation. ```tsx function useAnalyzerModel(compare: boolean) { // Read the URL before suspense data so static prerendering can bail out. useSearchParams() ``` Sources: [apps/bundle-analyzer/components/analyzer.tsx:106-108](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/components/analyzer.tsx#L106-L108) ### Binary Parsing and Data Models The analysis pipeline processes low-level binary artifacts generated by Rust build analyzers using custom data readers. The `ModulesData` and `AnalyzeData` classes parse JSON header payloads followed by binary DataView buffers to resolve module paths, dependencies, dependents, and chunk parts without loading entire trees into high-level object graphs. ```typescript export class ModulesData { private modulesHeader: ModulesDataHeader private modulesBinaryData: DataView private pathToModuleIndex: Map constructor(modulesArrayBuffer: ArrayBuffer) { // Parse modules.data const modulesDataView = new DataView(modulesArrayBuffer) const modulesJsonLength = modulesDataView.getUint32(0, false) const modulesJsonBytes = new Uint8Array( modulesArrayBuffer, 4, modulesJsonLength ) const modulesJsonString = new TextDecoder('utf-8').decode(modulesJsonBytes) this.modulesHeader = JSON.parse(modulesJsonString) as ModulesDataHeader const modulesBinaryOffset = 4 + modulesJsonLength this.modulesBinaryData = new DataView( modulesArrayBuffer, modulesBinaryOffset ) // Build pathToModuleIndex map this.pathToModuleIndex = new Map() for (let i = 0; i < this.modulesHeader.modules.length; i++) { const module = this.modulesHeader.modules[i] const existing = this.pathToModuleIndex.get(module.path) if (existing) { existing.push(i) } else { this.pathToModuleIndex.set(module.path, [i]) } } } ``` Sources: [apps/bundle-analyzer/lib/analyze-data.ts:62-95](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/analyze-data.ts#L62-L95) To maintain structural integrity when cross-referencing route chunks against global build modules, the application asserts matching index fingerprints between data bundles. ```typescript export function assertMatchingModuleIndex( modules: ModulesData, route: AnalyzeData, side: string ): void { const moduleHash = modules.moduleIndexHash() const routeHash = route.moduleIndexHash() if (moduleHash !== routeHash) { throw new Error(`${side}: analyzer module-index fingerprint mismatch`) } } ``` Sources: [apps/bundle-analyzer/lib/analyze-data.ts:216-226](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/analyze-data.ts#L216-L226) | Data Structure / Class | Responsibilities | Key Methods | | :--- | :--- | :--- | | `ModulesData` | Parses global module graphs, dependency edges, and path lookups | `module()`, `moduleDependents()`, `moduleDependencies()` | | `AnalyzeData` | Parses route-specific chunk parts, output files, and source trees | `source()`, `chunkPart()`, `outputFile()`, `sourceRoots()` | | `FileNode` | Represents individual files in the treemap model | Properties: `id`, `name`, `size`, `outputType`, `server`, `client` | | `DirectoryNode` | Represents container directories grouping child nodes | Properties: `id`, `name`, `type`, `children`, `size` | ```typescript export class ModulesData { private modulesHeader: ModulesDataHeader private modulesBinaryData: DataView private pathToModuleIndex: Map constructor(modulesArrayBuffer: ArrayBuffer) { // Parse modules.data const modulesDataView = new DataView(modulesArrayBuffer) const modulesJsonLength = modulesDataView.getUint32(0, false) const modulesJsonBytes = new Uint8Array( modulesArrayBuffer, 4, modulesJsonLength ) const modulesJsonString = new TextDecoder('utf-8').decode(modulesJsonBytes) this.modulesHeader = JSON.parse(modulesJsonString) as ModulesDataHeader const modulesBinaryOffset = 4 + modulesJsonLength this.modulesBinaryData = new DataView( modulesArrayBuffer, modulesBinaryOffset ) // Build pathToModuleIndex map this.pathToModuleIndex = new Map() for (let i = 0; i < this.modulesHeader.modules.length; i++) { const module = this.modulesHeader.modules[i] const existing = this.pathToModuleIndex.get(module.path) if (existing) { existing.push(i) } else { this.pathToModuleIndex.set(module.path, [i]) } } } moduleIndexHash(): string { const hash = this.modulesHeader.module_index_hash if (typeof hash !== 'string' || !hash) { throw new Error('Missing analyzer module-index fingerprint') } return hash } module(index: ModuleIndex): AnalyzeModule | undefined { return this.modulesHeader.modules[index] } moduleCount(): number { return this.modulesHeader.modules.length } getModuleIndiciesFromPath(path: string): ModuleIndex[] { return this.pathToModuleIndex.get(path) ?? [] } … export interface FileNode { id: number name: string type: 'file' size: number outputType: 'code' | 'css' | 'asset' server: boolean client: boolean dependencies: number[] dependents: number[] } export interface DirectoryNode { id: number name: string type: 'directory' children: TreeNode[] size?: number } ``` Sources: [apps/bundle-analyzer/lib/analyze-data.ts:62-115](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/analyze-data.ts#L62-L115), [apps/bundle-analyzer/lib/types.ts:1-19](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/types.ts#L1-L19) > [!WARNING] > Joining a route analysis data payload with an unmatched global module data buffer throws a runtime fingerprint mismatch error to prevent corrupted graph traversals. ```typescript const moduleHash = modules.moduleIndexHash() const routeHash = route.moduleIndexHash() if (moduleHash !== routeHash) { throw new Error(`${side}: analyzer module-index fingerprint mismatch`) } ``` Sources: [apps/bundle-analyzer/lib/analyze-data.ts:221-225](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/apps/bundle-analyzer/lib/analyze-data.ts#L221-L225) ## Core Package Organization ### App Directory and Module Resolution The main `next` package tree is structured into server-side runtime infrastructure, compilation layers, testing utilities, and module resolution helpers. Layer separation isolates bundling internals from runtime routing modules and experimental test harnesses. Server module resolution for the [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) relies on `LoaderTree` tuples generated by internal [webpack loaders](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/webpack-loaders). These trees encode segments, parallel routing keys, static sibling metadata, and module definitions to load layouts, pages, and fallback states dynamically. ```typescript export type LoaderTree = [ segment: string, parallelRoutes: { [parallelRouterKey: string]: LoaderTree }, modules: AppDirModules, staticSiblings: readonly string[] | null, ] ``` Sources: [packages/next/src/server/lib/app-dir-module.ts:7-29](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/app-dir-module.ts#L7-L29) The server retrieves layouts and page modules through `getLayoutOrPageModule`, evaluating segment types and default fallbacks based on the active `DEFAULT_SEGMENT_KEY`. ```typescript export async function getLayoutOrPageModule(loaderTree: LoaderTree) { const { layout, page, defaultPage } = loaderTree[2] const isLayout = typeof layout !== 'undefined' const isPage = typeof page !== 'undefined' const isDefaultPage = typeof defaultPage !== 'undefined' && loaderTree[0] === DEFAULT_SEGMENT_KEY let mod = undefined let modType: 'layout' | 'page' | undefined = undefined let filePath = undefined if (isLayout) { mod = await layout[0]() modType = 'layout' filePath = layout[1] } else if (isPage) { mod = await page[0]() modType = 'page' filePath = page[1] } else if (isDefaultPage) { mod = await defaultPage[0]() modType = 'page' filePath = defaultPage[1] } return { mod, modType, filePath } } ``` Sources: [packages/next/src/server/lib/app-dir-module.ts:31-57](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/app-dir-module.ts#L31-L57) > [!NOTE] > `getComponentTypeModule` accepts specific module types (`layout`, `not-found`, `forbidden`, `unauthorized`) to resolve conditional error and boundary components directly from the loader tree structure. ```typescript export async function getComponentTypeModule( loaderTree: LoaderTree, moduleType: 'layout' | 'not-found' | 'forbidden' | 'unauthorized' ) { const { [moduleType]: module } = loaderTree[2] if (typeof module !== 'undefined') { return await module[0]() } return undefined } ``` Sources: [packages/next/src/server/lib/app-dir-module.ts:59-68](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/app-dir-module.ts#L59-L68) ### Experimental Testing and Shared Bundles The package exposes experimental testing entry points for server configurations and middleware behaviors, alongside specialized routing query utilities. | Export Module | Source Path | Responsibilities | | :--- | :--- | :--- | | `config-testing-utils` | `./config-testing-utils` | Testing utilities for server configuration options | | `middleware-testing-utils` | `./middleware-testing-utils` | Testing harnesses for middleware request execution | | Route Utilities | `./utils` | Exports `getRedirectUrl`, `getRewrittenUrl`, and `isRewrite` | ```typescript export * from './config-testing-utils' export * from './middleware-testing-utils' export { getRedirectUrl, getRewrittenUrl, isRewrite } from './utils' ``` Sources: [packages/next/src/experimental/testing/server/index.ts:1-3](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/experimental/testing/server/index.ts#L1-L3) Shared app-route runtime modules re-export context shims such as `appRouterContext` to maintain compatibility with navigation hooks imported from `next/navigation`. ```typescript // the name of the export has to be the camelCase version of the file name (without the extension) // TODO: remove this. We need it because using notFound from next/navigation imports this file :( export * as appRouterContext from '../../../shared/lib/app-router-context.shared-runtime' ``` Sources: [packages/next/src/server/route-modules/app-route/shared-modules.ts:1-3](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/shared-modules.ts#L1-L3) ## Build System and Asset Tracing ### Build Adapters and File Tracing The Next.js build infrastructure includes asset tracing modules that process `.nft.json` trace files generated by bundlers like Webpack and Turbopack. The `mapNftFileEntries` helper parses `NftJson` structures, mapping source paths against base roots and additional roots while managing symlinks and root escapes. ```typescript export interface MappedNftFileEntry { source: string destination: string hash?: string symlinkTarget?: string symlinkCrossesRoot: boolean } ``` Sources: [packages/next/src/build/nft.ts:112-123](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/nft.ts#L112-L123) When building outputs, `pushAsset` records assets and generates SHA-256 hashes when utilizing Turbopack. File hashing inspects symlinks via `fs.readlink` or falls back to reading file buffers directly with a salt prefix. | Helper Function | Purpose | | :--- | :--- | | `loadNFT` | Parses `.nft.json` payloads and registers mapped entries | | `hashFile` | Computes a salted SHA-256 hash for files or symlink targets | | `hashLinkTarget` | Generates a salted SHA-256 hash for link target strings | | `resolveNftOutputPath` | Verifies that destination paths remain inside deployment roots | ```typescript async function pushAsset( assets: Record, assetsHashes: Record, targetFilePath: string, sourceFilePath: string, bundler: Bundler, salt: string, hashOverride?: string ) { if (!(targetFilePath in assets)) { assets[targetFilePath] = sourceFilePath if (bundler === Bundler.Turbopack) { assetsHashes[targetFilePath] = hashOverride ?? (await hashFile(salt, sourceFilePath)) } } } async function loadNFT( assets: Record, assetsHashes: Record, repoRoot: string, traceFilePath: string, syntheticSymlinks: SyntheticSymlinkManager, salt: string ): Promise<{ entryHash?: string }> { const nft = JSON.parse(await fs.readFile(traceFilePath, 'utf8')) as NftJson for (const entry of mapNftFileEntries(nft, traceFilePath, repoRoot)) { let source = entry.source let hash = entry.hash if (entry.symlinkCrossesRoot) { if (entry.symlinkTarget === undefined) { throw new InvariantError( `Expected cross-root symlink ${JSON.stringify(entry.destination)} to have a target` ) } const linkTarget = path.relative(path.dirname(entry.destination), entry.symlinkTarget) || '.' hash = hashLinkTarget(salt, linkTarget) source = syntheticSymlinks.createLink(entry.source, linkTarget, hash) } assets[entry.destination] = source if (hash) { assetsHashes[entry.destination] = hash } } return { entryHash: nft.entryHash } } async function hashFile(salt: string, filePath: string): Promise { try { // Try symlink first, since readFile just transparently resolves those (or fails if it's a // directory symlink). const linkTarget = await fs.readlink(filePath) return hashLinkTarget(salt, linkTarget) } catch (e: any) { if (e.code === 'EINVAL') { // Not a symlink const hash = crypto.createHash('sha256') hash.update(salt) hash.update('file:') hash.update(await fs.readFile(filePath)) return hash.digest('hex') } else { throw e } } } function hashLinkTarget(salt: string, linkTarget: string): string { const hash = crypto.createHash('sha256') hash.update(salt) hash.update('link') hash.update(linkTarget) return hash.digest('hex') ``` Sources: [packages/next/src/build/adapter/build-complete.ts:2822-2900](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/adapter/build-complete.ts:2822-2900) > [!CAUTION] > If a file or symlink destination attempts to escape the deployment root during resolution, `resolveNftOutputPath` immediately throws an invariant error. ```typescript export function resolveNftOutputPath( outputRoot: string, destination: string ): string { const outputPath = path.resolve(outputRoot, destination) if (relativePathIfInside(outputRoot, outputPath) === undefined) { invalid( `output path ${JSON.stringify(destination)} escapes the deployment root` ) } return outputPath } ``` Sources: [packages/next/src/build/nft.ts:269-280](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/nft.ts#L269-L280) ### Turborepo Access Tracing The Turbopack and Turborepo integration exposes access tracing utilities that record file system operations during compilation and build passes. The access trace subsystem is exported via modular entry points containing result classes and helper functions. ```typescript export type { SerializableTurborepoAccessTraceResult } from './types' export { turborepoTraceAccess, writeTurborepoAccessTraceResult, } from './helpers' export { TurborepoAccessTraceResult } from './result' ``` Sources: [packages/next/src/build/turborepo-access-trace/index.ts:1-6](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/turborepo-access-trace/index.ts#L1-L6) In parallel, build analysis graph dumping utilities (`dumpAnalyzeGraph`) read module indices and route snapshots to validate binary edge representations and schema versions. ```typescript export function dumpAnalyzeGraph( directory: string, snapshotName: string, routeFilter: string | undefined ): void { // Pipe stdout must block so writeSync supplies backpressure rather than EAGAIN. if (process.stdout._handle != null) { // @ts-ignore Node's internal handle, also used by the native bindings loader. process.stdout._handle.setBlocking?.(true) } ``` Sources: [packages/next/src/build/analyze/graph-dump.ts:326-335](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/analyze/graph-dump.ts#L326-L335) ## Developer Tooling and Overlay Subsystems ### Devtools Entrypoints and Browser Overlays The Next.js developer tooling subsystem initializes browser error overlays, build status indicators, and segment trees via entrypoints housed in `packages/next/src/next-devtools`. The main dev-overlay browser module (`packages/next/src/next-devtools/dev-overlay.browser.tsx`) exports `renderAppDevOverlay` and `renderPagesDevOverlay`, which attach shadow roots and mount the `DevOverlayRoot` component inside isolated `nextjs-portal` containers. | Function | Router Type | Key Parameters | Purpose | | :--- | :--- | :--- | :--- | | `renderAppDevOverlay` | `app` | `getOwnerStack`, `isRecoverableError`, `enableCacheIndicator`, `enableRuntimeErrorReporting` | Mounts the [developer overlay](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/developer-overlay) for the App Router with a script container and identifier prefix `ndt-` | | `renderPagesDevOverlay` | `pages` | `getOwnerStack`, `getSquashedHydrationErrorDetails`, `isRecoverableError` | Mounts the developer overlay for the Pages Router using a `MutationObserver` to re-attach the container if removed | ```typescript export * from './dev-overlay.browser' ``` Sources: [packages/next/src/next-devtools/entrypoint.ts:1-1](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/entrypoint.ts#L1-L1) > [!CAUTION] > Attempting to mount the Pages developer overlay while the App Router overlay is already mounted, or vice versa, triggers an invariant error because switching between router types requires a hard navigation. ```tsx if (isPagesMounted) { // Switching between App and Pages Router is always a hard navigation // TODO: Support soft navigation between App and Pages Router throw new Error( 'Next DevTools: Pages Dev Overlay is already mounted. This is a bug in Next.js' ) } ``` Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:455-462](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L455-L462) The `dispatcher` object processes queued events through an `EventQueue` instance, mapping action dispatchers for build states, version info, indicators, and runtime errors. | Dispatcher Action | Action Type Constant | Description | | :--- | :--- | :--- | | `onBuildOk` | `ACTION_BUILD_OK` | Signals successful compilation | | `onBuildError` | `ACTION_BUILD_ERROR` | Reports build error messages | | `onBeforeRefresh` | `ACTION_BEFORE_REFRESH` | Triggers before hot module replacement refresh | | `onRefresh` | `ACTION_REFRESH` | Executes HMR refresh | | `onStaticIndicator` | `ACTION_STATIC_INDICATOR` | Updates static vs [dynamic rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering) status (`pending`, `static`, `dynamic`, `disabled`) | | `openErrorOverlay` | `ACTION_ERROR_OVERLAY_OPEN` | Opens the runtime error overlay | ```tsx export const dispatcher: Dispatcher = { onBuildOk: createQueuable((dispatch: Dispatch) => { dispatch({ type: ACTION_BUILD_OK }) }), onBuildError: createQueuable((dispatch: Dispatch, message: string) => { dispatch({ type: ACTION_BUILD_ERROR, message }) }), onBeforeRefresh: createQueuable((dispatch: Dispatch) => { dispatch({ type: ACTION_BEFORE_REFRESH }) }), onRefresh: createQueuable((dispatch: Dispatch) => { dispatch({ type: ACTION_REFRESH }) }), ``` Sources: [packages/next/src/next-devtools/dev-overlay.browser.tsx:203-215](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay.browser.tsx#L203-L215) ### Segment Trees and User-Space Hooks The dev overlay includes a trie data structure located in `packages/next/src/next-devtools/dev-overlay/segment-explorer-trie.ts` for storing and searching App Router segment paths. The trie utilizes null-prototype child objects (`Object.create(null)`) so that segment names colliding with built-in `Object.prototype` members like `constructor` or `toString` resolve correctly. ```typescript type TrieNode = { value: Value | undefined children: { [key: string]: TrieNode | undefined } } ``` Sources: [packages/next/src/next-devtools/dev-overlay/segment-explorer-trie.ts:21-26](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/dev-overlay/segment-explorer-trie.ts#L21-L26) User-space integration hooks are provided in `packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx`, exporting boundary components and state providers. | Exported Component / Hook | Purpose | | :--- | :--- | | `SegmentStateProvider` | Context provider managing boundary types (`not-found`, `error`, `loading`, `global-error`) and reload triggers | | `SegmentBoundaryTriggerNode` | Renders simulated fallback components such as `LoadingSegmentNode`, `NotFoundSegmentNode`, or `ErrorSegmentNode` | | `SegmentViewStateNode` | Updates route state trees via the dispatcher during layout rendering | | `useSegmentState` | Consumes segment boundary context | ```tsx export function SegmentStateProvider({ children }: { children: ReactNode }) { const [boundaryType, setBoundaryType] = useState( null ) const [errorBoundaryKey, setErrorBoundaryKey] = useState(0) const reloadBoundary = useCallback( () => setErrorBoundaryKey((prev) => prev + 1), [] ) ``` Sources: [packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx:129-138](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx#L129-L138) > [!NOTE] > `SegmentTrieNode` registers node state using `useLayoutEffect` rather than `useEffect` to ensure updates occur during React Suspense boundaries without losing mounted state. ```tsx // Use `useLayoutEffect` to ensure the state is updated during suspense. // `useEffect` won't work as the state is preserved during suspense. useLayoutEffect(() => { dispatcher.segmentExplorerNodeAdd(nodeState) return () => { dispatcher.segmentExplorerNodeRemove(nodeState) } }, [nodeState]) ``` Sources: [packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx:50-57](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx#L50-L57) Additional user-space error helpers are re-exported from `packages/next/src/next-devtools/userspace/app/errors/index.ts`, exposing console error interception, client error handling, and dev error decoration. ```typescript export { originConsoleError } from './intercept-console-error' export { handleClientError } from './use-error-handler' export { decorateDevError } from './stitched-error' ``` Sources: [packages/next/src/next-devtools/userspace/app/errors/index.ts:1-3](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/errors/index.ts#L1-L3) ## Auxiliary Tooling Packages ### Documentation Indexing and Tree Building Satellite packages within the repository provide auxiliary capabilities such as repository automation, documentation indexing, and code transformations via `packages/next-codemod`. This package includes utilities for discovering documentation files, parsing directory trees, generating agent-readable indexes, and managing workspace configurations. The codemod package contains routines in `packages/next-codemod/lib/agents-md.ts` that scan documentation directories to build hierarchical representations of markdown and MDX files. The file collector filters out index pages, sorts results lexicographically, and normalizes path separators for cross-platform compatibility. ```typescript export function collectDocFiles(dir: string): { relativePath: string }[] { return (fs.readdirSync(dir, { recursive: true }) as string[]) .filter( (f) => (f.endsWith('.mdx') || f.endsWith('.md')) && !/[/\\]index\.mdx$/.test(f) && !/[/\\]index\.md$/.test(f) && !f.startsWith('index.') ) .sort() .map((f) => ({ relativePath: f.replace(/\\/g, '/') })) } ``` Sources: [packages/next-codemod/lib/agents-md.ts:237-248](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts#L237-L248) The tree builder organizes files into nested `DocSection` structures up to three levels deep, sorting sections and subsections alphabetically. | Structure Property | Type | Description | | :--- | :--- | :--- | | `name` | `string` | Directory segment name | | `files` | `{ relativePath: string }[]` | List of documentation files contained in the section | | `subsections` | `DocSection[]` | Nested child sections | ```typescript interface DocSection { name: string files: { relativePath: string }[] subsections: DocSection[] } ``` Sources: [packages/next-codemod/lib/agents-md.ts:250-254](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts#L250-L254) > [!NOTE] > `collectDocFiles` explicitly ignores any file whose path ends with `index.md` or `index.mdx`, or starts with `index.`, to prevent top-level landing pages from duplicating nested route structures in agent indexes. ```typescript return (fs.readdirSync(dir, { recursive: true }) as string[]) .filter( (f) => (f.endsWith('.mdx') || f.endsWith('.md')) && !/[/\\]index\.mdx$/.test(f) && !/[/\\]index\.md$/.test(f) && !f.startsWith('index.') ) ``` Sources: [packages/next-codemod/lib/agents-md.ts:238-245](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next.js/blob/HEAD/packages/next-codemod/lib/agents-md.ts#L238-L245) ### Workspace Detection and Ignore Management The auxiliary package inspects project environments to identify monorepo structures and ensure generated build artifacts or documentation caches are properly excluded from version control. | Workspace Type | Detection File | Parsing Utility | | :--- | :--- | :--- | | `pnpm` | `pnpm-workspace.yaml` | `parsePnpmWorkspace` | | `npm` / `yarn` | `package.json` | `parsePackageJsonWorkspaces` | | `lerna` | `lerna.json` | `parseLernaConfig` | | `null` | none | none | ```typescript function detectWorkspace(cwd: string): WorkspaceInfo { const packageJsonPath = path.join(cwd, 'package.json') // Check pnpm workspaces (pnpm-workspace.yaml) const pnpmWorkspacePath = path.join(cwd, 'pnpm-workspace.yaml') if (fs.existsSync(pnpmWorkspacePath)) { const packages = parsePnpmWorkspace(pnpmWorkspacePath) if (packages.length > 0) { return { isMonorepo: true, type: 'pnpm', packages } } } // Check npm/yarn workspaces (package.json workspaces field) if (fs.existsSync(packageJsonPath)) { const packages = parsePackageJsonWorkspaces(packageJsonPath) if (packages.length > 0) { return { isMonorepo: true, type: 'npm', packages } } } // Check Lerna (lerna.json) const lernaPath = path.join(cwd, 'lerna.json') if (fs.existsSync(lernaPath)) { const packages = parseLernaConfig(lernaPath) if (packages.length > 0) { return { isMonorepo: true, type: 'lerna', packages } ``` Sources: [packages/next-codemod/lib/agents-md.ts:463-488](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts#L463-L488) When updating `.gitignore`, `ensureGitignoreEntry` checks for existing patterns matching `.next-docs` entries using regular expression tests across file lines, appending the entry and a comment header if absent. ```typescript export function ensureGitignoreEntry(cwd: string): GitignoreStatus { const gitignorePath = path.join(cwd, '.gitignore') const entryRegex = /^\s*\.next-docs(?:\/.*)?$/ let content = '' if (fs.existsSync(gitignorePath)) { content = fs.readFileSync(gitignorePath, 'utf-8') } const hasEntry = content.split(/\r?\n/).some((line) => entryRegex.test(line)) if (hasEntry) { return { path: gitignorePath, updated: false, alreadyPresent: true } } ... ``` Sources: [packages/next-codemod/lib/agents-md.ts:428-441](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts#L428-L441) ## Related - [Overview](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/overview) - [Monorepo Workspace](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/monorepo-workspace) --- ## Technical docs: Monorepo Workspace URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/monorepo-workspace
Relevant source files The following files were used as context for generating this wiki page: - [pnpm-workspace.yaml](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/pnpm-workspace.yaml) - [packages/next-codemod/lib/agents-md.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts) - [packages/next/src/build/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/index.ts) - [packages/next/taskfile.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js) - [package.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/package.json) - [turbo.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/turbo.json) - [packages/next/src/build/adapter/build-complete.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/adapter/build-complete.ts) - [packages/create-next-app/templates/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/create-next-app/templates/index.ts) - [conductor.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/conductor.json) - [packages/next/src/build/swc/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/swc/index.ts) - [packages/next/src/build/turborepo-access-trace/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/turborepo-access-trace/index.ts) - [Cargo.toml](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/Cargo.toml) - [run-evals.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/run-evals.js) - [packages/next/src/build/webpack/loaders/next-app-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-app-loader/index.ts) - [packages/next-codemod/turbo.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/turbo.json) - [socket.yaml](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/socket.yaml) - [packages/next-codemod/bin/upgrade.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/bin/upgrade.ts) - [packages/next/turbo.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/turbo.json) - [packages/next-codemod/lib/handle-package.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/handle-package.ts) - [packages/next/src/lib/turbopack-cache-seed.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/turbopack-cache-seed.ts) - [packages/next/src/lib/find-root.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts) - [packages/next/package.json](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json) - [run-tests.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/run-tests.js) - [packages/next/src/server/lib/chrome-devtools-workspace.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/chrome-devtools-workspace.ts) - [packages/next/src/build/utils.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/utils.ts)
## Overview The Next.js repository is structured as a multi-package and multi-engine monorepo governed by declarative workspace configurations. It combines Node.js package management with Rust workspace orchestration to coordinate builds, internal packaging, and testing across disparate subdirectories. Sources: [pnpm-workspace.yaml:1-7](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/pnpm-workspace.yaml#L1-L7), [Cargo.toml:1-18](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/Cargo.toml#L1-L18) ## PNPM Workspace Layout and Boundaries ### Workspace Directory Patterns and Glob Mappings The monorepo workspace structure is governed declaratively by `pnpm-workspace.yaml`, which specifies pattern globs to map applications, packages, benchmarks, and compiler bindings into the unified dependency tree. The `packages` entry defines active workspace members across seven distinct directory paths. | Workspace Pattern Glob | Target Component Category | | :--- | :--- | | `apps/*` | End-user applications and deployment fixtures | | `packages/*` | Core shared libraries, developer tooling, and internal packages | | `bench/*` | Performance benchmark suites | | `crates/*/js` | JavaScript bindings for individual root-level Rust crates | | `turbopack/crates/*/js` | JavaScript bindings for Turbopack-specific Rust crates | | `turbopack/crates/turbopack-tests/tests/execution` | Turbopack execution test suites | Sources: [pnpm-workspace.yaml:1-7](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/pnpm-workspace.yaml#L1-L7) ### Package Manager and Security Restrictions The root `package.json` designates `pnpm@10.33.0` as the explicit package manager and sets a minimum Node.js engine requirement of `>=20.9.0`. Security policies and dependency constraints are enforced directly within the workspace configuration. | Workspace Setting | Value | Behavior | | :--- | :--- | :--- | | `updateNotifier` | `false` | Disables automated version check notifications during CLI execution | | `blockExoticSubdeps` | `true` | Prevents installation of non-standard or unexpected subdependency sources | | `minimumReleaseAge` | `2880` (48 hours) | Enforces a minimum delay before newly published registry versions can be installed | Sources: [pnpm-workspace.yaml:8-37](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/pnpm-workspace.yaml#L8-L37), [package.json:302-305](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/package.json#L302-L305) > [!NOTE] > Security settings including `blockExoticSubdeps` and `minimumReleaseAge` are synchronized with temporary fixture directories created by `scripts/install-native.mjs` and verified by `test/lib/pnpm-security-settings.js`. Sources: [pnpm-workspace.yaml:32-35](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/pnpm-workspace.yaml#L32-L35) ### Excluded Dependencies and Overrides Certain built dependencies and package versions are exempted from workspace constraints or explicitly overridden at the root level. The workspace allows native builds for `@ast-grep/cli` while ignoring build scripts for performance-critical or native packages. - **Ignored Build Dependencies:** `@datadog/native-appsec`, `@datadog/native-metrics`, `@datadog/pprof`, `@swc/core`, `@tailwindcss/oxide`, `core-js`, `cpu-features`, `dd-trace`, `esbuild`, `msw`, `nx`, `playwright-chromium`, `protobufjs`, `sharp`, `ssh2`, `unrs-resolver`, `wasm-pack` - **Minimum Release Age Exclusions:** `@mswjs/interceptors@0.42.6`, `@next/*`, `@turbo/*`, `@types/react@19.2.18`, `@types/react-dom@19.2.4`, `@vercel/*`, `@workflow/*`, `babel-plugin-react-compiler`, `httpxy@0.5.5`, `next`, `react`, `react-dom`, `react-is`, `react-server-dom-*`, `satori@0.33.5`, `scheduler`, `turbo` Sources: [pnpm-workspace.yaml:11-55](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/pnpm-workspace.yaml#L11-L55) > [!WARNING] > Patched dependencies defined in the root manifest override external package behaviors for modules such as `webpack-sources@3.2.3`, `stacktrace-parser@0.1.10`, `@rspack/core@1.6.7`, and `@vercel/og@1.0.1`. Sources: [package.json:333-346](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/package.json#L333-L346) ## Turborepo Task Pipeline Coordination ### Root Task Topologies and Global Environment The root `turbo.json` configures task execution semantics, global environment tracking, and concurrency options for the monorepo. It establishes the Turborepo schema, enables the terminal user interface (`"ui": "tui"`), and defines global variables that invalidate caches when altered. | Global Configuration Key | Value | Purpose | | :--- | :--- | :--- | | `globalEnv` | `["CI", "NEXT_CI_RUNNER"]` | Tracks CI execution state in cache keys | | `globalPassThroughEnv` | `["RUSTC_WRAPPER", "SCCACHE_*"]` | Forwards Rust compilation cache settings | | `ui` | `"tui"` | Enables the interactive Turborepo terminal interface | Sources: [turbo.json:1-4](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/turbo.json#L1-L4), [turbo.json:34-34](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/turbo.json#L34-L34) The root task definitions govern core commands across workspace packages, specifying dependencies, file inputs, and generated outputs. | Task Name | `dependsOn` | `inputs` | `outputs` | `env` | | :--- | :--- | :--- | :--- | :--- | | `build` | `["^build"]` | — | `["dist/**"]` | — | | `dev` | `["^dev"]` | — | `["dist/**"]` | — | | `storybook` | — | — | — | — | | `build-storybook` | `["^build-storybook"]` | — | `["storybook-static/**"]` | — | | `test-storybook` | `["^test-storybook"]` | — | — | — | | `pack-for-isolated-tests` | — | `["$TURBO_DEFAULT$", "dist/**"]` | `["packed.tgz"]` | — | | `typescript` | — | — | — | — | | `//#typescript` | — | — | — | — | | `//#get-test-timings` | — | `["run-tests.js"]` | `["test-timings.json"]` | `["KV_REST_API_URL", "KV_REST_API_TOKEN"]` | Sources: [turbo.json:5-33](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/turbo.json#L5-L33) > [!NOTE] > Tasks prefixed with `//#` execute exclusively at the root workspace level rather than propagating across individual package members. Sources: [turbo.json:27-32](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/turbo.json#L27-L32) ### Package-Specific Task Overrides Individual packages extend the root Turborepo configuration to tailor build outputs and topological constraints for specialized deliverables. The `packages/next/turbo.json` manifest customizes the primary `build` task by requiring [bundle analyzer](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/companion-packages/bundle-analyzer) UI compilation before executing package assembly. ```json { "$schema": "https://turborepo.org/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": ["@next/bundle-analyzer-ui#build", "^build"], "outputs": ["dist/**"] } } ``` Sources: [packages/next/turbo.json:1-9](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/turbo.json#L1-L9) Similarly, `packages/next-codemod/turbo.json` extends the root pipeline (`"extends": ["//"]`) to specify granular file outputs for both production build and development tasks, excluding test fixtures and test suites from cache artifacts. ```json { "$schema": "https://turbo.build/schema.json", "extends": ["//"], "tasks": { "build": { "outputs": [ "**/*.js", "**/*.d.ts", "**/*.js.map", "!bin/__testfixtures__/**", "!transforms/__testfixtures__/**", "!transforms/__tests__/**" ] }, "dev": { "outputs": [ "**/*.js", "**/*.d.ts", "**/*.js.map", "!bin/__testfixtures__/**", "!transforms/__testfixtures__/**", "!transforms/__tests__/**" ] } } ``` Sources: [packages/next-codemod/turbo.json:1-25](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/turbo.json#L1-L25) > [!CAUTION] > Failing to exclude test directories from package output globs can pollute the Turborepo cache with transient test artifacts, causing inconsistent build state invalidations across CI runs. Sources: [packages/next-codemod/turbo.json:10-13](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/turbo.json#L10-L13), [packages/next-codemod/turbo.json:20-23](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/turbo.json#L20-L23) ## Internal Packaging and Task Automation ### Task Automation and Compilation Pipelines The `packages/next/taskfile.js` script manages internal compilation routines, file watching, and output targets for the package using Taskr. The default export sequence clears the `dist` directory, invokes the primary release build, and establishes file watchers across source subdirectories like `src/bin`, `src/pages`, `src/server`, `src/client`, `src/lib`, and `src/cli`. ```javascript export default async function (task) { const opts = { dev: true } await task.clear('dist') await task.start('build', opts) await task.watch('src/bin', 'bin', opts) await task.watch('src/pages', 'pages', opts) await task.watch('src/server', ['server', 'server_esm', 'server_wasm'], opts) await task.watch('src/api', 'api_esm', opts) await task.watch( 'src/build', ['nextbuild', 'nextbuild_esm', 'nextbuildjest'], opts ) await task.watch( 'src/next-devtools', [ 'next_devtools_entrypoint', 'next_devtools_server', 'next_devtools_server_esm', 'next_devtools_shared', 'next_devtools_shared_esm', 'next_devtools_userspace', 'next_devtools_userspace_esm', ], opts ) await task.watch('src/experimental/testing', 'experimental_testing', opts) await task.watch('src/experimental/testmode', 'experimental_testmode', opts) await task.watch('src/export', 'nextbuildstatic', opts) await task.watch('src/export', 'nextbuildstatic_esm', opts) await task.watch('src/client', 'client', opts) await task.watch('src/client', 'client_esm', opts) await task.watch('src/diagnostics', 'diagnostics', opts) await task.watch('src/lib', 'lib', opts) await task.watch('src/lib', 'lib_esm', opts) await task.watch('src/cli', 'cli', opts) await task.watch('src/telemetry', 'telemetry', opts) await task.watch('src/trace', 'trace', opts) await task.watch( 'src/shared', ['shared_re_exported', 'shared_re_exported_esm', 'shared', 'shared_esm'], opts ) } ``` Sources: [packages/next/taskfile.js:2785-2828](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2785-L2828) Specialized functions handle transformations for shared utilities, Webpack runtime bundles, and WebAssembly assets. For instance, `shared` and `shared_esm` tasks compile files under `src/shared/` while ignoring tests and dynamic entry points, targeting `dist/shared` and `dist/esm/shared` respectively. | Task Name | Source Pattern | Target Directory | Compiler / Tool | Options / Flags | | :--- | :--- | :--- | :--- | :--- | | `shared` | `src/shared/**/*.+(js|ts|tsx)` | `dist/shared` | SWC | `dev: opts.dev` | | `shared_esm` | `src/shared/**/*.+(js|ts|tsx)` | `dist/esm/shared` | SWC | `dev: opts.dev, esm: true` | | `server_wasm` | `src/server/**/*.+(wasm)` | `dist/server` | Direct copy | — | | `experimental_testing` | `src/experimental/testing/**/!(*.test).+(js|ts|tsx)` | `dist/experimental/testing` | SWC | `dev: opts.dev` | | `experimental_testmode` | `src/experimental/testmode/**/!(*.test).+(js|ts|tsx)` | `dist/experimental/testmode` | SWC | `dev: opts.dev` | Sources: [packages/next/taskfile.js:2830-2904](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2830-L2904) > [!TIP] > The `generate_types` task conditionally passes `--watch` and `--preserveWatchOutput` flags to TypeScript compiler processes when `opts.dev` is active, keeping declaration generation running continuously during development. Sources: [packages/next/taskfile.js:2767-2783](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/taskfile.js#L2767-L2783) ### Package Metadata and Script Definitions The `packages/next/package.json` file declares core workspace identity, package entry points, binary mappings, and script automation hooks. It assigns `dist/server/next.js` as the main entry point and exposes the CLI binary via the `bin` mapping. Sources: [packages/next/package.json:1-10](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L1-L10), [packages/next/package.json:83-96](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L83-L96) The manifest enumerates runtime dependencies, peer requirements, and development tooling. The `taskr` configuration block explicitly registers required taskfile extensions for Webpack, NCC, SWC, and file watching. | Package Manifest Key | Value / Target | Description | | :--- | :--- | :--- | | `name` | `"next"` | Workspace package identifier | | `version` | `"16.5.0-canary.8"` | Current semantic version release string | | `main` | `"./dist/server/next.js"` | Primary CommonJS entry point | | `types` | `"index.d.ts"` | Root TypeScript declaration file | | `bin.next` | `"./dist/bin/next"` | Command-line executable mapping | | `scripts.dev` | `"cross-env NEXT_SERVER_NO_MANGLE=1 taskr"` | Starts development task runner with unmangled server output | | `scripts.build` | `"taskr release"` | Clears distribution and executes full release compilation | | `scripts.types` | `tsc --project tsconfig.build.json ...` | Emits isolated type declarations into `dist` | | `taskr.requires` | `["./taskfile-webpack.js", ...]` | Taskr plugin modules loaded at runtime | Sources: [packages/next/package.json:1-10](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L1-L10), [packages/next/package.json:83-104](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L83-L104) > [!CAUTION] > The `files` array in `packages/next/package.json` explicitly whitelists published distribution folders, type definitions, and experimental entry points (`experimental/testing/server.js`, `experimental/testmode/playwright.js`); omitting a built artifact from this list prevents it from being included when packed to registry tarballs. Sources: [packages/next/package.json:11-82](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/package.json#L11-L82) ## Turborepo Access Tracing and Caching ### Cache Seeding and Worktree Resolution Integration between the Next.js build runtime and workspace caching mechanisms relies on programmatic access tracing and cache seeding across Git worktrees. The Next.js build infrastructure exports helper utilities from `packages/next/src/build/turborepo-access-trace/index.ts` to coordinate Turborepo access tracing (`turborepoTraceAccess`, `writeTurborepoAccessTraceResult`, and `TurborepoAccessTraceResult`), enabling build pipelines to record file system and dependency accesses required for correct remote and local task caching. ```typescript export type { SerializableTurborepoAccessTraceResult } from './types' export { turborepoTraceAccess, writeTurborepoAccessTraceResult, } from './helpers' export { TurborepoAccessTraceResult } from './result' ``` Sources: [packages/next/src/build/turborepo-access-trace/index.ts:1-6](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/turborepo-access-trace/index.ts#L1-L6) To accelerate builds across isolated Git worktrees within a monorepo workspace, `seedTurbopackCacheIfNeeded` inspects the project directory and distribution path to seed local Turbopack caches from existing worktree sources. ```typescript export function seedTurbopackCacheIfNeeded({ projectDir, distDir, }: { projectDir: string distDir: string }): void { // This gets the version assuming that nothing is dirty. // If things are dirty, turbopack would write things // in a different location. There are other circumstances // as well. This only matters for people developing turbopack // see handle_db_versioning in turbotask backend for more details. const version = getTurbopackCacheVersion() if (!version) return const worktreeInfo = getGitWorktreeInfo(projectDir) if (!worktreeInfo) return const cacheDir = path.join(distDir, 'cache', 'turbopack') const targetVersionDir = path.join(cacheDir, version) if (dirHasEntries(targetVersionDir)) return ``` Sources: [packages/next/src/lib/turbopack-cache-seed.ts:11-32](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/turbopack-cache-seed.ts#L11-L32) When a project build executes, `findSeedSource` scans the main repository root and linked worktree roots returned by `listLinkedWorktreeRoots` to locate the most recently written cache directory matching the active Turbopack cache version (`getTurbopackCacheVersion()`). ```typescript function findSeedSource( worktreeInfo: GitWorktreeInfo, projectDir: string, distDir: string, version: string ): string | undefined { const projectRelToWorktree = path.relative( worktreeInfo.worktreeRoot, projectDir ) const distRelToProject = path.relative(projectDir, distDir) const currentWorktree = path.resolve(worktreeInfo.worktreeRoot) // We are going to find the best candidate worktree // based on the most recently written cache directory. // We only look at our version let best: { versionDir: string; commitTimeMs: number } | undefined for (const root of [ worktreeInfo.mainRepoRoot, ...listLinkedWorktreeRoots(worktreeInfo.mainRepoRoot), ]) { if (path.resolve(root) === currentWorktree) continue const versionDir = path.join( root, projectRelToWorktree, distRelToProject, 'cache', 'turbopack', version ) const commitTimeMs = currentCommitTimeMs(versionDir) if (commitTimeMs === undefined) continue if (!best || commitTimeMs > best.commitTimeMs) { best = { versionDir, commitTimeMs } } } return best?.versionDir } ``` Sources: [packages/next/src/lib/turbopack-cache-seed.ts:65-103](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/turbopack-cache-seed.ts#L65-L103) The candidacy of each `versionDir` is evaluated by reading the persistence layer metadata file `CURRENT` to extract the `commit_time` epoch timestamp, ensuring only valid, readable JSON cache states are considered as seed sources. ```typescript // When the cache in `versionDir` was last committed to, in epoch milliseconds, or undefined if // there is no usable cache there. Read from the `commit_time` the persistence layer records in // CURRENT. function currentCommitTimeMs(versionDir: string): number | undefined { let commitTime try { commitTime = JSON.parse( fs.readFileSync(path.join(versionDir, 'CURRENT'), 'utf8') ).commit_time } catch { // missing, unreadable, or not valid JSON - treat it as not a seed candidate return undefined } if (typeof commitTime !== 'string') return undefined const parsed = Date.parse(commitTime) return Number.isNaN(parsed) ? undefined : parsed } ``` Sources: [packages/next/src/lib/turbopack-cache-seed.ts:105-121](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/turbopack-cache-seed.ts#L105-L121) > [!NOTE] > The regular expression `IMMUTABLE_CACHE_FILE` identifies immutable Turbopack persistence artifacts (`.sst`, `.blob`, `.meta`, and `.del`), which are linked via `fs.linkSync` during seeding rather than copied, while mutable files such as `CURRENT` and `LOG` are copied to receive independent inodes. ```typescript const IMMUTABLE_CACHE_FILE = /\.(sst|blob|meta|del)$/ function seedCacheDir(src: string, dst: string): void { const stat = fs.lstatSync(src) if (stat.isDirectory()) { fs.mkdirSync(dst, { recursive: true }) for (const name of fs.readdirSync(src)) { seedCacheDir(path.join(src, name), path.join(dst, name)) } } else if (IMMUTABLE_CACHE_FILE.test(src)) { fs.linkSync(src, dst) } else { // Mutable/unknown (CURRENT, LOG, …) - copy so it gets its own inode. fs.copyFileSync(src, dst) } } ``` Sources: [packages/next/src/lib/turbopack-cache-seed.ts:131-146](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/turbopack-cache-seed.ts#L131-L146) | Helper Function / Constant | Target File / Module | Purpose | | :--- | :--- | :--- | | `turborepoTraceAccess` | `packages/next/src/build/turborepo-access-trace/helpers.ts` | Executes and traces file/module accesses for Turborepo task inputs | | `writeTurborepoAccessTraceResult` | `packages/next/src/build/turborepo-access-trace/helpers.ts` | Serializes recorded access trace results to disk | | `TurborepoAccessTraceResult` | `packages/next/src/build/turborepo-access-trace/result.ts` | Represents structured trace outputs across workspace boundaries | | `seedTurbopackCacheIfNeeded` | `packages/next/src/lib/turbopack-cache-seed.ts` | Coordinates cross-worktree Turbopack cache seeding | | `IMMUTABLE_CACHE_FILE` | `packages/next/src/lib/turbopack-cache-seed.ts` | Matches immutable persistence files (`.sst`, `.blob`, `.meta`, `.del`) for hardlinking | Sources: [packages/next/src/build/turborepo-access-trace/index.ts:1-6](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/turborepo-access-trace/index.ts#L1-L6), [packages/next/src/lib/turbopack-cache-seed.ts:11-146](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/turbopack-cache-seed.ts#L11-L146) ## Workspace Root Resolution and Detection ### Algorithmic Workspace Discovery Next.js and its related codemod and upgrade tooling implement explicit root discovery algorithms to locate monorepo boundaries, package managers, and workspace configurations from any working subdirectory. The build runtime core locates project roots via `findRootDirAndLockFiles` in `packages/next/src/lib/find-root.ts`, which searches upward using `findUp.sync` to evaluate dedicated workspace markers (`pnpm-workspace.yaml`, `lerna.json`) and package manager lockfiles (`pnpm-lock.yaml`, `package-lock.json`, `yarn.lock`, `bun.lock`, `bun.lockb`). ```typescript const LOCK_FILES = [ 'pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb', ] // Dedicated workspace-root files. pnpm and Lerna declare the root this way. const WORKSPACE_MARKERS = ['pnpm-workspace.yaml', 'lerna.json'] ``` Sources: [packages/next/src/lib/find-root.ts:98-108](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts#L98-L108) Workspace markers take precedence over ordinary lockfiles to prevent nested package-level lockfiles from incorrectly truncating root detection. The helper `findWorkspaceMarker` checks for workspace configuration files and evaluates `package.json` files for the presence of a `workspaces` array or object field via `hasWorkspacesField`. ```typescript function hasWorkspacesField(packageJson: string): boolean { try { return JSON.parse(readFileSync(packageJson, 'utf8')).workspaces != null } catch { return false } } function findWorkspaceMarker(directory: string): string | undefined { for (const name of WORKSPACE_MARKERS) { const markerPath = join(directory, name) if (existsSync(markerPath)) { return markerPath } } const packageJson = join(directory, 'package.json') return hasWorkspacesField(packageJson) ? packageJson : undefined } ``` Sources: [packages/next/src/lib/find-root.ts:111-129](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts#L111-L129) > [!NOTE] > When multiple candidate root markers are discovered ascending the directory tree, traversal halts if a higher parent directory contains no workspace marker once a workspace marker has already been accepted, preventing inner project roots from crossing monorepo boundaries incorrectly. ```typescript while (true) { const lastCandidate = candidates[candidates.length - 1] const currentDir = dirname(lastCandidate) const parentDir = dirname(currentDir) // dirname('/')==='/' so if we happen to reach the FS root (as might happen in a container we need to quit to avoid looping forever if (parentDir === currentDir) break const nextCandidate = findNextRootCandidate(parentDir) if (!nextCandidate) break // findNextRootCandidate searches for markers all the way up, so a non-marker // here means there is no higher marker: nothing above can extend the root. if (foundWorkspaceMarker && !nextCandidate.isWorkspaceMarker) break candidates.push(nextCandidate.path) foundWorkspaceMarker ||= nextCandidate.isWorkspaceMarker } ``` Sources: [packages/next/src/lib/find-root.ts:159-178](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts#L159-L178) ### Boundary Enforcement and Codemod Detection Root candidate acceptance enforces strict boundaries against git repositories, worktrees, and user home directories. `findGitBoundary` detects Git repository or worktree roots, validating worktree references by checking for a `commondir` file inside the git directory. ```typescript function isGitWorktree(dir: string, gitFile: string): boolean { let contents: string try { contents = readFileSync(gitFile, 'utf8') } catch { return false } // Match the behavior in git: // https://github.com/git/git/blob/13c7afec212fc97ce257d15601659314c6673d6c/setup.c#L1007-L1018 const match = /^gitdir: (.+?)[\r\n]*$/s.exec(contents) if (!match) return false const gitDir = resolve(dir, match[1]) return existsSync(join(gitDir, 'commondir')) } ``` Sources: [packages/next/src/lib/find-root.ts:53-68](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts#L53-L68) If an inferred candidate root extends past a git repository boundary or into the local home directory returned by `findHomeDir()`, resolution terminates and records a `RootBoundary` descriptor to issue configuration warnings. ```typescript const homeDir = findHomeDir() const gitBoundary = findGitBoundary(cwd) const acceptedCandidates: string[] = [] let boundary: RootBoundary | undefined for (const candidate of candidates) { const dir = dirname(candidate) // the app's own directory is always a valid root. even if it // is the home directory. if (dir !== cwd) { const resolvedDir = toRealPath(dir) // `dir` sits above the repo or worktree that contains the app. if (gitBoundary && isStrictAncestor(resolvedDir, gitBoundary.dir)) { // add a warning for going beyond a repository if (gitBoundary.type === 'repository') { boundary = { boundary: gitBoundary.dir, marker: candidate, root: dir, type: 'repository', } } break } // never treat the home directory (or above) as the root. if (homeDir && isAncestorOrSelf(resolvedDir, homeDir)) { boundary = { boundary: homeDir, marker: candidate, root: dir, type: 'home', } break } } acceptedCandidates.push(candidate) } ``` Sources: [packages/next/src/lib/find-root.ts:181-222](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts#L181-L222) Complementary workspace detection in `packages/next-codemod/lib/agents-md.ts` inspects working directories to classify monorepo types and expand glob patterns for package resolution. ```typescript type WorkspaceType = 'pnpm' | 'npm' | 'yarn' | 'nx' | 'lerna' | null interface WorkspaceInfo { isMonorepo: boolean type: WorkspaceType packages: string[] } ``` Sources: [packages/next-codemod/lib/agents-md.ts:455-461](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts#L455-L461) | Detector / Helper Function | Source Module | Target Markers / Configuration Files | | :--- | :--- | :--- | | `findRootDirAndLockFiles` | `packages/next/src/lib/find-root.ts` | `pnpm-workspace.yaml`, `lerna.json`, `package.json`, `pnpm-lock.yaml`, `package-lock.json`, `yarn.lock`, `bun.lock`, `bun.lockb` | | `findGitBoundary` | `packages/next/src/lib/find-root.ts` | `.git` (directory or worktree pointer file with `commondir`) | | `detectWorkspace` | `packages/next-codemod/lib/agents-md.ts` | `pnpm-workspace.yaml`, `package.json` (`workspaces`), `lerna.json`, `nx.json` | | `getPkgManager` | `packages/next-codemod/lib/handle-package.ts` | `package.json` (`packageManager` field), `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `package-lock.json` | Sources: [packages/next/src/lib/find-root.ts:53-129](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/find-root.ts#L53-L129), [packages/next-codemod/lib/agents-md.ts:455-502](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/agents-md.ts#L455-L502), [packages/next-codemod/lib/handle-package.ts:56-107](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/lib/handle-package.ts#L56-L107) ## Multi-Engine Tooling and Test Orchestration ### Cargo Workspace Configuration and Optimization Profiles The repository integrates a root `Cargo.toml` workspace managing Rust crates for Turbopack, SWC bindings, and NAPI extensions with resolver version `2`. Workspace members include core orchestration and compilation packages such as `next-api`, `next-build`, `next-core`, `crates/next-napi-bindings`, `crates/wasm`, and all workspace members under `turbopack/crates/*`. ``` [workspace] resolver = "2" members = [ "scripts/send-trace-to-jaeger", "crates/next-napi-bindings", "crates/wasm", "crates/next-api", "crates/next-build-test", "crates/next-build", "crates/next-code-frame", "crates/next-core", "crates/next-custom-transforms", "crates/next-taskless", "turbopack/crates/*", "turbopack/crates/*/fuzz", "turbopack/xtask", ] ``` Sources: [Cargo.toml:1-18](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/Cargo.toml#L1-L18) Custom Cargo compilation profiles govern development, release, and debugging behaviors across dependencies and size-optimized crates. The `profile.dev` configuration sets `debug = "line-tables-only"` to improve build times, applies `opt-level = 1` to `turbo-persistence` and external dependencies (`"*"`), and enforces `opt-level = 3` for build scripts via `profile.dev.build-override`. ``` [profile.dev] # https://kobzol.github.io/rust/rustc/2025/05/20/disable-debuginfo-to-improve-rust-compile-times.html debug = "line-tables-only" # This crate is particularly sensitive to compiler optimizations [profile.dev.package.turbo-persistence] opt-level = 1 # Set the options for dependencies (not crates in the workspace), this mostly impacts cold builds [profile.dev.package."*"] opt-level = 1 # Set the settings for build scripts and proc-macros. [profile.dev.build-override] opt-level = 3 ``` Sources: [Cargo.toml:38-53](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/Cargo.toml#L38-L53) > [!NOTE] > Size-optimized crates under `profile.release` target code size reduction (`opt-level = "s"`), specifically compiling Wasmtime, Cranelift, lightningcss, and SWC ecmascript transformation packages to minimize final binary footprints. ``` [profile.release.package.browserslist-rs] opt-level = "s" [profile.release.package.cranelift-codegen] opt-level = "s" [profile.release.package.handlebars] opt-level = "s" [profile.release.package.lightningcss] opt-level = "s" # The vendored napi glue for lightningcss; size-optimized like `lightningcss` itself. [profile.release.package.turbopack-lightningcss-napi] opt-level = "s" [profile.release.package.markdown] opt-level = "s" [profile.release.package.mdxjs] opt-level = "s" [profile.release.package.regalloc2] opt-level = "s" [profile.release.package.regex-syntax] opt-level = "s" [profile.release.package.reqwest] opt-level = "s" [profile.release.package.styled_jsx] opt-level = "s" [profile.release.package.swc_css_prefixer] opt-level = "s" [profile.release.package.swc_ecma_compat_bugfixes] opt-level = "s" [profile.release.package.swc_ecma_compat_es2015] opt-level = "s" [profile.release.package.swc_ecma_compat_es2022] opt-level = "s" [profile.release.package.swc_ecma_preset_env] opt-level = "s" [profile.release.package.swc_ecma_transforms_module] opt-level = "s" [profile.release.package.swc_ecma_transforms_proposal] opt-level = "s" [profile.release.package.swc_plugin_backend_wasmtime] opt-level = "s" [profile.release.package.swc_plugin_runner] opt-level = "s" [profile.release.package.wasmtime] opt-level = "s" [profile.release.package.wasmtime-internal-cranelift] opt-level = "s" ``` Sources: [Cargo.toml:94-160](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/Cargo.toml#L94-L160) | Profile Name | Key Settings & Optimizations | Purpose / Target Components | | :--- | :--- | :--- | | `profile.dev` | `debug = "line-tables-only"`, `opt-level = 1` for `turbo-persistence` and `"*"` | Fast local iteration and compile-time reduction | | `profile.release` | `lto = "thin"`, `codegen-units = 1`, `opt-level = "s"` for specific packages | Production builds with minimized binary size and code duplication | | `profile.release-with-assertions` | `debug-assertions = true`, `overflow-checks = true`, `lto = false`, `codegen-units = 64` | CI or performance-sensitive testing requiring validation checks | | `profile.dev-with-debug` | Inherits `dev`, `debug = true` | Local debugging with full debug information | Sources: [Cargo.toml:38-91](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/Cargo.toml#L38-L91) ### Orchestration Metadata and Test Profiles Workspace orchestration metadata is configured via `conductor.json`, defining framework setup scripts, worktree default branches (`canary`), and environment flags such as `NEXT_TELEMETRY_DISABLED` and `TURBO_TELEMETRY_DISABLED`. Recommendations advise running `pnpm sweep` to clean Rust build artifacts and utilizing `pnpm test-dev-turbo` for accelerated test execution. ```json { "name": "next.js", "description": "Next.js framework development workspace", "scripts": { "setup": "./.conductor/scripts/setup.sh", "run": "./.conductor/scripts/run.sh" }, "worktree": { "default_branch": "canary" }, "environment": { "NEXT_TELEMETRY_DISABLED": "1", "TURBO_TELEMETRY_DISABLED": "1" }, "recommendations": { "parallel_agents": 3, "notes": [ "Each worktree uses ~500MB-1GB disk space after build", "Run 'pnpm sweep' periodically to clean Rust build artifacts", "Use 'pnpm test-dev-turbo' for fastest test iteration", "Never run 'pnpm build' while 'pnpm dev' is active (causes corruption)" ] } ``` Sources: [conductor.json:1-23](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/conductor.json#L1-L23) Test suites and evaluation pipelines coordinate execution across environments through test configuration harnesses. `run-evals.js` packages the local `next` module and provisions agent evals against baseline and documentation-augmented variants (`baseline` and `agents-md`). ```javascript const BASE_VARIANTS = [ { suffix: 'baseline', imports: `import { installNextJs, installPlaywright, prepareFixture } from '../lib/setup.js'`, setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)`, }, { suffix: 'agents-md', imports: `import { installNextJs, installPlaywright, prepareFixture, writeAgentsMd } from '../lib/setup.js'`, setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)\n await writeAgentsMd(sandbox)`, }, ] ``` Sources: [run-evals.js:44-55](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/run-evals.js#L44-L55) The `TestProfile` class in `run-tests.js` captures test behavior identifiers, environment variables, and result caching states. It tracks behavioral variables like `IS_WEBPACK_TEST`, `IS_TURBOPACK_TEST`, `TURBOPACK_DEV`, `TURBOPACK_BUILD`, `BROWSER_NAME`, and `DEVICE_NAME`, while explicitly ignoring operational metadata. ```javascript class TestProfile { // Env vars that always affect test behavior (non-NEXT prefixed). static EXTRA_ENV_VARS = [ 'IS_WEBPACK_TEST', 'IS_TURBOPACK_TEST', 'TURBOPACK_DEV', 'TURBOPACK_BUILD', 'BROWSER_NAME', 'DEVICE_NAME', ] // NEXT_* / __NEXT* vars that are operational, not behavioral. static IGNORED_VARS = new Set([ 'NEXT_TELEMETRY_DISABLED', 'NEXT_TEST_JOB', 'NEXT_JUNIT_TEST_REPORT', 'NEXT_TEST_PREFER_OFFLINE', 'NEXT_CI_RUNNER', 'NEXT_E2E_TEST_TIMEOUT', 'NEXT_TURBOPACK_IO_CONCURRENCY', 'NEXT_TEST_PASSED_FILE', 'NEXT_TEST_BROWSER_WS_ENDPOINT', 'TURBO_TASKS_AVAILABLE_PARALLELISM', ]) // All key=value pairs identifying this test profile, sorted by key. // Used for the diagnostic `log()` output. Computed once at construction // from a snapshot of process.env. The actual cache key for the workflow // is `input_step_key` (see `.github/workflows/build_reusable.yml`). entries // NEXT_*/__NEXT* vars that matched the pattern but were ignored. ignoredVars cachingEnabled ``` Sources: [run-tests.js:23-56](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/run-tests.js#L23-L56) ## Related - [Project Structure](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/orientation/project-structure) - [Build Pipeline](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/build-pipeline) --- ## Technical docs: Server Architecture URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/server/next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts) - [packages/next/src/server/lib/router-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-server.ts) - [packages/next/src/server/lib/start-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/start-server.ts) - [packages/next/src/server/dev/hot-reloader-turbopack.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/hot-reloader-turbopack.ts) - [packages/next/src/server/dev/next-dev-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/next-dev-server.ts) - [packages/next/src/server/base-http/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/index.ts) - [packages/next/src/server/base-http/node.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/node.ts) - [packages/next/src/server/web/spec-extension/adapters/next-request.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/adapters/next-request.ts) - [packages/next/src/server/node-environment-baseline.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/node-environment-baseline.ts) - [packages/next/server.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/server.js) - [packages/next/src/server/app-render/entry-base.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/entry-base.ts) - [packages/next/src/api/server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/api/server.ts) - [packages/next/src/lib/is-error.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts) - [packages/next/src/server/request-meta.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts)
## Overview The Next.js server architecture provides the foundational runtime environment, HTTP request processing pipeline, and modular routing infrastructure that drives both development and production servers. It handles programmatic instantiation via wrapper classes, orchestrates process socket binding and listener bootstrapping, and implements abstract base server contracts specialized for Node.js execution. By normalizing low-level Node.js streams into Web standard request and response abstractions, the server architecture unifies handling across disparate runtimes while managing robust error detection, bubbling, and request metadata propagation throughout the rendering lifecycle. Sources: [packages/next/src/server/next.ts:179-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L179-L190), [packages/next/src/server/lib/router-server.ts:131-145](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-server.ts#L131-L145), [packages/next/src/server/base-server.ts:477-492](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L477-L492), [packages/next/src/server/next-server.ts:198-202](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L198-L202), [packages/next/src/server/base-http/node.ts:19-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/node.ts#L19-L27), [packages/next/src/server/request-meta.ts:51-110](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L51-L110) ## Public Server Entrypoints ### Wrapper Server and Lifecycle Configuration The `NextServer` wrapper class implements `NextWrapperServer` to serve as the programmatic public interface for custom servers and commands like `next start`. It manages asynchronous configuration loading via `loadConfig`, maps runtime phases to `PHASE_DEVELOPMENT_SERVER` or `PHASE_PRODUCTION_SERVER`, and initializes either `NextNodeServer` or `NextDevServer` depending on `options.dev`. ```typescript export class NextServer implements NextWrapperServer { private serverPromise?: Promise private server?: NextNodeServer private reqHandler?: NodeRequestHandler private reqHandlerPromise?: Promise private preparedAssetPrefix?: string public options: NextServerOptions constructor(options: NextServerOptions) { this.options = options } ``` Sources: [packages/next/src/server/next.ts:179-190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L179-L190) ```typescript private async [SYMBOL_LOAD_CONFIG]() { const dir = path.resolve( /* turbopackIgnore: true */ this.options.dir || '.' ) const config = await loadConfig( this.options.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER, dir, { customConfig: this.options.conf, silent: true, } ) ``` Sources: [packages/next/src/server/next.ts:342-355](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L342-L355) > [!WARNING] > `NextServer` enforces strict checks on production output configurations during initialization. If `conf.output === 'standalone'` is set without `__NEXT_PRIVATE_STANDALONE_CONFIG`, a warning is logged, whereas `conf.output === 'export'` throws an immediate error instructing the user to use `serve` instead. ```typescript if (!this.options.dev) { if (conf.output === 'standalone') { if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) { log.warn( `"next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.` ) } } else if (conf.output === 'export') { throw new Error( `"next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.` ) } } ``` Sources: [packages/next/src/server/next.ts:389-401](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L389-L401) ### Deprecated Custom Server Methods Custom server instances expose several legacy methods that are guarded with runtime warnings via `warnDeprecatedCustomServerMethod`. The mapping of deprecated methods to alternative guidance is maintained in `DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE`. | Deprecated Method | Guidance Message | | :--- | :--- | | `setAssetPrefix` | Please configure `assetPrefix` in `next.config.js` instead. | | `logError` | Please use application logging instead. | | `logErrorWithOriginalStack` | Please use application logging instead. | | `revalidate` | Please use documented application revalidation APIs instead. | | `render` | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `renderToHTML` | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `renderError` | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `renderErrorToHTML` | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | | `render404` | Please use `app.getRequestHandler()` with an adjusted parsed URL instead. | ```typescript const DEPRECATED_CUSTOM_SERVER_METHOD_GUIDANCE: Record< DeprecatedCustomServerMethod, string > = { setAssetPrefix: 'Please configure `assetPrefix` in `next.config.js` instead.', logError: 'Please use application logging instead.', logErrorWithOriginalStack: 'Please use application logging instead.', revalidate: 'Please use documented application revalidation APIs instead.', render: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', renderToHTML: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', renderError: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', renderErrorToHTML: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', render404: 'Please use `app.getRequestHandler()` with an adjusted parsed URL instead.', } ``` Sources: [packages/next/src/server/next.ts:84-102](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next.ts#L84-L102) ## Server Initialization and Bootstrapping ### Baseline Runtime Environment and Server Startup Before loading any application modules or establishing network sockets, the server establishes its baseline runtime environment via `node-environment-baseline.ts`. This initialization step ensures that `AsyncLocalStorage` from `async_hooks` is exposed on `globalThis` for React context propagation if the host environment does not provide it natively. Additionally, it defines a getter property on `globalThis` for `WebSocket`, lazily requiring `next/dist/compiled/ws` when accessed. ```typescript if (typeof (globalThis as any).AsyncLocalStorage !== 'function') { const { AsyncLocalStorage } = require('async_hooks') as typeof import('async_hooks') ;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage } if (typeof (globalThis as any).WebSocket !== 'function') { Object.defineProperty(globalThis, 'WebSocket', { configurable: true, get() { return ( require('next/dist/compiled/ws') as typeof import('next/dist/compiled/ws') ).WebSocket }, set(value) { Object.defineProperty(globalThis, 'WebSocket', { configurable: true, writable: true, value, }) }, }) ``` Sources: [packages/next/src/server/node-environment-baseline.ts:5-26](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/node-environment-baseline.ts#L5-L26) The core bootstrapping function `startServer` in `start-server.ts` updates `process.title` to `next-server (v${process.env.__NEXT_VERSION})` and instantiates the underlying HTTP listener. Depending on whether `selfSignedCertificate` options and production constraints are met, it invokes either `https.createServer` or `http.createServer` with a `requestListener`. ```typescript let { port } = serverOptions process.title = `next-server (v${process.env.__NEXT_VERSION})` let handlersReady = () => {} let handlersError = () => {} let handlersPromise: Promise | undefined = new Promise( (resolve, reject) => { handlersReady = resolve handlersError = reject } ) let requestHandler: WorkerRequestHandler = async ( req: IncomingMessage, res: ServerResponse ): Promise => { if (handlersPromise) { await handlersPromise return requestHandler(req, res) } throw new Error('Invariant request handler was not setup') } let upgradeHandler: WorkerUpgradeHandler = async ( req, socket, head ): Promise => { if (handlersPromise) { await handlersPromise return upgradeHandler(req, socket, head) } throw new Error('Invariant upgrade handler was not setup') } let nextServer: NextServer | undefined let devMemoryThresholdRestart = true // setup server listener as fast as possible if (selfSignedCertificate && !isDev) { throw new Error( 'Using a self signed certificate is only supported with `next dev`.' ) } async function requestListener(req: IncomingMessage, res: ServerResponse) { try { if (handlersPromise) { await handlersPromise handlersPromise = undefined } await requestHandler(req, res) } catch (err) { res.statusCode = 500 res.end('Internal Server Error') Log.error(`Failed to handle request for ${req.url}`) console.error(err) } finally { const memoryRestartStats = getMemoryRestartStats( isDev, devMemoryThresholdRestart, v8.getHeapStatistics ) if (memoryRestartStats) { Log.warn( `Server is approaching the used memory threshold, restarting...` ) trace('server-restart-close-to-memory-threshold', undefined, { 'memory.heapSizeLimit': String(memoryRestartStats.heap_size_limit), 'memory.heapUsed': String(memoryRestartStats.used_heap_size), }).stop() flushAllTraces() process.exit(RESTART_EXIT_CODE) } } } const server = selfSignedCertificate ? https.createServer( { key: fs.readFileSync(selfSignedCertificate.key), ``` Sources: [packages/next/src/server/lib/start-server.ts:204-288](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/start-server.ts#L204-L288) > [!CAUTION] > Using a self-signed certificate via `selfSignedCertificate` is strictly restricted to development mode (`isDev`). Attempting to use a self-signed certificate when `isDev` is false causes `startServer` to throw an immediate error during listener setup. ```typescript if (selfSignedCertificate && !isDev) { throw new Error( 'Using a self signed certificate is only supported with `next dev`.' ) } ``` Sources: [packages/next/src/server/lib/start-server.ts:242-246](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/start-server.ts#L242-L246) ### Socket Binding, Port Allocation, and Termination Signals Once the server instance is configured with optional `keepAliveTimeout` and upgrade event handlers, it binds to the specified port and hostname. If `allowRetry` is enabled and an `EADDRINUSE` error occurs on `error`, the [development server](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/development-server) automatically increments the port by one and retries up to 10 times before logging a fatal startup failure and exiting the process with code `1`. ```typescript if (keepAliveTimeout) { server.keepAliveTimeout = keepAliveTimeout } server.on('upgrade', async (req, socket, head) => { try { await upgradeHandler(req, socket, head) } catch (err) { socket.destroy() Log.error(`Failed to handle request for ${req.url}`) console.error(err) } }) let portRetryCount = 0 const originalPort = port server.on('error', (err: NodeJS.ErrnoException) => { if ( allowRetry && port && isDev && err.code === 'EADDRINUSE' && portRetryCount < 10 ) { port += 1 portRetryCount += 1 server.listen(port, hostname) } else { Log.error(`Failed to start server`) console.error(err) process.exit(1) } }) ``` Sources: [packages/next/src/server/lib/start-server.ts:290-322](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/start-server.ts#L290-L322) Upon successfully emitting the `listening` event, the server registers signal handlers for graceful process termination unless `NEXT_MANUAL_SIG_HANDLE` is set in the environment. | Signal | Exit Code Behavior | | :--- | :--- | | `SIGINT` | Exits process with code `130` (signal termination) | | `SIGTERM` | Exits process with code `143` (signal termination) | | Default / Unhandled | Exits process with code `128` | ```typescript switch (signal) { case 'SIGINT': process.exit(130) break case 'SIGTERM': process.exit(143) break default: // Make sure all handled signals have explicit exit codes. // This is just a fallback to guard against unsound types. signal satisfies never process.exit(128) } })() } // Make sure commands gracefully respect termination signals (e.g. from Docker) // Allow the graceful termination to be manually configurable if (!process.env.NEXT_MANUAL_SIG_HANDLE) { process.on('SIGINT', cleanup) process.on('SIGTERM', cleanup) } ``` Sources: [packages/next/src/server/lib/start-server.ts:471-492](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/start-server.ts#L471-L492) ## BaseServer Architecture and Core Contracts ### Abstract Server Responsibilities and Constructor Initialization `BaseServer` serves as the abstract coordinator for Next.js HTTP request handling, environment configuration, and asset normalization across different execution runtimes. The constructor initializes configuration values, sets up path resolvers, and instantiates request normalizers based on whether app directories, pages directories, or internationalization settings are active. ```typescript public constructor(options: ServerOptions) { const { dir = '.', quiet = false, conf, dev = false, minimalMode = false, hostname, port, experimentalTestProxy, } = options this.dev = dev this.experimentalTestProxy = experimentalTestProxy this.serverOptions = options this.dir = path.resolve(/* turbopackIgnore: true */ dir) this.quiet = quiet this.loadEnvConfig({ dev, forceReload: false }) // TODO: should conf be normalized to prevent missing // values from causing issues as this can be user provided this.nextConfig = conf as NextConfigRuntime if ( (dev || process.env.__NEXT_DEV_SERVER) && this.nextConfig.experimental.requestInsights ) { process.env.__NEXT_REQUEST_INSIGHTS = 'true' } if (this.nextConfig.experimental.runtimeServerDeploymentId) { if (!process.env.NEXT_DEPLOYMENT_ID) { throw new Error( 'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled' ) } this.deploymentId = process.env.NEXT_DEPLOYMENT_ID } else { let id = this.nextConfig.experimental.useSkewCookie ? '' : this.nextConfig.deploymentId || '' this.deploymentId = id process.env.NEXT_DEPLOYMENT_ID = id } ;(globalThis as any).NEXT_CLIENT_ASSET_SUFFIX = this.nextConfig.supportsImmutableAssets || !this.deploymentId ? '' : `?dpl=${this.deploymentId}` this.hostname = hostname if (this.hostname) { // we format the hostname so that it can be fetched this.fetchHostname = formatHostname(this.hostname) } this.port = port this.distDir = path.join( /* turbopackIgnore: true */ this.dir, this.nextConfig.distDir ) this.pagesNormalizers = new PagesNormalizers(this.distDir) this.appNormalizers = new AppNormalizers(this.distDir) this.publicDir = this.getPublicDir() this.hasStaticDir = !minimalMode && this.getHasStaticDir() this.i18nProvider = this.nextConfig.i18n?.locales ? new I18NProvider(this.nextConfig.i18n) : undefined // Configure the locale normalizer, it's used for routes inside `pages/`. this.localeNormalizer = this.i18nProvider ? new LocaleRouteNormalizer(this.i18nProvider) : undefined const { assetPrefix, generateEtags } = this.nextConfig this.buildId = this.getBuildId() // this is a hack to avoid Webpack knowing this is equal to this.minimalMode // because we replace this.minimalMode to true in production bundles. ``` Sources: [packages/next/src/server/base-server.ts:477-580](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L477-L580) During initialization, the server resolves the root application directory (`dir`), configures deployment identifiers via `process.env.NEXT_DEPLOYMENT_ID` or `runtimeServerDeploymentId`, and sets up locale normalizers if internationalization is enabled. It configures path normalizers for Pages (`PagesNormalizers`) and App (`AppNormalizers`) routes within the distribution directory (`distDir`). ```typescript this.dir = path.resolve(/* turbopackIgnore: true */ dir) this.quiet = quiet this.loadEnvConfig({ dev, forceReload: false }) // TODO: should conf be normalized to prevent missing // values from causing issues as this can be user provided this.nextConfig = conf as NextConfigRuntime if ( (dev || process.env.__NEXT_DEV_SERVER) && this.nextConfig.experimental.requestInsights ) { process.env.__NEXT_REQUEST_INSIGHTS = 'true' } if (this.nextConfig.experimental.runtimeServerDeploymentId) { if (!process.env.NEXT_DEPLOYMENT_ID) { throw new Error( 'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled' ) } this.deploymentId = process.env.NEXT_DEPLOYMENT_ID } else { let id = this.nextConfig.experimental.useSkewCookie ? '' : this.nextConfig.deploymentId || '' this.deploymentId = id process.env.NEXT_DEPLOYMENT_ID = id } ;(globalThis as any).NEXT_CLIENT_ASSET_SUFFIX = this.nextConfig.supportsImmutableAssets || !this.deploymentId ? '' : `?dpl=${this.deploymentId}` this.hostname = hostname if (this.hostname) { // we format the hostname so that it can be fetched this.fetchHostname = formatHostname(this.hostname) } this.port = port this.distDir = path.join( /* turbopackIgnore: true */ this.dir, this.nextConfig.distDir ) this.pagesNormalizers = new PagesNormalizers(this.distDir) this.appNormalizers = new AppNormalizers(this.distDir) this.publicDir = this.getPublicDir() this.hasStaticDir = !minimalMode && this.getHasStaticDir() ``` Sources: [packages/next/src/server/base-server.ts:493-541](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L493-L541) > [!CAUTION] > If `runtimeServerDeploymentId` is enabled in `nextConfig.experimental`, `process.env.NEXT_DEPLOYMENT_ID` must be defined beforehand. If the environment variable is missing during server startup, `BaseServer` throws an immediate error. ```typescript if (this.nextConfig.experimental.runtimeServerDeploymentId) { if (!process.env.NEXT_DEPLOYMENT_ID) { throw new Error( 'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled' ) } this.deploymentId = process.env.NEXT_DEPLOYMENT_ID ``` Sources: [packages/next/src/server/base-server.ts:508-514](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L508-L514) ### Normalizers and Render Options Configuration The constructor constructs a core set of request path normalizers and builds the internal `renderOpts` object passed down to rendering pipelines. The normalizers object routes incoming requests through specialized prefix checkers depending on whether the server operates in minimal mode or handles server components. | Normalizer Property | Class Type / Condition | | :--- | :--- | | `rsc` | `RSCPathnameNormalizer` (Active if `enabledDirectories.app` and `minimalMode` are true) | | `segmentPrefetchRSC` | `SegmentPrefixRSCPathnameNormalizer` (Active if `minimalMode` is true) | | `data` | `NextDataPathnameNormalizer` (Active if `enabledDirectories.pages` is true, initialized with `buildId`) | ```typescript this.normalizers = { // We should normalize the pathname from the RSC prefix only in minimal // mode as otherwise that route is not exposed external to the server as // we instead only rely on the headers. rsc: this.enabledDirectories.app && this.minimalMode ? new RSCPathnameNormalizer() : undefined, segmentPrefetchRSC: this.minimalMode ? new SegmentPrefixRSCPathnameNormalizer() : undefined, data: this.enabledDirectories.pages ? new NextDataPathnameNormalizer(this.buildId) : undefined, } ``` Sources: [packages/next/src/server/base-server.ts:566-580](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L566-L580) The server also compiles `renderOpts` using configuration options extracted from `this.nextConfig`, including base paths, asset prefixes, experimental feature flags like taint support, script workers, optimize CSS, and internationalized domain settings. ```typescript this.renderOpts = { dir: this.dir, supportsDynamicResponse: true, trailingSlash: this.nextConfig.trailingSlash, poweredByHeader: this.nextConfig.poweredByHeader, generateEtags, previewProps: this.getPreviewProps(), basePath: this.nextConfig.basePath, images: this.nextConfig.images, optimizeCss: this.nextConfig.experimental.optimizeCss, nextConfigOutput: this.nextConfig.output, nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers, disableOptimizedLoading: this.nextConfig.experimental.disableOptimizedLoading, domainLocales: this.nextConfig.i18n?.domains, distDir: this.distDir, serverComponents: this.enabledDirectories.app, cacheLifeProfiles: this.nextConfig.cacheLife, staticPageGenerationTimeout: this.nextConfig.staticPageGenerationTimeout, enableTainting: this.nextConfig.experimental.taint, crossOrigin: this.nextConfig.crossOrigin ? this.nextConfig.crossOrigin : undefined, largePageDataBytes: this.nextConfig.experimental.largePageDataBytes, isExperimentalCompile: options.compileMode ? options.compileMode.isExperimentalCompile : this.nextConfig.experimental.isExperimentalCompile, ``` Sources: [packages/next/src/server/base-server.ts:584-611](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L584-L611) ## NextNodeServer Specialization and Execution ### Node.js Platform Server Implementation and Request Normalization `NextNodeServer` extends `BaseServer` to implement the Node.js production server runtime, inheriting platform-specific request routing, file system caching bindings, and custom server handlers. The server initializes request adapters that bridge incoming Node.js `IncomingMessage` and `ServerResponse` streams into `NodeNextRequest` and `NodeNextResponse` wrappers. ```typescript protected normalizeReq( req: NodeNextRequest | IncomingMessage ): NodeNextRequest { return !(req instanceof NodeNextRequest) ? new NodeNextRequest(req) : req } protected normalizeRes( res: NodeNextResponse | ServerResponse ): NodeNextResponse { return !(res instanceof NodeNextResponse) ? new NodeNextResponse(res) : res } ``` Sources: [packages/next/src/server/next-server.ts:1339-1349](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1339-L1349) The request handler pipeline ensures that `prepare()` is fired eagerly upon request receipt while catching unhandled rejections prior to execution. When `getRequestHandler()` or `getRequestHandlerWithMetadata()` is invoked, incoming parameters and metadata are bound to request attributes via `setRequestMeta` before routing through the parent handler. ```typescript public getRequestHandler(): NodeRequestHandler { const handler = this.makeRequestHandler() if (this.serverOptions.experimentalTestProxy) { const { wrapRequestHandlerNode } = // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm require('next/dist/experimental/testmode/server') as typeof import('../experimental/testmode/server') return wrapRequestHandlerNode(handler) } return handler } /** * @internal - this method is internal to Next.js and should not be used directly by end-users */ public getRequestHandlerWithMetadata(meta: RequestMeta): NodeRequestHandler { const handler = this.makeRequestHandler() return (req, res, parsedUrl) => { setRequestMeta(req, meta) return handler(req, res, parsedUrl) } } ``` Sources: [packages/next/src/server/next-server.ts:1351-1371](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1351-L1371) > [!WARNING] > Calling `ensurePage` directly on `NextNodeServer` outside of development environments throws an immediate invariant error, as on-demand compilation is restricted to development server instances. ```typescript throw new Error( 'Invariant: ensurePage can only be called on the development server' ) } ``` Sources: [packages/next/src/server/next-server.ts:1315-1318](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1315-L1318) ### Caching Bridges and Incremental Cache Configuration `NextNodeServer` manages caching bridges by integrating custom cache handlers and delegating file system operations to `nodeFs`. Custom cache handlers specified in the user configuration are dynamically imported via `dynamicImportEsmDefault`, interoped, and registered using `setCacheHandler`. ```typescript const { cacheMaxMemorySize, cacheHandlers } = this.nextConfig if (!cacheHandlers) return initializeCacheHandlers(cacheMaxMemorySize) await registerCustomCacheHandlers(async () => { for (const [kind, handler] of Object.entries(cacheHandlers)) { if (!handler) continue setCacheHandler( kind, interopDefault( await dynamicImportEsmDefault( formatDynamicImportPath(this.distDir, handler) ) ) ) } }) } ``` Sources: [packages/next/src/server/next-server.ts:431-449](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L431-L449) The [incremental cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) setup method inspects `this.nextConfig` for a `cacheHandler` property, loads any custom handlers asynchronously, and returns the configured cache instance for downstream rendering workers. ```typescript protected async getIncrementalCache({ requestHeaders, }: { requestHeaders: IncrementalCache['requestHeaders'] }) { const dev = !!this.dev let CacheHandler: any const { cacheHandler } = this.nextConfig if (cacheHandler) { CacheHandler = interopDefault( await dynamicImportEsmDefault( formatDynamicImportPath(this.distDir, cacheHandler) ) ) } await this.loadCustomCacheHandlers() ``` Sources: [packages/next/src/server/next-server.ts:451-468](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L451-L468) | Method / Utility | Target Platform / Module | Purpose | | :--- | :--- | :--- | | `getCacheFilesystem()` | `CacheFs` (`nodeFs`) | Supplies the Node.js file system interface for cache persistence | | `normalizeReq()` | `NodeNextRequest` | Wraps raw Node.js `IncomingMessage` objects into Next.js base request streams | | `normalizeRes()` | `NodeNextResponse` | Wraps raw Node.js `ServerResponse` objects into Next.js base response streams | | `handleApiRequest()` | `PagesAPIRouteMatch` | Dispatches legacy Pages API requests via `runApi` execution | ```typescript protected async handleApiRequest( req: NodeNextRequest, res: NodeNextResponse, query: ParsedUrlQuery, match: PagesAPIRouteMatch ): Promise { return this.runApi(req, res, query, match) } protected getCacheFilesystem(): CacheFs { return nodeFs } ``` Sources: [packages/next/src/server/next-server.ts:1326-1337](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1326-L1337) ## HTTP Abstractions and Request Adaptation ### BaseNextRequest and BaseNextResponse Abstractions Next.js decouples core request handling from platform-specific APIs by defining abstract base classes: `BaseNextRequest` and `BaseNextResponse`. The `BaseNextRequest` abstract class manages request properties including method, URL, body, and headers, while providing a lazy cookie parser utilizing `getCookieParser` configured with request headers. ```typescript export abstract class BaseNextRequest { protected _cookies: NextApiRequestCookies | undefined public abstract headers: IncomingHttpHeaders public abstract fetchMetrics: FetchMetric[] | undefined constructor( public method: string, public url: string, public body: Body ) {} // Utils implemented using the abstract methods above public get cookies() { if (this._cookies) return this._cookies return (this._cookies = getCookieParser(this.headers)()) } } ``` Sources: [packages/next/src/server/base-http/index.ts:28-45](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/index.ts#L28-L45) `BaseNextResponse` defines abstract interfaces for status codes, headers, body setting, and response dispatching. It includes helper methods like `redirect`, which automatically sets the `Location` header, status code, and a fallback `Refresh` header if the status code is a permanent redirect. ```typescript export abstract class BaseNextResponse { abstract statusCode: number | undefined abstract statusMessage: string | undefined abstract get sent(): boolean constructor(public destination: Destination) {} /** * Sets a value for the header overwriting existing values */ abstract setHeader(name: string, value: string | string[]): this /** * Removes a header */ abstract removeHeader(name: string): this /** * Appends value for the given header name */ abstract appendHeader(name: string, value: string): this /** * Get all values for a header as an array or undefined if no value is present */ abstract getHeaderValues(name: string): string[] | undefined abstract hasHeader(name: string): boolean /** * Get values for a header concatenated using `,` or undefined if no value is present */ abstract getHeader(name: string): string | undefined abstract getHeaders(): OutgoingHttpHeaders abstract body(value: string): this abstract send(): void abstract onClose(callback: () => void): void // Utils implemented using the abstract methods above public redirect(destination: string, statusCode: number) { this.setHeader('Location', destination) this.statusCode = statusCode // Since IE11 doesn't support the 308 header add backwards // compatibility using refresh header if (statusCode === RedirectStatusCode.PermanentRedirect) { this.setHeader('Refresh', `0;url=${destination}`) } return this } ``` Sources: [packages/next/src/server/base-http/index.ts:47-102](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/index.ts#L47-L102) ### Node.js Platform Stream Implementation The `NodeNextRequest` and `NodeNextResponse` classes extend the base abstractions to wrap Node.js `IncomingMessage` and `ServerResponse` objects. `NodeNextRequest` exposes a `stream()` method that converts the underlying Node.js readable stream into a Web `ReadableStream`, ensuring the stream can only be read once. ```typescript export class NodeNextRequest extends BaseNextRequest { public headers = this._req.headers public fetchMetrics: FetchMetric[] | undefined = this._req?.fetchMetrics; [NEXT_REQUEST_META]: RequestMeta = this._req[NEXT_REQUEST_META] || {} constructor(private _req: Req) { super(_req.method!.toUpperCase(), _req.url!, _req) } get originalRequest() { // Need to mimic these changes to the original req object for places where we use it: // render.tsx, api/ssg requests this._req[NEXT_REQUEST_META] = this[NEXT_REQUEST_META] this._req.url = this.url this._req.cookies = this.cookies return this._req } set originalRequest(value: Req) { this._req = value } private streaming = false /** * Returns the request body as a Web Readable Stream. The body here can only * be read once as the body will start flowing as soon as the data handler * is attached. * * @internal */ public stream() { if (this.streaming) { throw new Error( 'Invariant: NodeNextRequest.stream() can only be called once' ) } this.streaming = true return new ReadableStream({ start: (controller) => { this._req.on('data', (chunk) => { controller.enqueue(new Uint8Array(chunk)) }) this._req.on('end', () => { controller.close() }) this._req.on('error', (err) => { controller.error(err) }) }, }) } } ``` Sources: [packages/next/src/server/base-http/node.ts:19-73](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/node.ts#L19-L73) > [!WARNING] > Calling `NodeNextRequest.stream()` more than once triggers an invariant error stating that the stream can only be called once, preventing multiple consumers from reading a consumed request body. ```typescript public stream() { if (this.streaming) { throw new Error( 'Invariant: NodeNextRequest.stream() can only be called once' ) } this.streaming = true ``` Sources: [packages/next/src/server/base-http/node.ts:51-57](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/node.ts#L51-L57) `NodeNextResponse` delegates header manipulation, status code setting, and response finalization directly to the underlying Node.js `ServerResponse` instance. ```typescript export class NodeNextResponse extends BaseNextResponse { private textBody: string | undefined = undefined public [SYMBOL_CLEARED_COOKIES]?: boolean get originalResponse() { if (SYMBOL_CLEARED_COOKIES in this) { this._res[SYMBOL_CLEARED_COOKIES] = this[SYMBOL_CLEARED_COOKIES] } return this._res } constructor( private _res: ServerResponse & { [SYMBOL_CLEARED_COOKIES]?: boolean } ) { super(_res) } get sent() { return this._res.finished || this._res.headersSent } get statusCode() { return this._res.statusCode } set statusCode(value: number) { this._res.statusCode = value } get statusMessage() { return this._res.statusMessage } set statusMessage(value: string) { this._res.statusMessage = value } setHeader(name: string, value: string | string[]): this { this._res.setHeader(name, value) return this } removeHeader(name: string): this { this._res.removeHeader(name) return this } getHeaderValues(name: string): string[] | undefined { const values = this._res.getHeader(name) if (values === undefined) return undefined return (Array.isArray(values) ? values : [values]).map((value) => value.toString() ) } hasHeader(name: string): boolean { return this._res.hasHeader(name) } getHeader(name: string): string | undefined { const values = this.getHeaderValues(name) return Array.isArray(values) ? values.join(',') : undefined } getHeaders(): OutgoingHttpHeaders { return this._res.getHeaders() } appendHeader(name: string, value: string): this { const currentValues = this.getHeaderValues(name) ?? [] if (!currentValues.includes(value)) { this._res.setHeader(name, [...currentValues, value]) } return this ``` Sources: [packages/next/src/server/base-http/node.ts:75-169](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-http/node.ts#L75-L169) ### Bridging to Web NextRequest via NextRequestAdapter `NextRequestAdapter` transforms `BaseNextRequest` instances into standard `NextRequest` objects depending on the active execution runtime environment. When running outside the [edge runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime), `fromNodeNodeNextRequest` resolves relative URLs against request metadata and configures the request with a half-duplex body and an abort signal tied to the underlying response lifecycle. ```typescript export class NextRequestAdapter { public static fromBaseNextRequest( request: BaseNextRequest, signal: AbortSignal ): NextRequest { if ( // The type check here ensures that `req` is correctly typed, and the // environment variable check provides dead code elimination. process.env.NEXT_RUNTIME === 'edge' && isWebNextRequest(request) ) { return NextRequestAdapter.fromWebNextRequest(request) } else if ( // The type check here ensures that `req` is correctly typed, and the // environment variable check provides dead code elimination. process.env.NEXT_RUNTIME !== 'edge' && isNodeNextRequest(request) ) { return NextRequestAdapter.fromNodeNextRequest(request, signal) } else { throw new Error('Invariant: Unsupported NextRequest type') } } public static fromNodeNextRequest( request: NodeNextRequest, signal: AbortSignal ): NextRequest { // HEAD and GET requests can not have a body. let body: BodyInit | null = null if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) { // @ts-expect-error - this is handled by undici, when streams/web land use it instead body = request.body } let url: URL if (request.url.startsWith('http')) { url = new URL(request.url) } else { // Grab the full URL from the request metadata. const base = getRequestMeta(request, 'initURL') if (!base || !base.startsWith('http')) { // Because the URL construction relies on the fact that the URL provided // is absolute, we need to provide a base URL. We can't use the request // URL because it's relative, so we use a dummy URL instead. url = new URL(request.url, 'http://n') } else { url = new URL(request.url, base) } } return new NextRequest(url, { method: request.method, headers: fromNodeOutgoingHttpHeaders(request.headers), duplex: 'half', signal, // geo // ip // nextConfig // body can not be passed if request was aborted // or we get a Request body was disturbed error ...(signal.aborted ? {} : { body, }), }) } ``` Sources: [packages/next/src/server/web/spec-extension/adapters/next-request.ts:56-124](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/adapters/next-request.ts#L56-L124) > [!IMPORTANT] > If a request signal has already been aborted, `NextRequestAdapter` omits the request body entirely from the constructed `NextRequest` to prevent disturbing or consuming an aborted body stream. ```typescript // body can not be passed if request was aborted // or we get a Request body was disturbed error ...(signal.aborted ? {} : { body, }), }) ``` Sources: [packages/next/src/server/web/spec-extension/adapters/next-request.ts:116-123](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/adapters/next-request.ts#L116-L123) | Adapter Method | Target Input Type | Output Type | Purpose | | :--- | :--- | :--- | :--- | | `fromBaseNextRequest()` | `BaseNextRequest` | `NextRequest` | Runtime-dispatched entrypoint routing to node or web adapters | | `fromNodeNextRequest()` | `NodeNextRequest` | `NextRequest` | Converts Node.js incoming messages and metadata into standard `NextRequest` | | `fromWebNextRequest()` | `WebNextRequest` | `NextRequest` | Adapts web-native request wrappers for standard spec consumption | ```typescript export class NextRequestAdapter { public static fromBaseNextRequest( request: BaseNextRequest, signal: AbortSignal ): NextRequest { if ( // The type check here ensures that `req` is correctly typed, and the // environment variable check provides dead code elimination. process.env.NEXT_RUNTIME === 'edge' && isWebNextRequest(request) ) { return NextRequestAdapter.fromWebNextRequest(request) } else if ( // The type check here ensures that `req` is correctly typed, and the // environment variable check provides dead code elimination. process.env.NEXT_RUNTIME !== 'edge' && isNodeNextRequest(request) ) { return NextRequestAdapter.fromNodeNextRequest(request, signal) } else { throw new Error('Invariant: Unsupported NextRequest type') } } ``` Sources: [packages/next/src/server/web/spec-extension/adapters/next-request.ts:56-78](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/adapters/next-request.ts#L56-L78) ## Server Error Handling and Normalization ### Error Types and Safe Stringification Next.js defines the `NextError` interface extending standard errors to include optional properties like `type`, `page`, `code`, `cancelled`, and `digest`. The `isError` utility validates whether an unknown thrown value is an object containing `name` and `message` properties. ```typescript export interface NextError extends Error { type?: string page?: string code?: string | number cancelled?: boolean digest?: string } ``` Sources: [packages/next/src/lib/is-error.ts:4-10](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts#L4-L10) ```typescript export default function isError(err: unknown): err is NextError { return ( typeof err === 'object' && err !== null && 'name' in err && 'message' in err ) } ``` Sources: [packages/next/src/lib/is-error.ts:38-42](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts#L38-L42) The `safeStringifyLite` helper serializes objects without requiring external production dependencies by tracking circular references with a `WeakSet` and replacing duplicates with `"[Circular]"`. ```typescript function safeStringifyLite(obj: any) { const seen = new WeakSet() return JSON.stringify(obj, (_key, value) => { // If value is an object and already seen, replace with "[Circular]" if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return '[Circular]' } seen.add(value) } return value }) } ``` Sources: [packages/next/src/lib/is-error.ts:19-32](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts#L19-L32) ### Error Normalization and Development Diagnostics The `getProperError` function normalizes thrown values into standard `Error` instances. In development mode, throwing `undefined` or `null` triggers explicit errors referencing documentation URLs for diagnostics. ```typescript export function getProperError(err: unknown): Error { if (isError(err)) { return err } if (process.env.NODE_ENV === 'development') { // provide better error for case where `throw undefined` // is called in development if (typeof err === 'undefined') { return new Error( 'An undefined error was thrown, ' + 'see here for more info: https://nextjs.org/docs/messages/threw-undefined' ) } if (err === null) { return new Error( 'A null error was thrown, ' + 'see here for more info: https://nextjs.org/docs/messages/threw-undefined' ) } } ``` Sources: [packages/next/src/lib/is-error.ts:44-65](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts#L44-L65) > [!WARNING] > Plain objects passed as thrown values are converted to JSON strings using `safeStringifyLite`, while primitive values are coerced into strings before being wrapped in an `Error`. ```typescript return new Error(isPlainObject(err) ? safeStringifyLite(err) : err + '') ``` Sources: [packages/next/src/lib/is-error.ts:67-67](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts#L67-L67) | Helper Function | Input Type | Output Type | Purpose | | :--- | :--- | :--- | :--- | | `isError()` | `unknown` | `err is NextError` | Type guard checking for object structure with `name` and `message` | | `getProperError()` | `unknown` | `Error` | Normalizes non-error throwables, handling `undefined`, `null`, and plain objects | | `safeStringifyLite()` | `any` | `string` | Safe JSON serializer guarding against circular references using a `WeakSet` | ```typescript function safeStringifyLite(obj: any) { const seen = new WeakSet() return JSON.stringify(obj, (_key, value) => { // If value is an object and already seen, replace with "[Circular]" if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return '[Circular]' } seen.add(value) } return value }) } /** * Checks whether the given value is a NextError. * This can be used to print a more detailed error message with properties like `code` & `digest`. */ export default function isError(err: unknown): err is NextError { return ( typeof err === 'object' && err !== null && 'name' in err && 'message' in err ) } ``` Sources: [packages/next/src/lib/is-error.ts:19-42](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/lib/is-error.ts#L19-L42) ## Related - [Request Lifecycle](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/request-lifecycle) - [Route Handlers](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers) - [Edge Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime) --- ## Technical docs: Request Lifecycle URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/request-lifecycle
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next-routing/src/resolve-routes.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-routing/src/resolve-routes.ts) - [packages/next/src/server/lib/router-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-server.ts) - [packages/next/src/build/templates/app-route.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts) - [packages/next/src/build/templates/app-page-runtime.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts) - [packages/next/src/server/lib/router-utils/resolve-routes.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-utils/resolve-routes.ts) - [packages/next/src/server/dev/next-dev-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/next-dev-server.ts) - [packages/next/src/server/web/adapter.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts) - [packages/next/src/build/templates/edge-ssr-app.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts) - [packages/next/src/build/templates/pages-api.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts) - [packages/next/src/server/route-modules/app-route/module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts) - [packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts) - [packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts) - [packages/next/src/server/request-meta.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts) - [packages/next/src/server/send-payload.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts) - [packages/next/src/build/duration-to-string.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/duration-to-string.ts) - [packages/next/src/server/config.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/config.ts)
## Overview The request lifecycle orchestrates how HTTP requests are received, parsed, routed, and fulfilled across both Node.js and [Edge Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime) environments. It manages request metadata propagation via [Async Storage](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/async-storage), matches incoming paths against custom routes, headers, and redirects, and normalizes bundle paths for App and Pages directories. The pipeline controls the execution of Server Components, [Route Handlers](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers), and legacy Pages APIs while interfacing with the [Incremental Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) to dispatch optimized payloads and responses. Sources: [packages/next/src/server/base-server.ts:1071-1080](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts#L1071-L1080), [packages/next/src/server/web/adapter.ts:127-145](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts#L127-L145), [packages/next/src/server/request-meta.ts:51-175](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L51-L175), [packages/next-routing/src/resolve-routes.ts:557-600](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-routing/src/resolve-routes.ts#L557-L600), [packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts:7-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts#L7-L15), [packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts:7-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts#L7-L21), [packages/next/src/build/templates/app-page-runtime.ts:245-280](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L245-L280), [packages/next/src/build/templates/pages-api.ts:47-80](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L47-L80), [packages/next/src/server/send-payload.ts:35-50](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L35-L50) ## Edge and Server Request Metadata ### Request Metadata Operations Per-request metadata tracking in Next.js relies on a shared internal symbol `NEXT_REQUEST_META` (`Symbol.for('NextInternalRequestMeta')`) attached directly to incoming message objects (`NextIncomingMessage`), bridging Node.js HTTP requests, base HTTP wrappers, and Web API request types. Sources: [packages/next/src/server/request-meta.ts:19-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L19-L27) During request execution, the invocation path passes through specific middleware handling routines. In `handleCatchallMiddlewareRequest()`, the server checks whether the request has an active middleware invocation flag. When middleware is absent or routing matchers evaluate to false, `handleFinished()` is invoked. Inside `handleFinished()`, the call chain invokes `addRequestMeta(req, 'middlewareInvoke', true)` to record the completed state, which in turn calls `getRequestMeta()` to read the existing metadata dictionary before setting the key. The full call sequence is `handleCatchallMiddlewareRequest` → `handleFinished` → `addRequestMeta` → `getRequestMeta`. Sources: [packages/next/src/server/next-server.ts:1943-2053](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L2053), [packages/next/src/server/request-meta.ts:421-429](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L421-L429), [packages/next/src/server/request-meta.ts:393-399](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L393-L399) ```mermaid sequenceDiagram participant NextNodeServer as next-server.ts participant RequestMeta as request-meta.ts NextNodeServer->>NextNodeServer: handleCatchallMiddlewareRequest() NextNodeServer->>NextNodeServer: handleFinished() NextNodeServer->>RequestMeta: addRequestMeta() RequestMeta->>RequestMeta: getRequestMeta() ``` Sources: [packages/next/src/server/next-server.ts:1943-2053](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts#L1943-L2053), [packages/next/src/server/request-meta.ts:421-429](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L421-L429), [packages/next/src/server/request-meta.ts:393-399](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L393-L399) ### Metadata Fields and Structure The `RequestMeta` interface maintains state regarding routing decisions, incremental caching layers, locale negotiation, and development diagnostics. | Field | Type | Purpose | | :--- | :--- | :--- | | `initQuery` | `ParsedUrlQuery` | The initial query string parameters used to make the request. | | `initURL` | `string` | The full request URL string captured at entry. | | `initProtocol` | `string` | The protocol scheme (`http` or `https`) associated with the request. | | `clonableBody` | `CloneableBody` | Multi-readable request body stream wrapper. | | `isLocaleDomain` | `boolean` | True when the request matches a configured locale domain. | | `didStripLocale` | `boolean` | True when locale information was stripped from the URL pathname. | | `rewrittenPathname` | `string` | The target pathname if the request URL underwent a rewrite. | | `middlewareCookie` | `string[]` | Cookies added by middleware to be appended to the response. | | `match` | `RouteMatch` | The resolved route match object for the current pathname. | | `incrementalCache` | `IncrementalCache` | The incremental cache provider instance assigned to the request. | | `serverComponentsHmrCache` | `ServerComponentsHmrCache` | Development-only HMR cache for server components. | | `hmrRefreshHash` | `string` | Hash of the latest server component change used in `"use cache"` keys. | | `segmentPrefetchRSCRequest` | `string` | Target segment path for prefetch RSC requests. | | `isPrefetchRSCRequest` | `true` | True when the request fetches prefetch flight data. | | `isRSCRequest` | `true` | True when the request fetches React Server Component flight data. | | `cacheBustingSearchParam` | `string` | Search param hash verifying custom headers to prevent cache poisoning on CDNs. | | `isNextDataReq` | `true` | True when requesting `/_next/data` via the Pages Router. | | `postponed` | `string` | Postponed PPR state string used for resumption rendering. | | `actionBody` | `Buffer` | Action payload extracted from server action requests. | | `onCacheEntry` | `OnCacheEntryHandler` | Deprecated callback invoked on response cache hits or generations. | | `onCacheEntryV2` | `OnCacheEntryHandler` | Callback invoked when a response cache entry is generated or retrieved. | | `notFoundRevalidate` | `number \| false` | Revalidation interval prior to rendering a 404 page for `notFound: true`. | | `developmentNotFoundSourcePage` | `string` | Original source page returning a 404 during development. | | `invokePath` | `string` | Internal routing invocation path. | | `invokeOutput` | `string` | Specific page output target for matching. | | `invokeStatus` | `number` | Status code passed during internal routing invocation. | | `invokeError` | `Error` | Routing error object associated with an invocation. | | `invokeQuery` | `Record` | Parsed query parameters for internal routing invocations. | | `middlewareInvoke` | `boolean` | Flag indicating whether the request is a middleware invocation. | | `renderFallbackShell` | `boolean` | True if the server should render the fallback shell. | | `resolvedRouteParamKeys` | `Set` | Route parameter keys explicitly resolved from partial query parameters. | | `customErrorRender` | `true` | True when rendering the custom application error page. | | `bubbleNoFallback` | `true` | Bubble `NoFallbackError` to the caller when a 404 occurs. | | `localeInferredFromDefault` | `true` | True when the locale was inferred from the default configuration. | | `locale` | `string` | The active locale set or inferred for the request. | | `defaultLocale` | `string` | The default locale configured for the application. | | `relativeProjectDir` | `string` | Relative path of the project directory from the root. | | `distDir` | `string` | Build output distribution directory. | | `hostname` | `string` | Hostname used by route handlers for absolute URL construction. | | `revalidate` | `RevalidateFn` | Internal revalidation function bypassing network calls. | | `render404` | `Function` | Callback rendering the Pages Router 404 page. | | `query` | `ParsedUrlQuery` | Resolved query parameters after route matching. | | `params` | `ParsedUrlQuery` | Resolved dynamic route parameters after route matching. | | `PagesErrorDebug` | `PagesDevOverlayBridgeType` | Error overlay component bridge for the Pages Router in development. | | `minimalMode` | `boolean` | True when running the server in minimal resource mode. | | `stagedFallbackParams` | `OpaqueFallbackRouteParams` | Route params deferred until after the static stage in PPR. | | `fallbackRouteParams` | `OpaqueFallbackRouteParams` | Route params substituted with opaque placeholders during shell debugging. | | `devParamMatchingRejected` | `boolean` | Development flag indicating parameter matching rejection. | | `devNotFoundParams` | `readonly string[]` | Closed parameters including allowed values in development. | | `devRequestTimingStart` | `bigint` | Request start timestamp in nanoseconds via `process.hrtime.bigint()`. | | `devRequestTimingMiddlewareStart` | `bigint` | Middleware execution start timestamp in development. | | `devRequestTimingMiddlewareEnd` | `bigint` | Middleware execution completion timestamp in development. | | `devRequestTimingInternalsEnd` | `bigint` | Internal processing completion timestamp in development. | | `devGenerateStaticParamsDuration` | `bigint` | Duration of `getStaticPaths` or `generateStaticParams` execution. | | `devServerActionLog` | `object` | Server action execution logs captured in development. | Sources: [packages/next/src/server/request-meta.ts:51-375](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L51-L375) > [!NOTE] > The `NEXT_REQUEST_META` symbol allows mutable request attributes to persist across framework boundaries, including Node.js `IncomingMessage`, custom `BaseNextRequest` wrappers, and Web `NextRequest` abstractions, preventing metadata loss during internal request forwarding and middleware runs. Sources: [packages/next/src/server/request-meta.ts:18-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L18-L27) ## Route Resolution and Header Rewriting ### Path Matching and Internationalization Incoming HTTP requests undergo initial route resolution through `resolveRoutes`, which evaluates request URLs, normalizes `_next/data` requests when `shouldNormalizeNextData` is enabled, and applies internationalization (i18n) locale detection. When i18n is configured and the request does not target `_next` or `api` paths, the system inspects cookies, accept-language headers, pathnames, and domain configuration. ```typescript // Handle i18n locale detection and redirects if (i18n && !isDataUrl) { const pathname = currentUrl.pathname.startsWith(basePath) ? currentUrl.pathname.slice(basePath.length) || '/' : currentUrl.pathname // Skip locale handling for _next and api routes if (!pathname.startsWith('/_next/') && !pathname.startsWith('/api/')) { const hostname = currentUrl.hostname const cookieHeader = currentRequestHeaders.get('cookie') || undefined const acceptLanguageHeader = currentRequestHeaders.get('accept-language') || undefined // Detect locale from path first const pathLocaleResult = normalizeLocalePath(pathname, i18n.locales) const localeInPath = !!pathLocaleResult.detectedLocale // Detect domain locale const domainLocale = detectDomainLocale(i18n.domains, hostname) const defaultLocale = domainLocale?.defaultLocale || i18n.defaultLocale // Determine target locale if locale detection is enabled let targetLocale = pathLocaleResult.detectedLocale || defaultLocale // Match Next.js behavior: preferred-locale auto-detection redirects only // on index requests, not on arbitrary non-locale pathnames. const shouldDetectPreferredLocale = i18n.localeDetection !== false && !localeInPath && pathLocaleResult.pathname === '/' if (shouldDetectPreferredLocale) { const detectedResult = detectLocale({ pathname, hostname, cookieHeader, acceptLanguageHeader, i18n, }) targetLocale = detectedResult.locale ``` Sources: [packages/next-routing/src/resolve-routes.ts:602-643](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-routing/src/resolve-routes.ts#L602-L643) If preferred-locale auto-detection triggers on root index requests without an explicit path locale, the request redirects to the detected locale or domain. Otherwise, the locale is prefixed internally for route resolution without triggering an HTTP redirect. > [!TIP] > Preferred-locale auto-detection is restricted strictly to root index requests (`pathLocaleResult.pathname === '/'`) when no explicit locale exists in the path, preventing unexpected redirects on nested application routes. Sources: [packages/next-routing/src/resolve-routes.ts:628-632](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-routing/src/resolve-routes.ts#L628-L632) ### Middleware Execution and Header Overrides After processing `beforeMiddleware` rules, the routing engine evaluates whether the request matches any middleware matchers. If matched, middleware is invoked, and any resulting headers, redirects, or rewrites are applied to the request and response objects. ```typescript const middlewareHeaders = toNodeOutgoingHttpHeaders( middlewareRes.headers ) as Record debug('middleware res', middlewareRes.status, middlewareHeaders) if (middlewareHeaders['x-middleware-override-headers']) { const overriddenHeaders: Set = new Set() let overrideHeaders: string | string[] = middlewareHeaders['x-middleware-override-headers'] if (typeof overrideHeaders === 'string') { overrideHeaders = overrideHeaders.split(',') } for (const key of overrideHeaders) { overriddenHeaders.add(key.trim()) } delete middlewareHeaders['x-middleware-override-headers'] // Delete headers. for (const key of Object.keys(req.headers)) { if (!overriddenHeaders.has(key)) { delete req.headers[key] } } // Update or add headers. for (const key of overriddenHeaders.keys()) { const valueKey = 'x-middleware-request-' + key const newValue = middlewareHeaders[valueKey] const oldValue = req.headers[key] if (oldValue !== newValue) { req.headers[key] = newValue === null ? undefined : newValue } delete middlewareHeaders[valueKey] } } ``` Sources: [packages/next/src/server/lib/router-utils/resolve-routes.ts:662-700](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-utils/resolve-routes.ts#L662-L700) When middleware returns `x-middleware-override-headers`, the server parses the specified header names, strips unlisted incoming request headers, and applies new values prefixed with `x-middleware-request-`. Headers explicitly blocked by `ipcForbiddenHeaders` or control keys such as `content-length`, `x-middleware-rewrite`, `x-middleware-redirect`, and `x-middleware-refresh` are filtered out or handled specially. > [!CAUTION] > The `x-middleware-set-cookie` header is assigned directly to request headers (`req.headers['x-middleware-set-cookie'] = value`) rather than copied to response headers, ensuring cookies passed from middleware persist for downstream request processing. Sources: [packages/next/src/server/lib/router-utils/resolve-routes.ts:725-730](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-utils/resolve-routes.ts#L725-L730) ### Dynamic Routes and Condition Evaluation Once file system checks and `beforeFiles` rewrites complete, dynamic routes are scanned against pathnames and query conditions using `has` and `missing` parameters. ```typescript for (const route of routes.dynamicRoutes) { const match = matchDynamicRoute(currentUrl.pathname, route, caseSensitive) if (!match.matched) { continue } const hasResult = checkHasConditions( route.has, currentUrl, currentRequestHeaders ) const missingMatched = checkMissingConditions( route.missing, currentUrl, currentRequestHeaders ) if (!hasResult.matched || !missingMatched) { continue } ``` Sources: [packages/next-routing/src/resolve-routes.ts:881-901](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-routing/src/resolve-routes.ts#L881-L901) If a dynamic route matches both pattern criteria and validation conditions, its destination is resolved via query merging and matched headers from `routes.onMatch` are appended to the response context. ## Path Normalization and Manifest Mapping ### App Router Normalizers The [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) utilizes specialized normalizers to transform route strings and filenames into canonical bundle paths. The `AppBundlePathNormalizer` extends `PrefixingNormalizer` with an `'app'` prefix, applying `normalizePagePath` to convert pages into their normalized pathname representations. Sources: [packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts:7-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts#L7-L15) In development mode, `DevAppBundlePathNormalizer` orchestrates a composite normalizer chain via `Normalizers`. It combines the incoming page normalizer and an `AppBundlePathNormalizer`, conditionally prepending an `UnderscoreNormalizer` when Turbopack is active to handle `%5F` to `_` replacements. Sources: [packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts:17-31](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts#L17-L31) > [!NOTE] > The `%5F` to `_` underscore replacement in bundle paths is restricted strictly to Turbopack compilation runs within `DevAppBundlePathNormalizer`. Sources: [packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts:26-29](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts#L26-L29) ### Pages Router Normalizers For the legacy Pages Router, `PagesBundlePathNormalizer` wraps `normalizePagePath` to strip trailing `/index` segments from bundle paths before passing them through a `PrefixingNormalizer` initialized with the `'pages'` prefix. Sources: [packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts:7-16](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts#L7-L16) The corresponding development variant, `DevPagesBundlePathNormalizer`, composes the pages-specific normalizer with a runtime page normalizer to translate filenames into target route paths during on-demand compilation. Sources: [packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts:23-31](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts#L23-L31) | Normalizer Class | Base Class / Wrapper | Prefix / Target | Core Operation | | :--- | :--- | :--- | :--- | | `AppBundlePathNormalizer` | `PrefixingNormalizer` | `'app'` | Normalizes page paths via `normalizePagePath` and prefixes with `'app'` | | `DevAppBundlePathNormalizer` | `Normalizers` | `'app'` (+ optional `UnderscoreNormalizer`) | Combines page normalizer, app normalizer, and conditional Turbopack underscore normalization | | `PagesBundlePathNormalizer` | `Normalizers` | `'pages'` | Strips trailing `/index` via `normalizePagePath` and prefixes with `'pages'` | | `DevPagesBundlePathNormalizer` | `Normalizers` | `'pages'` | Chains pages file normalizer with `PagesBundlePathNormalizer` | Sources: [packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts:7-31](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/app/app-bundle-path-normalizer.ts#L7-L31), [packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts:7-31](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/normalizers/built/pages/pages-bundle-path-normalizer.ts#L7-L31) ## App Page Runtime Execution Pipeline ### Runtime Template Invocation and Handler Initialization The App Page runtime execution pipeline begins when incoming requests are processed by generated runtime templates such as `packages/next/src/build/templates/app-page-runtime.ts` and Edge SSR templates like `packages/next/src/build/templates/edge-ssr-app.ts`. The main `handler` function extracts request metadata, normalizes source paths via `normalizeAppPath`, and parses dynamic route segment parameter names from the route pattern. Sources: [packages/next/src/build/templates/app-page-runtime.ts:206-222](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L206-L222) ```typescript async function handler( req: IncomingMessage, res: ServerResponse, ctx: { waitUntil?: (prom: Promise) => void requestMeta?: RequestMeta } ) { if (ctx.requestMeta) { setRequestMeta(req, ctx.requestMeta) } ``` Sources: [packages/next/src/build/templates/app-page-runtime.ts:215-225](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L215-L225) Requests are prepared via `routeModule.prepare`, evaluating multi-zone draft mode configuration and returning a comprehensive context object containing build manifests, router contexts, query parameters, and configuration properties. Sources: [packages/next/src/build/templates/app-page-runtime.ts:245-280](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L245-L280) > [!WARNING] > Failing to capture `req.url` into `httpTarget` before `routeModule.prepare` runs will cause subsequent CDN URL rewrites to corrupt trace span attributes. Sources: [packages/next/src/build/templates/app-page-runtime.ts:236-241](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L236-L241) ### PPR Resumption and Server Actions Handling When Partial Prerendering (PPR) is enabled via `nextConfig.cacheComponents`, incoming requests accompanied by postponed resume state headers undergo body size and limit validations. If `NEXT_RESUME_STATE_LENGTH_HEADER` is present alongside a server action request, the runtime reads the request body with a combined size budget comprising the state length and action body limit. Sources: [packages/next/src/build/templates/app-page-runtime.ts:349-390](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L349-L390) ```typescript const resumeStateLengthHeader = req.headers[NEXT_RESUME_STATE_LENGTH_HEADER] if ( !getRequestMeta(req, 'postponed') && isMinimalMode && couldSupportPPR && isPossibleServerAction && resumeStateLengthHeader && typeof resumeStateLengthHeader === 'string' ) { const stateLength = parseInt(resumeStateLengthHeader, 10) const { maxPostponedStateSize, maxPostponedStateSizeBytes } = getMaxPostponedStateSize(nextConfig.experimental.maxPostponedStateSize) if (!isNaN(stateLength) && stateLength > 0) { if (stateLength > maxPostponedStateSizeBytes) { res.statusCode = 413 res.end(getPostponedStateExceededErrorMessage(maxPostponedStateSize)) ctx.waitUntil?.(Promise.resolve()) return null } ``` Sources: [packages/next/src/build/templates/app-page-runtime.ts:353-372](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L353-L372) The raw request buffer is subdivided into the postponed state string—stored in request metadata under `'postponed'`—and the remaining action body payload destined for the server action handler. Sources: [packages/next/src/build/templates/app-page-runtime.ts:403-411](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L403-L411) ### Route Invocation and Edge SSR Adapters Route modules execute rendering operations by wrapping Node request and response objects into `NodeNextRequest` and `NodeNextResponse` adapters, dispatching either `routeModule.prerender` or `routeModule.render` depending on the active render operation. Sources: [packages/next/src/build/templates/app-page-runtime.ts:777-789](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L777-L789) ```typescript const invokeRouteModule = async ( span: Span | undefined, context: AppPageRouteHandlerContext, renderOperation: AppPageRenderOperation ) => { const nextReq = new NodeNextRequest(req) const nextRes = new NodeNextResponse(res) const result = renderOperation === 'prerender' ? routeModule.prerender(nextReq, nextRes, context) : routeModule.render(nextReq, nextRes, context) return result.finally(() => { ``` Sources: [packages/next/src/build/templates/app-page-runtime.ts:777-790](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L777-L790) In Edge SSR runtime templates, `renderResultToResponse` converts render outcomes into standard Web `Response` instances, setting appropriate `x-edge-runtime` headers, mapping fetch metrics, and piping dynamic readable streams via `TransformStream`. Sources: [packages/next/src/build/templates/edge-ssr-app.ts:250-328](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts#L250-L328) | Operation Context | Target Parameter / Header | Default / Fallback Value | Purpose | | :--- | :--- | :--- | :--- | | Action Body Limit | `nextConfig.experimental.serverActions?.bodySizeLimit` | `'1 MB'` (1024 * 1024 bytes) | Bounded payload size check for server action requests | | Postponed State Size | `nextConfig.experimental.maxPostponedStateSize` | Platform default limits | Validates incoming PPR postponed state length against configuration | | Response Content-Type | `result.contentType` | `'text/html; charset=utf-8'` | Establishes mime type for Edge SSR responses | | Edge Runtime Header | `'x-edge-runtime'` | `'1'` | Identifies responses originating from the V8 edge sandbox | Sources: [packages/next/src/build/templates/app-page-runtime.ts:378-387](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L378-L387), [packages/next/src/build/templates/edge-ssr-app.ts:272-274](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts#L272-L274) ## Pages API Template Request Processing ### Request Preparation and Route Module Initialization The legacy Pages API handler initializes by accepting incoming `IncomingMessage` and `ServerResponse` objects alongside a context object containing optional `waitUntil` and `requestMeta` properties. If `requestMeta` is provided, it is attached to the request, and development timing metrics are recorded if `routeModule.isDev` is active. For Turbopack environments, dynamic route page paths ending in `/index` are normalized to ensure correct path matching. Sources: [packages/next/src/build/templates/pages-api.ts:47-68](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L47-L68) ```typescript const prepareResult = await routeModule.prepare(req, res, { srcPage }) if (!prepareResult) { res.statusCode = 400 res.end('Bad Request') ctx.waitUntil?.(Promise.resolve()) return } ``` Sources: [packages/next/src/build/templates/pages-api.ts:70-77](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L70-L77) > [!WARNING] > If `routeModule.prepare` returns a falsy result, the response status code is immediately set to `400` with a `"Bad Request"` body, short-circuiting execution before any userland route module rendering occurs. Sources: [packages/next/src/build/templates/pages-api.ts:72-77](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L72-L77) ### Tracing Context and Route Execution When preparation succeeds, the request method and active OpenTelemetry tracer are retrieved to establish distributed tracing spans. Depending on whether the server wraps the request, the handler either uses an existing active span or initiates a new `BaseServerSpan.handleRequest` trace with server span kinds and route attributes. Sources: [packages/next/src/build/templates/pages-api.ts:79-92](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L79-L92), [packages/next/src/build/templates/pages-api.ts:172-196](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L172-L196) ```typescript const invokeRouteModule = async (span?: Span) => routeModule .render(req, res, { query: { ...query, ...params, }, params, allowedRevalidateHeaderKeys: process.env .__NEXT_ALLOWED_REVALIDATE_HEADERS as any as string[], multiZoneDraftMode: Boolean(process.env.__NEXT_MULTI_ZONE_DRAFT_MODE), trustHostHeader: process.env .__NEXT_TRUST_HOST_HEADER as any as boolean, // TODO: get this from from runtime env so manifest // doesn't need to load previewProps, propagateError: false, dev: routeModule.isDev, page: 'VAR_DEFINITION_PAGE', internalRevalidate: routerServerContext?.revalidate, onError: (...args: Parameters) => onRequestError(req, ...args), }) ``` Sources: [packages/next/src/build/templates/pages-api.ts:93-117](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L93-L117) Spans are finalized via `.finally()` hooks that inspect `res.statusCode`. Status codes of `500` or greater trigger `SpanStatusCode.ERROR` along with `error.type` attributes. Root span attributes are verified to match `BaseServerSpan.handleRequest` before updating trace span names with HTTP methods and matched route paths. Sources: [packages/next/src/build/templates/pages-api.ts:118-170](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L118-L170) ### Error Boundary Traps and Response Delivery Uncaught exceptions thrown during route module invocation are intercepted by a catch block. In development mode, errors are re-thrown directly to trigger the error overlay. In production environments, an internal server error is dispatched using `sendError`, serving a `500` status response. Sources: [packages/next/src/build/templates/pages-api.ts:197-205](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L197-L205) ```typescript } finally { // We don't allow any waitUntil work in pages API routes currently // so if callback is present return with resolved promise since no // pending work ctx.waitUntil?.(Promise.resolve()) } ``` Sources: [packages/next/src/build/templates/pages-api.ts:205-210](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L205-L210) > [!NOTE] > Pages API routes do not currently permit asynchronous background work via `waitUntil`, so the `finally` block immediately resolves any pending `waitUntil` promise callbacks. Sources: [packages/next/src/build/templates/pages-api.ts:206-210](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L206-L210) ## Response Payload Dispatch and Caching ### ETag Validation and Caching Headers The payload dispatch pipeline verifies response state and sets caching and metadata headers before outputting content. If a response has already been sent, execution returns immediately. When `poweredByHeader` is enabled and the response content type matches the HTML content type header, the `X-Powered-By: Next.js` header is assigned. Sources: [packages/next/src/server/send-payload.ts:35-56](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L35-L56) ```typescript // If cache control is already set on the response we don't // override it to allow users to customize it via next.config if (cacheControl && !res.getHeader('Cache-Control')) { res.setHeader('Cache-Control', getCacheControlHeader(cacheControl)) } const payload = result.isDynamic ? null : result.toUnchunkedString() if (generateEtags && payload !== null) { const etag = generateETag(payload) if (sendEtagResponse(req, res, etag)) { return } } ``` Sources: [packages/next/src/server/send-payload.ts:58-71](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L58-L71) Cache control headers are populated using `getCacheControlHeader` if not already present, preserving user customizations set via `next.config`. For unchunked static payloads, ETags are generated and evaluated via `sendEtagResponse`. If the request headers match the generated ETag using `fresh`, status `304` is assigned, the connection is ended, and dispatch terminates early. Sources: [packages/next/src/server/send-payload.ts:11-33](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L11-L33), [packages/next/src/server/send-payload.ts:58-71](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L58-L71) > [!WARNING] > When generating a `304` Not Modified response, the server sets required validation headers such as `ETag` per RFC 7232 before ending the response without a body. Sources: [packages/next/src/server/send-payload.ts:16-24](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L16-L24) ### Payload Streaming and Node Response Piping ```typescript if (!res.getHeader('Content-Type') && result.contentType) { res.setHeader('Content-Type', result.contentType) } if (payload) { res.setHeader('Content-Length', Buffer.byteLength(payload)) } if (req.method === 'HEAD') { res.end(null) return } if (payload !== null) { res.end(payload) return } // Pipe the render result to the response after we get a writer for it. await result.pipeToNodeResponse(res) ``` Sources: [packages/next/src/server/send-payload.ts:73-92](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L73-L92) Content type and content length headers are registered for non-empty payloads. If the incoming method is `HEAD`, the body is omitted and the response is terminated. Unchunked string payloads are dispatched directly via `res.end(payload)`, whereas dynamic streaming results are piped to the underlying Node response using `result.pipeToNodeResponse(res)`. Sources: [packages/next/src/server/send-payload.ts:73-92](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/send-payload.ts#L73-L92) ## Related - [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) - [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) - [Pages Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/pages-rendering) --- ## Technical docs: Route Handlers URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/route-modules/app-route/module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts) - [packages/next/src/build/templates/app-route.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts) - [packages/next/src/build/templates/app-page-runtime.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts) - [packages/next/src/server/app-render/action-handler.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/action-handler.ts) - [packages/next/src/build/templates/pages-api.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts) - [packages/next/src/server/route-modules/pages/pages-handler.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/pages-handler.ts) - [packages/next/src/build/templates/edge-ssr-app.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/src/server/web/edge-route-module-wrapper.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts) - [packages/next/src/server/api-utils/node/api-resolver.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/node/api-resolver.ts) - [packages/next/src/build/templates/edge-app-route.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-app-route.ts) - [packages/next/src/server/dev/next-dev-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/next-dev-server.ts) - [packages/next/src/server/lib/router-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/router-server.ts) - [packages/next/src/server/web/adapter.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts) - [packages/next/src/build/templates/edge-ssr.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts) - [packages/next/src/server/route-modules/pages-api/module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages-api/module.ts) - [packages/next/src/server/api-utils/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/index.ts) - [packages/next/src/server/route-modules/app-page/module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.ts) - [packages/next/src/server/lib/patch-set-header.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/patch-set-header.ts) - [packages/next/src/server/request-meta.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts) - [packages/next/src/server/route-modules/route-module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts) - [packages/next/src/server/web/get-edge-preview-props.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/get-edge-preview-props.ts)
## Overview Route Handlers provide a unified mechanism for executing custom server-side request handlers and API endpoints within Next.js, bridging both the [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) (via `AppRouteRouteModule`) and the Pages API router (via `PagesAPIRouteModule`). By building upon the foundational `RouteModule` class, route handlers establish a consistent architecture for environment initialization, manifest loading, error reporting, and request preparation across diverse runtimes. Sources: [packages/next/src/server/route-modules/app-route/module.ts:10-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts#L10-L15), [packages/next/src/server/route-modules/pages-api/module.ts:8-10](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages-api/module.ts#L8-L10), [packages/next/src/server/route-modules/route-module.ts:119-164](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L119-L164) ## Route Module Base Architecture ### Execution Walkthrough and Sequence The abstract `RouteModule` class serves as the core foundation for all Next.js route handlers, providing a shared environment initialization, manifest loading, error reporting, and request preparation pipeline. During initialization, the constructor accepts `RouteModuleOptions` containing the `definition`, `userland` module, `distDir`, and `relativeProjectDir`, setting up the canonical `cacheOwner` via `getResponseCacheOwner(definition)` and detecting the development runtime mode through `process.env.__NEXT_DEV_SERVER`. Sources: [packages/next/src/server/route-modules/route-module.ts:89-164](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L89-L164) When a request arrives at a route, the execution flows through the entry point template handler and initializes through the base class. The invocation sequence executes in the following call order: `handler` → `prepare` → `prepareImpl` → `patchSetHeaderWithCookieSupport` → `getRequestMeta`. 1. `handler`: The template entry function receives the incoming request and response objects, attaches request metadata if provided, and invokes `routeModule.prepare()`. Sources: [packages/next/src/build/templates/app-route.ts:106-137](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts#L106-L137) 2. `prepare`: Traces the preparation span using the tracer utility and delegates the execution to `prepareImpl()`. Sources: [packages/next/src/server/route-modules/route-module.ts:635-648](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L635-L648) 3. `prepareImpl`: Evaluates runtime environment conditions, patches headers, resolves absolute project directories, loads route manifests, normalizes URLs, handles localization, and processes rewrites and dynamic route parameters. Sources: [packages/next/src/server/route-modules/route-module.ts:650-735](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L650-L735) 4. `patchSetHeaderWithCookieSupport`: Wraps the response `setHeader` method to intercept `set-cookie` headers, ensuring middleware cookies are properly merged rather than overridden by downstream handlers. Sources: [packages/next/src/server/lib/patch-set-header.ts:18-65](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/patch-set-header.ts#L18-L65), [packages/next/src/server/route-modules/route-module.ts:707-710](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L707-L710) 5. `getRequestMeta`: Retrieves internal request metadata properties such as `middlewareCookie`, `relativeProjectDir`, and `distDir` from the request symbol storage. Sources: [packages/next/src/server/request-meta.ts:385-399](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L385-L399), [packages/next/src/server/lib/patch-set-header.ts:43-43](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/patch-set-header.ts#L43-L43) ```mermaid sequenceDiagram participant AppRoute as app-route.ts participant RouteModule as route-module.ts participant PatchHeader as patch-set-header.ts participant RequestMeta as request-meta.ts AppRoute->>RouteModule: handler() calls prepare() RouteModule->>RouteModule: prepare() traces and calls prepareImpl() RouteModule->>PatchHeader: prepareImpl() calls patchSetHeaderWithCookieSupport(req, res) PatchHeader->>RequestMeta: patchSetHeaderWithCookieSupport checks getRequestMeta(req, 'middlewareCookie') ``` Sources: [packages/next/src/build/templates/app-route.ts:134-137](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts#L134-L137), [packages/next/src/server/route-modules/route-module.ts:635-648](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L635-L648), [packages/next/src/server/route-modules/route-module.ts:707-710](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L707-L710), [packages/next/src/server/lib/patch-set-header.ts:18-43](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/patch-set-header.ts#L18-L43), [packages/next/src/server/request-meta.ts:385-399](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request-meta.ts#L385-L399) > [!NOTE] > During header patching, `patchSetHeaderWithCookieSupport` intercepts calls to `res.setHeader`. When the header name matches `set-cookie`, it pulls any pending cookies set by middleware via `getRequestMeta(req, 'middlewareCookie')` and combines them with unique entries to prevent downstream overwrites. Sources: [packages/next/src/server/lib/patch-set-header.ts:32-62](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/patch-set-header.ts#L32-L62) ## App Route Module Execution ### Dynamic Dispatch and HTTP Method Resolution Incoming requests to an app route undergo preparation via `prepareExecution`, which ensures the userland module is fully loaded through `this.ensureUserland()`. In Turbopack development mode, the module resolver fetches the live userland module on each request via `this._getUserland?.()` to reflect immediate HMR updates, falling back to cached modules if top-level await yields a pending promise. The target HTTP method is inspected against the loaded userland module using `this.resolveHandlerFromUserland(req.method, liveUserland)` or `this.resolveHandler(req.method)`. Sources: [packages/next/src/server/route-modules/app-route/module.ts:851-874](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts#L851-L874) ```mermaid sequenceDiagram participant NextReq as NextRequest participant AppRouteMod as AppRouteRouteModule participant Userland as Userland Module NextReq->>AppRouteMod: prepareExecution(req, context) AppRouteMod->>AppRouteMod: ensureUserland() AppRouteMod->>Userland: _getUserland() (Turbopack live module) AppRouteMod->>AppRouteMod: resolveHandlerFromUserland(req.method, liveUserland) AppRouteMod-->>NextReq: Returns PreparedAppRouteExecution ``` Sources: [packages/next/src/server/route-modules/app-route/module.ts:851-913](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts#L851-L913) ### Execution Lifecycle and Dynamic Behavior Modes Once prepared, `executeRequest` runs the handler within asynchronous storage scopes (`actionAsyncStorage`, `workUnitAsyncStorage`, and `workAsyncStorage`). The request object is wrapped or proxied depending on the route's [dynamic rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering) configuration. | Dynamic Mode | Store Property Mutated | Request Modification | | :--- | :--- | :--- | | `force-dynamic` | `workStore.forceDynamic = true` | None (Standard `NextRequest`) | | `force-static` | `workStore.forceStatic = true` | `new Proxy(req, forceStaticRequestHandlers)` | | `error` | `workStore.dynamicShouldError = true` | None (Standard `NextRequest`) | | `auto` / `undefined` | None | `proxyNextRequest(req, workStore)` | Sources: [packages/next/src/server/route-modules/app-route/module.ts:939-972](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts#L939-L972) > [!WARNING] > If a route handler returns an object that is not an instance of the global `Response` class, `validateExecutionResponse` catches it and immediately returns a fallback HTTP 500 internal error response. Furthermore, headers containing `x-middleware-rewrite` or `x-middleware-next` set to `'1'` throw explicit runtime errors because middleware-specific response directives are unsupported inside app route handlers. Sources: [packages/next/src/server/route-modules/app-route/module.ts:915-937](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts#L915-L937) ## Node App Route Invocation ### Request Normalization and Manifest Caching When an app route is invoked via the Node runtime template, the request enters the exported `handler` function where request metadata is attached and page paths are normalized. Specifically, Turbopack and Webpack route paths ending with `/index` or mapped via multi-zone draft modes are adjusted before invoking `routeModule.prepare(req, res, { srcPage, multiZoneDraftMode })`. This preparation method executes inside a tracing span using `RouteModuleSpan.prepare`, wrapping an internal call to `prepareImpl` which handles directory resolution, cookie patch support, and instrumentation registration. Sources: [packages/next/src/build/templates/app-route.ts:106-137](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts#L106-L137), [packages/next/src/server/route-modules/route-module.ts:635-648](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L635-L648), [packages/next/src/server/route-modules/route-module.ts:707-735](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L707-L735) ```mermaid sequenceDiagram participant Handler as handler (app-route.ts) participant Prepare as prepare (route-module.ts) participant PrepareImpl as prepareImpl (route-module.ts) participant LoadManifests as loadManifests (route-module.ts) participant EdgePreview as getEdgePreviewProps / maybeJSONParse Handler->>Prepare: routeModule.prepare(req, res, options) Prepare->>PrepareImpl: RouteModuleSpan.prepare trace scope PrepareImpl->>LoadManifests: RouteModuleSpan.loadManifests trace scope LoadManifests->>EdgePreview: getEdgePreviewProps() (Edge) or loadManifestFromRelativePath (Node) EdgePreview-->>LoadManifests: parsed manifests & preview props LoadManifests-->>PrepareImpl: manifests object PrepareImpl-->>Prepare: prepareResult context Prepare-->>Handler: resolved parameters & configuration ``` Sources: [packages/next/src/build/templates/app-route.ts:134-161](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts#L134-L161), [packages/next/src/server/route-modules/route-module.ts:254-256](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L254-L256), [packages/next/src/server/route-modules/route-module.ts:635-648](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L635-L648), [packages/next/src/server/route-modules/route-module.ts:736-741](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L736-L741) Within `prepareImpl`, manifest files are loaded via `loadManifests` under the `RouteModuleSpan.loadManifests` tracer span. Depending on whether the runtime is set to `edge` or `node`, manifests are either parsed from global variables using `maybeJSONParse` or read from disk relative to the project directory. > [!NOTE] > In the [edge runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime), preview properties are retrieved via `getEdgePreviewProps()`, which extracts configuration directly from `process.env.__NEXT_PREVIEW_MODE_ID`, `process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY`, and `process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY`. Sources: [packages/next/src/server/route-modules/route-module.ts:254-274](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L254-L274), [packages/next/src/server/route-modules/route-module.ts:736-741](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L736-L741), [packages/next/src/server/web/get-edge-preview-props.ts:6-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/get-edge-preview-props.ts#L6-L12) ### Response Wrapping and Execution Flow Once preparation yields a valid configuration, `handler` initializes the [incremental cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) and sets up global singletons for [server actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions) and client reference manifests if present. Standard Node `IncomingMessage` and `ServerResponse` instances are adapted into `NodeNextRequest`, `NodeNextResponse`, and standard Web `NextRequest` objects via `NextRequestAdapter.fromNodeNextRequest`. Sources: [packages/next/src/build/templates/app-route.ts:139-278](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts#L139-L278) | Manifest Category | Node Runtime Source / Method | Edge Runtime Source / Fallback | | :--- | :--- | :--- | | **Routes Manifest** | `loadManifestFromRelativePath(ROUTES_MANIFEST)` | `process.env.__NEXT_REWRITES` / defaults | | **Prerender Manifest** | `loadManifestFromRelativePath(PRERENDER_MANIFEST)` | Static empty routes object | | **Client Reference** | `evalManifestFromRelativePath(...)` | `self.__RSC_MANIFEST?.[srcPage]` | | **Server Actions** | `loadManifestFromRelativePath(SERVER_REFERENCE_MANIFEST)` | `maybeJSONParse(self.__RSC_SERVER_MANIFEST)` | Sources: [packages/next/src/server/route-modules/route-module.ts:275-306](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L275-L306), [packages/next/src/server/route-modules/route-module.ts:337-404](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts#L337-L404) > [!WARNING] > If `prepare` returns a falsy result, the handler immediately terminates execution by setting the response status code to `400`, writing `'Bad Request'`, resolving any pending `waitUntil` promises, and returning `null`. Sources: [packages/next/src/build/templates/app-route.ts:139-144](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts#L139-L144) ## Edge Route Module Adapter ### Streaming and Response Lifecycle The edge runtime integration wraps route modules via `EdgeRouteModuleWrapper`, bridging standard Web Request/Response types and Next.js internal execution contexts. When an edge app route is invoked, userland configuration and environmental settings such as `__NEXT_BASE_PATH`, `__NEXT_I18N_CONFIG`, and `__NEXT_TRAILING_SLASH` are supplied to the internal adapter handler. ```typescript export async function handler( request: Request, ctx: { waitUntil?: (prom: Promise) => void signal?: AbortSignal requestMeta?: RequestMeta } ): Promise { const result = await internalHandler({ request: { url: request.url, method: request.method, headers: toNodeOutgoingHttpHeaders(request.headers), nextConfig: { basePath: process.env.__NEXT_BASE_PATH, i18n: process.env.__NEXT_I18N_CONFIG as any, trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH), experimental: { cacheLife: process.env.__NEXT_CACHE_LIFE as any, authInterrupts: Boolean( process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS ), clientParamParsingOrigins: process.env .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any, }, }, page: { name: 'VAR_PAGE', }, body: request.method !== 'GET' && request.method !== 'HEAD' ? (request.body ?? undefined) : undefined, waitUntil: ctx.waitUntil, requestMeta: ctx.requestMeta, signal: ctx.signal || new AbortController().signal, }, }) ctx.waitUntil?.(result.waitUntil) return result.response } ``` Sources: [packages/next/src/build/templates/edge-app-route.ts:42-84](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-app-route.ts#L42-L84) Within `EdgeRouteModuleWrapper.handler`, dynamic route parameters are normalized from search parameters, cache handlers are initialized with configuration limits, and preview properties are retrieved via `getEdgePreviewProps`. ```typescript export function getEdgePreviewProps() { return { previewModeId: process.env.__NEXT_PREVIEW_MODE_ID || '', previewModeSigningKey: process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY || '', previewModeEncryptionKey: process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY || '', } ``` Sources: [packages/next/src/server/web/get-edge-preview-props.ts:6-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/get-edge-preview-props.ts#L6-L12) | Environment Variable | Source Property / Fallback | Purpose in Edge Context | | :--- | :--- | :--- | | `__NEXT_PREVIEW_MODE_ID` | `process.env.__NEXT_PREVIEW_MODE_ID` | Identifies active draft/preview mode sessions | | `__NEXT_PREVIEW_MODE_SIGNING_KEY` | `process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY` | Cryptographic signature validation for cookies | | `__NEXT_PREVIEW_MODE_ENCRYPTION_KEY` | `process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY` | Payload encryption for preview cookies | Sources: [packages/next/src/server/web/get-edge-preview-props.ts:6-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/get-edge-preview-props.ts#L6-L12) > [!NOTE] > In the edge runtime, preview props are directly read from runtime environment variables injected by the edge-runtime or replaced during the edge [build pipeline](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/build-pipeline). Sources: [packages/next/src/server/web/get-edge-preview-props.ts:1-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/get-edge-preview-props.ts#L1-L5) When handling responses, the wrapper manages asynchronous execution tasks and body streaming lifecycles. If a response body is absent, a deferred close controller timeout dispatches a close event. For streaming responses, `trackStreamConsumed` wraps the response body to guarantee close handlers execute correctly upon consumption. ```typescript if (!res.body) { // we can delay running it until a bit later -- // if it's needed, we'll have a `waitUntil` lock anyway. setTimeout(() => closeController.dispatchClose(), 0) } else { // NOTE: if this is a streaming response, onClose may be called later, // so we can't rely on `closeController.listeners` -- it might be 0 at this point. const trackedBody = trackStreamConsumed(res.body, () => closeController.dispatchClose() ) res = new Response(trackedBody, { status: res.status, statusText: res.statusText, headers: res.headers, }) } return res } ``` Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:158-176](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L158-L176) > [!WARNING] > Because streaming responses can invoke `onClose` at a later time, listeners cannot be tracked by a static count; `trackStreamConsumed` monitors body stream consumption to trigger `closeController.dispatchClose()`. Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:162-167](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L162-L167) ## Pages API Route Resolution ### Pages API Module Wrapper and Template The `PagesAPIRouteModule` class manages execution for legacy Pages API routes. Upon instantiation, it validates that `options.userland.default` is a function and wraps the underlying `apiResolver` function using `wrapApiHandler` to assign the route name to root span attributes and trace execution under `NodeSpan.runHandler`. ```typescript constructor(options: PagesAPIRouteModuleOptions) { super(options) if (typeof options.userland.default !== 'function') { throw new Error( `Page ${options.definition.page} does not export a default function.` ) } this.apiResolverWrapped = wrapApiHandler( options.definition.page, apiResolver ) } ``` Sources: [packages/next/src/server/route-modules/pages-api/module.ts:115-128](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages-api/module.ts#L115-L128) The generated `pages-api` template exports the userland handler and config via hoisting, and executes a request handler function that attaches request metadata, handles Turbopack page normalization for `/index` routes, and calls `routeModule.prepare(req, res, { srcPage })`. ```typescript export default hoist(userland, 'default') // Re-export config. export const config = hoist(userland, 'config') // Create and export the route module that will be consumed. const routeModule = new PagesAPIRouteModule({ definition: { kind: RouteKind.PAGES_API, page: 'VAR_DEFINITION_PAGE', pathname: 'VAR_DEFINITION_PATHNAME', // The following aren't used in production. bundlePath: '', filename: '', }, userland, distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', }) export async function handler( req: IncomingMessage, res: ServerResponse, ctx: { waitUntil?: (prom: Promise) => void requestMeta?: RequestMeta } ) { if (ctx.requestMeta) { setRequestMeta(req, ctx.requestMeta) } if (routeModule.isDev) { addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint()) } let srcPage = 'VAR_DEFINITION_PAGE' // turbopack doesn't normalize `/index` in the page name // so we need to to process dynamic routes properly // TODO: fix turbopack providing differing value from webpack if (process.env.TURBOPACK) { srcPage = srcPage.replace(/\/index$/, '') || '/' } const prepareResult = await routeModule.prepare(req, res, { srcPage }) ``` Sources: [packages/next/src/build/templates/pages-api.ts:27-70](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L27-L70) > [!WARNING] > If `routeModule.prepare` returns a falsy result, the template immediately responds with a `400 Bad Request` status and terminates execution. Sources: [packages/next/src/build/templates/pages-api.ts:70-77](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts#L70-L77) ### Node.js apiResolver Pipeline and Configuration The `apiResolver` function orchestrates request parsing and execution. It reads the page configuration from `resolverModule.config`, extracting configuration properties that dictate body parsing behavior, response size limits, and external resolver status. ```typescript const config: PageConfig = resolverModule.config || {} const bodyParser = config.api?.bodyParser !== false const responseLimit = config.api?.responseLimit ?? true const externalResolver = config.api?.externalResolver || false ``` Sources: [packages/next/src/server/api-utils/node/api-resolver.ts:351-355](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/node/api-resolver.ts#L351-L355) | PageConfig API Property | Default Value / Evaluation | Description | | :--- | :--- | :--- | | `config.api.bodyParser` | `true` (enabled unless explicitly `false` or object with `false`) | Determines whether to parse the incoming request body. | | `config.api.responseLimit` | `true` (defaults to `RESPONSE_LIMIT_DEFAULT` bytes) | Enforces response content length limits and warns on overflow. | | `config.api.externalResolver` | `false` | Disables unhandled resolution warnings for external routing middleware. | Sources: [packages/next/src/server/api-utils/node/api-resolver.ts:352-354](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/node/api-resolver.ts#L352-L354), [packages/next/src/server/api-utils/index.ts:114-114](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/index.ts#L114-L114) > [!NOTE] > `apiResolver` uses `setLazyProp` to lazily parse cookies, query parameters, preview data, and draft mode state on `req` only when accessed. Sources: [packages/next/src/server/api-utils/node/api-resolver.ts:356-375](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/node/api-resolver.ts#L356-L375) ### Body Parsing and Response Helpers When `bodyParser` is enabled and `apiReq.body` is not already populated, `apiResolver` invokes `parseBody` with the configured size limit, defaulting to `'1mb'`. ```typescript // Parsing of body if (bodyParser && !apiReq.body) { apiReq.body = await parseBody( apiReq, config.api && config.api.bodyParser && config.api.bodyParser.sizeLimit ? config.api.bodyParser.sizeLimit : '1mb' ) } ``` Sources: [packages/next/src/server/api-utils/node/api-resolver.ts:377-385](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/node/api-resolver.ts#L377-L385) Response methods and helpers are monkey-patched or attached directly onto `apiRes` during resolution to provide utility methods. | Response Helper Method | Implementation Target | Purpose | | :--- | :--- | :--- | | `res.status(statusCode)` | `sendStatusCode` | Sets response status code and returns response object. | | `res.send(data)` | `sendData` | Sends payload data back to the client. | | `res.json(data)` | `sendJson` | Serializes and sends JSON data. | | `res.redirect(statusOrUrl, url)` | `redirect` | Writes redirection headers and terminates request. | | `res.setDraftMode(options)` | `setDraftMode` | Configures draft mode state cookies. | | `res.setPreviewData(data, options)` | `setPreviewData` | Sets preview data cookies. | | `res.clearPreviewData(options)` | `clearPreviewData` | Clears preview cookies using expiration dates in the past. | | `res.revalidate(urlPath, opts)` | `revalidate` | Triggers on-demand revalidation for a path. | Sources: [packages/next/src/server/api-utils/node/api-resolver.ts:410-426](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/node/api-resolver.ts#L410-L426), [packages/next/src/server/api-utils/index.ts:44-76](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/index.ts#L44-L76), [packages/next/src/server/api-utils/index.ts:119-164](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/api-utils/index.ts#L119-L164) ## Related - [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) - [Request Lifecycle](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/request-lifecycle) - [Edge Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime) --- ## Technical docs: Edge Runtime URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/web/sandbox/sandbox.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts) - [packages/next/src/build/templates/edge-ssr.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts) - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/src/build/templates/edge-ssr-app.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts) - [packages/next/src/build/templates/edge-app-route.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-app-route.ts) - [packages/next/src/server/web/sandbox/context.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts) - [packages/next/src/server/web/adapter.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts) - [packages/next/src/build/templates/middleware.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/middleware.ts) - [packages/next/src/build/templates/app-route.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-route.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/server/dev/next-dev-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/next-dev-server.ts) - [packages/next/src/build/webpack/plugins/middleware-plugin.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/middleware-plugin.ts) - [packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts) - [packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts) - [packages/next/src/build/templates/pages-edge-api.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-edge-api.ts) - [packages/next/src/server/web/edge-route-module-wrapper.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts) - [packages/next/src/build/templates/pages-api.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages-api.ts) - [packages/next/src/server/route-modules/route-module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts) - [packages/next/src/build/templates/edge-wrapper.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-wrapper.js) - [packages/next/src/build/webpack/loaders/next-edge-function-loader.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts) - [packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts) - [packages/next/src/server/web/internal-edge-wait-until.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/internal-edge-wait-until.ts) - [packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts) - [packages/next/src/server/web/globals.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/globals.ts) - [packages/next/src/server/route-modules/pages-api/module.compiled.js](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages-api/module.compiled.js) - [packages/next/src/server/web/spec-extension/request.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/request.ts) - [packages/next/src/server/web/spec-extension/response.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/response.ts)
## Overview The Edge Runtime powers Next.js middleware, edge API routes, and edge-rendered App and Pages router components by executing userland code in a lightweight, web-standard V8 sandbox. Built on top of the `edge-runtime` package, the edge architecture establishes a secure global environment with process polyfills, stubs for unsupported Node.js APIs, and specialized [Webpack loaders](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/webpack-loaders) that package entrypoints and dependency manifests. Incoming HTTP requests and asynchronous fetch event lifecycles are normalized across the adapter layer, while bridge wrappers connect edge route modules to execution handlers, streaming responses, and `waitUntil` background task primitives. Sources: [packages/next/src/server/web/sandbox/sandbox.ts:1-44](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts#L1-L44), [packages/next/src/server/web/sandbox/context.ts:259-282](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts#L259-L282), [packages/next/src/build/webpack/plugins/middleware-plugin.ts:44-74](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/middleware-plugin.ts#L44-L74), [packages/next/src/server/web/adapter.ts:259-278](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts#L259-L278), [packages/next/src/server/web/edge-route-module-wrapper.ts:35-81](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L35-L81) ## Edge Compilation and Manifest Packaging ### Webpack Loaders for Edge Entrypoints Next.js orchestrates the compilation and packaging of Edge Runtime components through specialized Webpack loaders and the `MiddlewarePlugin`. These components transform userland modules, collect module build metadata, manage asset and WebAssembly bindings, and emit the `middleware.json` manifest version 3. Edge compilation relies on dedicated loaders that attach build information to webpack modules via `getModuleBuildInfo`. The `EdgeAppRouteLoader` processes [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) routes and page paths, configuring cache handlers and route metadata. Similarly, `edgeSSRLoader` handles Pages and App router Server-Side Rendering (SSR) entrypoints, swapping standard folder paths for their ESM equivalents (`next/dist/esm/pages`) to optimize tree-shaking and bundle sizing. | Loader Name | Source File | Key Responsibilities | | :--- | :--- | :--- | | `EdgeAppRouteLoader` | `packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts` | Configures `nextEdgeSSR` build info, parses base64 middleware configurations, and sets up cache handlers for App Router route modules. | | `edgeSSRLoader` | `packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts` | Resolves absolute paths for documents, error boundaries, and 500 pages while mapping dist folders to ESM variants. | | `nextEdgeFunctionLoader` | `packages/next/src/build/webpack/loaders/next-edge-function-loader.ts` | Injects global web polyfills, wraps page handlers using `wrapApiHandler`, and exports an adapter instance for Edge API routes. | | `MiddlewareWasmLoader` | `packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts` | Computes a SHA-1 hash of binary WebAssembly files, emits chunks into `server/edge-chunks/`, and exposes module bindings. | | `MiddlewareAssetLoader` | `packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts` | Interpolates asset names with hashes, emits files to `server/edge-chunks/`, and exports a blob URL identifier string. | Sources: [packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts:57-117](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts#L57-L117), [packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts:104-228](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts#L104-L228), [packages/next/src/build/webpack/loaders/next-edge-function-loader.ts:15-71](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts#L15-L71), [packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts:8-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts#L8-L15), [packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts:4-17](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-middleware-asset-loader.ts#L4-L17) ```typescript export default function MiddlewareWasmLoader(this: any, source: Buffer) { const name = `wasm_${sha1(source)}` const filePath = `edge-chunks/${name}.wasm` const buildInfo = getModuleBuildInfo(this._module) buildInfo.nextWasmMiddlewareBinding = { filePath: `server/${filePath}`, name } this.emitFile(`/${filePath}`, source, null) return `module.exports = ${name};` } ``` Sources: [packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts:8-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-middleware-wasm-loader.ts#L8-L15) ### MiddlewarePlugin Manifest Generation The `MiddlewarePlugin` compiles execution metadata across all entrypoints to construct version 3 of the `MiddlewareManifest`. This manifest tracks sorted middleware patterns alongside defined middleware functions and edge SSR entrypoints, mapping each entrypoint to its generated file dependencies, environment variables, WebAssembly bindings, asset bindings, and target execution regions. ```typescript export interface EdgeFunctionDefinition { files: string[] name: string page: string entrypoint: string matchers: ProxyMatcher[] env: Record wasm?: AssetBinding[] assets?: AssetBinding[] regions?: string[] | string } export interface MiddlewareManifest { version: 3 sortedMiddleware: string[] middleware: { [page: string]: EdgeFunctionDefinition } functions: { [page: string]: EdgeFunctionDefinition } } ``` Sources: [packages/next/src/build/webpack/plugins/middleware-plugin.ts:44-64](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/middleware-plugin.ts#L44-L64) > [!NOTE] > `MiddlewarePlugin` extracts file dependencies using `getEntryFiles`, which differentiates between server components requiring client reference manifests and standard edge functions, ensuring that Subresource Integrity (SRI) and dynamic CSS manifests are correctly bundled for edge SSR targets. Sources: [packages/next/src/build/webpack/plugins/middleware-plugin.ts:105-158](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/middleware-plugin.ts#L105-L158) ## Global Environment and Runtime Polyfills ### Environment Bootstrapping and Global Enhancement When the runtime initialization checks `process.env.NEXT_RUNTIME === 'edge'`, `enhanceGlobals` sets up the global environment. It synchronizes `process.env` with `global.process.env` and overwrites `global.process` to point to the sandboxed process instance. It also defines `__import_unsupported` on `globalThis` as a non-enumerable, non-configurable property. This helper returns a proxy that throws an error when property access, construction, or function invocation occurs on un-supported Node.js modules, enabling codebases to import modules that are unused at runtime without failing build checks. Additionally, it eagerly triggers `ensureInstrumentationRegistered` to initialize telemetry or instrumentation hooks. ```typescript function getUnsupportedModuleErrorMessage(module: string) { // warning: if you change these messages, you must adjust how dev-overlay's middleware detects modules not found return `The edge runtime does not support Node.js '${module}' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime` } function __import_unsupported(moduleName: string) { const proxy: any = new Proxy(function () {}, { get(_obj, prop) { if (prop === 'then') { return {} } throw new Error(getUnsupportedModuleErrorMessage(moduleName)) }, construct() { throw new Error(getUnsupportedModuleErrorMessage(moduleName)) }, apply(_target, _this, args) { if (typeof args[0] === 'function') { return args[0](proxy) } throw new Error(getUnsupportedModuleErrorMessage(moduleName)) }, }) return new Proxy({}, { get: () => proxy }) } function enhanceGlobals() { if (process.env.NEXT_RUNTIME !== 'edge') { return } // The condition is true when the "process" module is provided if (process !== global.process) { // prefer local process but global.process has correct "env" process.env = global.process.env global.process = process } // to allow building code that import but does not use node.js modules, // webpack will expect this function to exist in global scope try { Object.defineProperty(globalThis, '__import_unsupported', { value: __import_unsupported, enumerable: false, configurable: false, }) } catch {} // Eagerly fire instrumentation hook to make the startup faster. void ensureInstrumentationRegistered() } ``` Sources: [packages/next/src/server/web/globals.ts:57-108](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/globals.ts#L57-L108) > [!WARNING] > Accessing any property or calling a function on an unsupported Node.js module proxy created by `__import_unsupported` immediately throws an error stating that the edge runtime does not support that module. Sources: [packages/next/src/server/web/globals.ts:57-82](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/globals.ts#L57-L82) ### Runtime Context Extension and Node API Stubs The module context creation function initializes an `EdgeRuntime` instance with code generation flags enabled when `process.env.NODE_ENV !== 'production'`. Through its `extend` hook, it attaches process polyfills, custom `require` implementations via `NativeModuleMap`, timers (`setInterval`, `clearInterval`, `setTimeout`, `clearTimeout`), performance hooks, and `AsyncLocalStorage`. It iterates over `EDGE_UNSUPPORTED_NODE_APIS` to add stubs for missing Node modules and attaches custom handlers for dynamic code evaluation warnings. ```typescript const runtime = new EdgeRuntime({ codeGeneration: process.env.NODE_ENV !== 'production' ? { strings: true, wasm: true } : undefined, extend: (context) => { context.process = createProcessPolyfill(edgeFunctionEntry.env) Object.defineProperty(context, 'require', { enumerable: false, value: (id: string) => { const value = NativeModuleMap.get(id) if (!value) { throw TypeError('Native module not found: ' + id) } return value }, }) if (process.env.NODE_ENV !== 'production') { context.__next_log_error__ = function (err: unknown) { options.onError(err) } } context.__next_eval__ = function __next_eval__(fn: Function) { const key = fn.toString() if (!warnedEvals.has(key)) { const warning = getServerError( new Error( `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation` ), COMPILER_NAMES.edgeServer ) warning.name = 'DynamicCodeEvaluationWarning' Error.captureStackTrace(warning, __next_eval__) warnedEvals.add(key) options.onWarning(warning) } return fn() } context.__next_webassembly_compile__ = function __next_webassembly_compile__(fn: Function) { const key = fn.toString() if (!warnedWasmCodegens.has(key)) { const warning = getServerError( new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime. Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), COMPILER_NAMES.edgeServer ) warning.name = 'DynamicWasmCodeGenerationWarning' Error.captureStackTrace(warning, __next_webassembly_compile__) warnedWasmCodegens.add(key) options.onWarning(warning) } return fn() } context.__next_webassembly_instantiate__ = async function __next_webassembly_instantiate__(fn: Function) { const result = await fn() // If a buffer is given, WebAssembly.instantiate returns an object // containing both a module and an instance while it returns only an // instance if a WASM module is given. Utilize the fact to determine // if the WASM code generation happens. // // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code const instantiatedFromBuffer = result.hasOwnProperty('module') const key = fn.toString() if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) { const warning = getServerError( new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime. Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), COMPILER_NAMES.edgeServer ) warning.name = 'DynamicWasmCodeGenerationWarning' ``` Sources: [packages/next/src/server/web/sandbox/context.ts:264-464](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts#L264-L464) > [!NOTE] > Invoking `eval` or `new Function` triggers `__next_eval__`, which checks a `warnedEvals` set to emit a `DynamicCodeEvaluationWarning` once per unique function string in non-production environments. Sources: [packages/next/src/server/web/sandbox/context.ts:289-305](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts#L289-L305) ## Development Sandbox Execution and Isolation ### Module Context Creation and Global Injection The `createModuleContext` function constructs an isolated `EdgeRuntime` environment for local development. It loads WebAssembly binaries from the edge function entry and configures code generation flags based on environment conditions. Within the runtime extension hook, it provisions custom globals including process polyfills, native module resolution via `NativeModuleMap`, timers, performance monitoring, and an overridden `fetch` implementation capable of resolving inline assets. It also intercepts `Request` constructor calls and `Response.redirect` to validate target URLs. ```typescript async function createModuleContext(options: ModuleContextOptions) { const warnedEvals = new Set() const warnedWasmCodegens = new Set() const { edgeFunctionEntry } = options const wasm = await loadWasm(edgeFunctionEntry.wasm ?? []) const runtime = new EdgeRuntime({ codeGeneration: process.env.NODE_ENV !== 'production' ? { strings: true, wasm: true } : undefined, extend: (context) => { context.process = createProcessPolyfill(edgeFunctionEntry.env) Object.defineProperty(context, 'require', { enumerable: false, value: (id: string) => { const value = NativeModuleMap.get(id) if (!value) { throw TypeError('Native module not found: ' + id) } return value }, }) if (process.env.NODE_ENV !== 'production') { context.__next_log_error__ = function (err: unknown) { options.onError(err) } } context.__next_eval__ = function __next_eval__(fn: Function) { const key = fn.toString() if (!warnedEvals.has(key)) { const warning = getServerError( new Error( `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation` ), COMPILER_NAMES.edgeServer ) warning.name = 'DynamicCodeEvaluationWarning' Error.captureStackTrace(warning, __next_eval__) warnedEvals.add(key) options.onWarning(warning) } return fn() } context.__next_webassembly_compile__ = function __next_webassembly_compile__(fn: Function) { const key = fn.toString() if (!warnedWasmCodegens.has(key)) { const warning = getServerError( new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime. Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), COMPILER_NAMES.edgeServer ) warning.name = 'DynamicWasmCodeGenerationWarning' Error.captureStackTrace(warning, __next_webassembly_compile__) warnedWasmCodegens.add(key) options.onWarning(warning) } return fn() } context.__next_webassembly_instantiate__ = async function __next_webassembly_instantiate__(fn: Function) { const result = await fn() // If a buffer is given, WebAssembly.instantiate returns an object // containing both a module and an instance while it returns only an // instance if a WASM module is given. Utilize the fact to determine // if the WASM code generation happens. // // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code const instantiatedFromBuffer = result.hasOwnProperty('module') const key = fn.toString() if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) { const warning = getServerError( ``` Sources: [packages/next/src/server/web/sandbox/context.ts:259-399](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts#L259-L399) > [!WARNING] > Attempting to instantiate WebAssembly modules from a buffer via `WebAssembly.instantiate` triggers `__next_webassembly_instantiate__`, emitting a `DynamicWasmCodeGenerationWarning` when detected outside precompiled modules. Sources: [packages/next/src/server/web/sandbox/context.ts:324-349](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts#L324-L349) ### Runtime Context Evaluation and Runner Execution The `getRuntimeContext` function initializes module contexts and injects shared global singletons into the sandbox `globalThis` object. These injections support incremental caching, router server contexts, server component HMR caching, and client asset tokens. Once injected, it evaluates all provided path entries within the context. ```typescript export async function getRuntimeContext( params: Omit ): Promise> { const { runtime, evaluateInContext } = await getModuleContext({ moduleName: params.name, onWarning: params.onWarning ?? (() => {}), onError: params.onError ?? (() => {}), useCache: params.useCache !== false, edgeFunctionEntry: params.edgeFunctionEntry, distDir: params.distDir, }) if (params.incrementalCache) { runtime.context.globalThis.__incrementalCacheShared = true runtime.context.globalThis.__incrementalCache = params.incrementalCache } // expose router server context for access to dev handlers like // logErrorWithOriginalStack ;(runtime.context.globalThis as any as typeof routerServerGlobal)[ RouterServerContextSymbol ] = routerServerGlobal[RouterServerContextSymbol] if (params.serverComponentsHmrCache) { runtime.context.globalThis.__serverComponentsHmrCache = params.serverComponentsHmrCache } if (params.clientAssetToken) { runtime.context.globalThis.NEXT_CLIENT_ASSET_SUFFIX = params.clientAssetToken ? `?dpl=${params.clientAssetToken}` : '' } for (const paramPath of params.paths) { evaluateInContext(paramPath) } return runtime } ``` Sources: [packages/next/src/server/web/sandbox/sandbox.ts:72-109](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts#L72-L109) The `run` function executes the compiled edge function handler within wrapped `AsyncLocalStorage` request stores and custom request contexts. It clones request bodies for non-GET/HEAD methods, builds standard headers while filtering forbidden headers, and finalizes request body streams upon completion. ```typescript export const run = withTaggedErrors(async function runWithTaggedErrors(params) { const runtime = await getRuntimeContext(params) const edgeFunction: EdgeHandler = ( await runtime.context._ENTRIES[`middleware_${params.name}`] ).default const cloned = !['HEAD', 'GET'].includes(params.request.method) ? params.request.body?.cloneBodyStream() : undefined const KUint8Array = runtime.evaluate('Uint8Array') const urlInstance = new URL(params.request.url) params.request.url = urlInstance.toString() const headers = new Headers() for (const [key, value] of Object.entries(params.request.headers)) { headers.set(key, value?.toString() ?? '') } try { let result: FetchEventResult | undefined = undefined const builtinRequestCtx: BuiltinRequestContextValue = { ...getBuiltinRequestContext(), // FIXME(after): // arguably, this is an abuse of "@next/request-context" -- // it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`) // but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not. waitUntil: params.request.waitUntil, } await edgeSandboxNextRequestContext.run(builtinRequestCtx, () => requestStore.run({ headers }, async () => { result = await edgeFunction({ request: { ...params.request, body: cloned && requestToBodyStream(runtime.context, KUint8Array, cloned), }, }) for (const headerName of FORBIDDEN_HEADERS) { result.response.headers.delete(headerName) } }) ) if (!result) throw new Error('Edge function did not return a response') return result } finally { await params.request.body?.finalize() } }) ``` Sources: [packages/next/src/server/web/sandbox/sandbox.ts:111-163](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts#L111-L163) > [!NOTE] > `FORBIDDEN_HEADERS` containing `content-length`, `content-encoding`, and `transfer-encoding` are unconditionally deleted from the resulting response headers before dispatch. Sources: [packages/next/src/server/web/sandbox/sandbox.ts:23-27](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts#L23-L27), [packages/next/src/server/web/sandbox/sandbox.ts:152-154](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts#L152-L154) ### Error Tagging and Unhandled Event Handling In development mode, `withTaggedErrors` decorates runner executions by passing caught errors and unhandled `waitUntil` rejections through `getServerError` with an `'edge-server'` compiler tag, enabling original stack frames to be resolved and displayed correctly in development overlays. ```typescript function withTaggedErrors(fn: RunnerFn): RunnerFn { if (process.env.NODE_ENV === 'development') { const { getServerError } = require('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames') return (params) => fn(params) .then((result) => ({ ...result, waitUntil: result?.waitUntil?.catch((error) => { // TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size. throw getServerError(error, 'edge-server') }), })) .catch((error) => { // TODO: used COMPILER_NAMES.edgeServer instead throw getServerError(error, 'edge-server') }) } return fn } ``` Sources: [packages/next/src/server/web/sandbox/sandbox.ts:49-70](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/sandbox.ts#L49-L70) Additionally, the runtime context binds event listeners for unhandled errors and rejections, using `getDecorateUnhandledError` and `getDecorateUnhandledRejection` to ensure runtime exceptions bubble up safely into the parent Node.js process with proper stack decorations. ```typescript const decorateUnhandledError = getDecorateUnhandledError(runtime) runtime.context.addEventListener('error', decorateUnhandledError) const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime) runtime.context.addEventListener( 'unhandledrejection', decorateUnhandledRejection ) ``` Sources: [packages/next/src/server/web/sandbox/context.ts:467-474](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/sandbox/context.ts#L467-L474) ## Edge Web Adapter Architecture ### Request and Response Extensions The adapter architecture bridges incoming Node.js requests and standard Web APIs through `NextRequest` and `NextResponse`, which extend the standard `Request` and `Response` interfaces with specialized Next.js behaviors. `NextRequest` parses incoming headers into structured `RequestCookies` via its internal symbol store and constructs a `NextURL` instance that handles internationalization, base paths, and query string normalization. When bodies are present in non-edge runtimes, `NextRequest` automatically sets the request duplex mode to `'half'`. ```typescript export class NextRequest extends Request { /** @internal */ [INTERNALS]: { cookies: RequestCookies url: string nextUrl: NextURL } constructor(input: URL | RequestInfo, init: RequestInit = {}) { const url = typeof input !== 'string' && 'url' in input ? input.url : String(input) validateURL(url) // node Request instance requires duplex option when a body // is present or it errors, we don't handle this for // Request being passed in since it would have already // errored if this wasn't configured if (process.env.NEXT_RUNTIME !== 'edge') { if (init.body && init.duplex !== 'half') { init.duplex = 'half' } } if (input instanceof Request) super(input, init) else super(url, init) const nextUrl = new NextURL(url, { headers: toNodeOutgoingHttpHeaders(this.headers), nextConfig: init.nextConfig, }) this[INTERNALS] = { cookies: new RequestCookies(this.headers), nextUrl, url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url : nextUrl.toString(), } } ``` Sources: [packages/next/src/server/web/spec-extension/request.ts:14-52](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/request.ts#L14-L52) `NextResponse` wraps response cookies with a proxy that intercepts `.set()` and `.delete()` calls to automatically serialize cookie values and synchronize them into the `'x-middleware-set-cookie'` header. It also exposes static helper methods for creating specialized responses, such as `NextResponse.json`, `NextResponse.redirect`, `NextResponse.rewrite`, and `NextResponse.next`. | Static Method | Default Status / Header | Description | | --- | --- | --- | | `NextResponse.json` | Standard JSON init | Instantiates a response wrapping a JSON body | | `NextResponse.redirect` | Status `307` (validates `301`, `302`, `303`, `307`, `308`) | Sets the `Location` header to the validated target URL | | `NextResponse.rewrite` | Header `x-middleware-rewrite` | Sets the rewrite destination and handles middleware request overrides | | `NextResponse.next` | Header `x-middleware-next: '1'` | Instructs the router to continue to the next middleware or route | ```typescript export class NextResponse extends Response { [INTERNALS]: { cookies: ResponseCookies url?: NextURL body?: Body } constructor(body?: BodyInit | null, init: ResponseInit = {}) { super(body, init) const headers = this.headers const cookies = new ResponseCookies(headers) const cookiesProxy = new Proxy(cookies, { get(target, prop, receiver) { switch (prop) { case 'delete': case 'set': { return (...args: [string, string]) => { const result = Reflect.apply(target[prop], target, args) const newHeaders = new Headers(headers) if (result instanceof ResponseCookies) { headers.set( 'x-middleware-set-cookie', result .getAll() .map((cookie) => stringifyCookie(cookie)) .join(',') ) } handleMiddlewareField(init, newHeaders) return result } } default: return ReflectAdapter.get(target, prop, receiver) } }, }) this[INTERNALS] = { cookies: cookiesProxy, url: init.url ? new NextURL(init.url, { headers: toNodeOutgoingHttpHeaders(headers), nextConfig: init.nextConfig, }) : undefined, } } [Symbol.for('edge-runtime.inspect.custom')]() { return { cookies: this.cookies, url: this.url, // rest of props come from Response body: this.body, bodyUsed: this.bodyUsed, headers: Object.fromEntries(this.headers), ok: this.ok, redirected: this.redirected, status: this.status, statusText: this.statusText, type: this.type, } } public get cookies() { return this[INTERNALS].cookies } static json( body: JsonBody, init?: ResponseInit ): NextResponse { const response: Response = Response.json(body, init) return new NextResponse(response.body, response) } ``` Sources: [packages/next/src/server/web/spec-extension/response.ts:36-153](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/response.ts#L36-L153) > [!WARNING] > Passing an invalid HTTP status code to `NextResponse.redirect` that is absent from the `REDIRECTS` set (`301`, `302`, `303`, `307`, `308`) throws a synchronous `RangeError`. Sources: [packages/next/src/server/web/spec-extension/response.ts:10-10](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/response.ts#L10-L10), [packages/next/src/server/web/spec-extension/response.ts:118-123](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/response.ts#L118-L123) ### FetchEvent and WaitUntil Lifecycle The adapter manages background task continuation using `NextFetchEvent` and internal waitUntil tracking. The `internal_runWithWaitUntil` function intercepts asynchronous promises passed to the runtime, incrementing a global `waitUntilCounter` and provisioning a shared `waitUntilPromise` that only resolves when all concurrent background operations complete. ```typescript export function internal_getCurrentFunctionWaitUntil() { return state.waitUntilPromise } export function internal_runWithWaitUntil(fn: () => T): T { const result = fn() if ( result && typeof result === 'object' && 'then' in result && 'finally' in result && typeof result.then === 'function' && typeof result.finally === 'function' ) { if (!state.waitUntilCounter) { // Create the promise for the next batch of waitUntil calls. state.waitUntilPromise = new Promise((resolve) => { state.waitUntilResolve = resolve }) } state.waitUntilCounter++ return result.finally(() => { resolveOnePromise() }) } return result ``` Sources: [packages/next/src/server/web/internal-edge-wait-until.ts:32-58](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/internal-edge-wait-until.ts#L32-L58) > [!NOTE] > Regardless of the number of concurrent requests executing in the edge sandbox, `resolveOnePromise` ensures the primary `waitUntilPromise` remains active until `waitUntilCounter` drops exactly to zero. Sources: [packages/next/src/server/web/internal-edge-wait-until.ts:21-30](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/internal-edge-wait-until.ts#L21-L30) During adapter execution, requests identified as middleware (`/middleware`, `/src/middleware`, `/proxy`, `/src/proxy`) are wrapped with execution telemetry via `MiddlewareSpan.execute`. The adapter sets up a `CloseController` to schedule resource cleanup via `setTimeout` upon completion, initializes request and work stores using `createRequestStoreForAPI` and `createWorkStore`, and executes the handler within `workAsyncStorage` and `workUnitAsyncStorage` contexts. ```typescript response = await propagator(request, () => { // we only care to make async storage available for middleware const isMiddleware = params.page === '/middleware' || params.page === '/src/middleware' || params.page === '/proxy' || params.page === '/src/proxy' if (isMiddleware) { // if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`), // so we have to inject it via DefinePlugin. // in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`). const waitUntil = event.waitUntil.bind(event) const closeController = new CloseController() return getTracer().trace( MiddlewareSpan.execute, { spanName: `middleware ${request.method}`, attributes: { 'http.target': request.nextUrl.pathname, 'http.method': request.method, }, }, async () => { try { const onUpdateCookies = (cookies: Array) => { cookiesFromResponse = cookies } const previewProps = getEdgePreviewProps() const page = '/' // Fake Work const fallbackRouteParams = null const implicitTags = await getImplicitTags( page, request.nextUrl.pathname, fallbackRouteParams ) const requestStore = createRequestStoreForAPI( request, request.nextUrl, implicitTags, onUpdateCookies, previewProps, // Edge route handlers can't use `"use cache"`, so there's no HMR // refresh hash to thread through here. undefined ) const workStore = createWorkStore({ page, renderOpts: { cacheLifeProfiles: proxyCacheLifeProfiles, // Proxy doesn't do static generation, so this value does not // apply here. 0 is a sentinel: if something ever reads it, // it'll surface loudly instead of silently using a misleading // default. staticPageGenerationTimeout: 0, cacheComponents: false, // Proxy doesn't run instant validation; the level value is // irrelevant here. // TODO: remove validationLevel and other global config from renderOpts validationLevel: 'warning', experimental: { isRoutePPREnabled: false, authInterrupts: !!params.request.nextConfig?.experimental?.authInterrupts, // Proxy doesn't fill Cache Components entries, so this value // is never read. 0 is a sentinel: if something ever reads it, // the cache fill will time out immediately and surface the // bug. useCacheTimeout: 0, durableUseCacheEntries: false, }, waitUntil, onClose: closeController.onClose.bind(closeController), onAfterTaskError: undefined, }, ``` Sources: [packages/next/src/server/web/adapter.ts:270-377](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts#L270-L377) ## Route Module Edge Wrappers ### Edge Route Module Wrapper Class The `EdgeRouteModuleWrapper` class bridges edge request handlers and App Route modules. Constructed via its static `wrap` method, it accepts an `AppRouteRouteModule` instance along with configuration options like `cacheHandlers` and `incrementalCacheHandler`. The private constructor evaluates whether the route pathname is dynamic using `isDynamicRoute`. ```typescript export class EdgeRouteModuleWrapper { private readonly pageIsDynamic: boolean /** * The constructor is wrapped with private to ensure that it can only be * constructed by the static wrap method. * * @param routeModule the route module to wrap */ private constructor( private readonly routeModule: AppRouteRouteModule, private readonly cacheHandlers: Record ) { this.pageIsDynamic = isDynamicRoute(routeModule.definition.pathname) } ``` Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:35-49](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L35-L49) | Parameter / Property | Type | Description | | --- | --- | --- | | `routeModule` | `AppRouteRouteModule` | The target App Route module being executed | | `cacheHandlers` | `Record` | Custom cache handlers registered for the edge runtime | | `incrementalCacheHandler` | `typeof IncrementalCacheHandler` | Optional [incremental cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) class reference | | `pageIsDynamic` | `boolean` | Indicates if the route definition pathname contains dynamic segments | ```typescript export interface WrapOptions { page: string cacheHandlers?: Record incrementalCacheHandler?: typeof IncrementalCacheHandler } /** * EdgeRouteModuleWrapper is a wrapper around a route module. * * Note that this class should only be used in the edge runtime. */ export class EdgeRouteModuleWrapper { private readonly pageIsDynamic: boolean /** * The constructor is wrapped with private to ensure that it can only be * constructed by the static wrap method. * * @param routeModule the route module to wrap */ private constructor( private readonly routeModule: AppRouteRouteModule, private readonly cacheHandlers: Record ) { this.pageIsDynamic = isDynamicRoute(routeModule.definition.pathname) } ``` Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:24-49](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L24-L49) ### Request Execution and Context Construction When the wrapped handler executes, it initializes server utilities, loads custom cache handlers based on `nextConfig.cacheMaxMemorySize`, and maps dynamic route parameters using `normalizeDynamicRouteParams`. It constructs an `AppRouteRouteHandlerContext` containing route parameters, preview properties, and render options. ```typescript private async handler( request: NextRequestHint, evt: NextFetchEvent ): Promise { const utils = getServerUtils({ pageIsDynamic: this.pageIsDynamic, page: this.routeModule.definition.pathname, basePath: request.nextUrl.basePath, // We don't need the `handleRewrite` util, so can just pass an empty object rewrites: {}, // only used for rewrites, so setting an arbitrary default value here caseSensitive: false, }) const { nextConfig } = this.routeModule.getNextConfigEdge( new WebNextRequest(request) ) initializeCacheHandlers(nextConfig.cacheMaxMemorySize) for (const [kind, cacheHandler] of Object.entries(this.cacheHandlers)) { setCacheHandler(kind, cacheHandler) } const { params } = utils.normalizeDynamicRouteParams( searchParamsToUrlQuery(request.nextUrl.searchParams), false ) const waitUntil = evt.waitUntil.bind(evt) const closeController = new CloseController() const previewProps = getEdgePreviewProps() // Create the context for the handler. This contains the params from the // match (if any). const context: AppRouteRouteHandlerContext = { params, previewProps, renderOpts: { waitUntil, onClose: closeController.onClose.bind(closeController), onAfterTaskError: undefined, cacheComponents: !!process.env.__NEXT_CACHE_COMPONENTS, // Edge runtime doesn't run instant validation; the level value is // irrelevant here. // TODO: Remove validationLevel and other global config from renderOpts validationLevel: 'warning', experimental: { authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS, // Edge runtime doesn't support Cache Components, so this value is // never read. 0 is a sentinel: if something ever reads it, the cache // fill will time out immediately and surface the bug. useCacheTimeout: 0, durableUseCacheEntries: false, }, cacheLifeProfiles: nextConfig.cacheLife, // Edge runtime doesn't do static generation, so this value does not // apply here. 0 is a sentinel: if something ever reads it, it'll // surface loudly instead of silently using a misleading default. staticPageGenerationTimeout: 0, }, sharedContext: { buildId: '', // TODO: Populate this properly. deploymentId: '', // TODO: Populate this properly. }, } ``` Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:83-147](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L83-L147) > [!CAUTION] > In the edge runtime, `staticPageGenerationTimeout` and `useCacheTimeout` are set to sentinel values of `0`. Because edge environments do not support [static generation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/static-generation) or cache components, any accidental read forces an immediate timeout to expose the invalid configuration loudly. Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:129-142](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L129-L142) ### Background Task Handling and Response Tracking After invoking `this.routeModule.handle(request, context)`, the wrapper gathers pending background work by combining `internal_getCurrentFunctionWaitUntil()` and `context.renderOpts.pendingWaitUntil` into `evt.waitUntil()`. If the response lacks a body, a `CloseController` dispatches closure via `setTimeout` with a delay of zero; otherwise, `trackStreamConsumed` wraps the response body to trigger cleanup once consumption finishes. ```typescript // Get the response from the handler. let res = await this.routeModule.handle(request, context) const waitUntilPromises = [internal_getCurrentFunctionWaitUntil()] if (context.renderOpts.pendingWaitUntil) { waitUntilPromises.push(context.renderOpts.pendingWaitUntil) } evt.waitUntil(Promise.all(waitUntilPromises)) if (!res.body) { // we can delay running it until a bit later -- // if it's needed, we'll have a `waitUntil` lock anyway. setTimeout(() => closeController.dispatchClose(), 0) } else { // NOTE: if this is a streaming response, onClose may be called later, // so we can't rely on `closeController.listeners` -- it might be 0 at this point. const trackedBody = trackStreamConsumed(res.body, () => closeController.dispatchClose() ) res = new Response(trackedBody, { status: res.status, statusText: res.statusText, headers: res.headers, }) } return res } ``` Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:149-176](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L149-L176) > [!NOTE] > For streaming responses, `onClose` cannot rely on pre-existing static listener counts because cleanup may be deferred until the stream body is fully read or consumed. Sources: [packages/next/src/server/web/edge-route-module-wrapper.ts:163-167](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/edge-route-module-wrapper.ts#L163-L167) ## Edge SSR and Middleware Templates ### Pages SSR and App SSR Entrypoint Templates Next.js generates dedicated edge entrypoint templates for Server-Side Rendering under both the Pages and App routers. The Pages SSR template (`edge-ssr.ts`) imports global polyfills, the adapter utility, and userland modules including `Document`, `VAR_MODULE_APP`, and `VAR_USERLAND`. It instantiates a Pages route module with `pageRouteModuleOptions`, configures cache handlers using `nextConfig.cacheMaxMemorySize`, and maps responses through `renderResultToResponse`. ```typescript import '../../server/web/globals' import { adapter, type EdgeHandler, type NextRequestHint, } from '../../server/web/adapter' import { IncrementalCache } from '../../server/lib/incremental-cache' import * as cacheHandlers from '../../server/use-cache/handlers' import Document from 'VAR_MODULE_DOCUMENT' import * as appMod from 'VAR_MODULE_APP' import * as userlandPage from 'VAR_USERLAND' import * as userlandErrorPage from 'VAR_MODULE_GLOBAL_ERROR' declare const userland500Page: any declare const incrementalCacheHandler: any // OPTIONAL_IMPORT:* as userland500Page // OPTIONAL_IMPORT:incrementalCacheHandler import RouteModule, { type PagesRouteHandlerContext, } from '../../server/route-modules/pages/module' import { WebNextRequest, WebNextResponse } from '../../server/base-http/web' import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event' import type RenderResult from '../../server/render-result' import type { RenderResultMetadata } from '../../server/render-result' import { getTracer, SpanKind, SpanStatusCode, type Span, } from '../../server/lib/trace/tracer' import { BaseServerSpan } from '../../server/lib/trace/constants' import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants' import type { RequestMeta } from '../../server/request-meta' import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' // injected by the loader afterwards. declare const pageRouteModuleOptions: any declare const errorRouteModuleOptions: any declare const user500RouteModuleOptions: any // INJECT:pageRouteModuleOptions // INJECT:errorRouteModuleOptions // INJECT:user500RouteModuleOptions // INJECT_RAW:cacheHandlerImports const pageMod = { ...userlandPage, routeModule: new RouteModule({ ...pageRouteModuleOptions, components: { App: appMod.default, Document, }, userland: userlandPage, distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', }), } ``` Sources: [packages/next/src/build/templates/edge-ssr.ts:1-60](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts#L1-L60) ```typescript cacheHandlers.initializeCacheHandlers(nextConfig.cacheMaxMemorySize) // INJECT_RAW:cacheHandlerRegistration const renderContext: PagesRouteHandlerContext = { page: srcPage, query, params, sharedContext: { buildId, deploymentId, clientAssetToken, customServer: undefined, }, renderContext: { isFallback: false, isDraftMode: false, developmentNotFoundSourcePage: undefined, }, renderOpts: { params, page: srcPage, supportsDynamicResponse: true, Component: pageMod.Component, ComponentMod: pageMod, pageConfig: pageMod.pageConfig, routeModule: pageMod.routeModule, previewProps, basePath: nextConfig.basePath, assetPrefix: nextConfig.assetPrefix, images: nextConfig.images, optimizeCss: nextConfig.experimental.optimizeCss, nextConfigOutput: nextConfig.output, nextScriptWorkers: nextConfig.experimental.nextScriptWorkers, disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading, domainLocales: nextConfig.i18n?.domains, distDir: '', crossOrigin: nextConfig.crossOrigin ? nextConfig.crossOrigin : undefined, largePageDataBytes: nextConfig.experimental.largePageDataBytes, isExperimentalCompile: nextConfig.experimental.isExperimentalCompile, // `htmlLimitedBots` is passed to server as serialized config in string format experimental: { clientTraceMetadata: nextConfig.experimental.clientTraceMetadata, }, buildManifest, subresourceIntegrityManifest, reactLoadableManifest, dynamicCssManifest, }, } ``` Sources: [packages/next/src/build/templates/edge-ssr.ts:129-182](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr.ts#L129-L182) Similarly, the App SSR template (`edge-ssr-app.ts`) populates the React Server Component (RSC) manifest singletons by reading `self.__RSC_MANIFEST` and `self.__RSC_SERVER_MANIFEST`. It wraps page execution with `AppPageRouteModule`, detects [server actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions) via `getIsPossibleServerAction`, and sets up incremental caching and stream tracking controllers. ```typescript import '../../server/web/globals' import { adapter, type EdgeHandler, type NextRequestHint, } from '../../server/web/adapter' import { IncrementalCache } from '../../server/lib/incremental-cache' import * as pageMod from 'VAR_USERLAND' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' import * as cacheHandlers from '../../server/use-cache/handlers' import { BaseServerSpan } from '../../server/lib/trace/constants' import { getTracer, SpanKind, SpanStatusCode, type Span, } from '../../server/lib/trace/tracer' import { WebNextRequest, WebNextResponse } from '../../server/base-http/web' import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event' import type { AppPageRouteHandlerContext, AppPageRouteModule, DevRenderContext, RouteMatch, } from '../../server/route-modules/app-page/module.compiled' import type { AppPageRenderResultMetadata } from '../../server/render-result' import type RenderResult from '../../server/render-result' import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' import { getBotType } from '../../shared/lib/router/utils/is-bot' import { shouldServeStreamingMetadata } from '../../server/lib/streaming-metadata' import { interopDefault } from '../../lib/interop-default' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { checkIsOnDemandRevalidate } from '../../server/api-utils' import { CloseController } from '../../server/web/web-on-close' import { parseMaxPostponedStateSize } from '../../shared/lib/size-limit' import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' import type { RequestMeta } from '../../server/request-meta' import { createDevRenderContext } from '../../server/route-modules/app-page/dev-render-context' import { parseRequestHeaders, type ParsedRequestHeaders, } from '../../server/route-modules/app-page/parse-request-headers' declare const incrementalCacheHandler: any // OPTIONAL_IMPORT:incrementalCacheHandler // INJECT_RAW:cacheHandlerImports const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined) const rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE'] const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) if (rscManifest && rscServerManifest) { setManifestsSingleton({ page: 'VAR_PAGE', clientReferenceManifest: rscManifest, serverActionsManifest: rscServerManifest, }) } export const ComponentMod = pageMod ``` Sources: [packages/next/src/build/templates/edge-ssr-app.ts:1-64](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts#L1-L64) ```typescript // Initialize the cache handlers interface. cacheHandlers.initializeCacheHandlers(nextConfig.cacheMaxMemorySize) // INJECT_RAW:cacheHandlerRegistration const isPossibleServerAction = getIsPossibleServerAction(req) const userAgent = req.headers.get('User-Agent') || '' const botType = getBotType(userAgent) const { isOnDemandRevalidate } = checkIsOnDemandRevalidate( req.headers, previewProps ) const closeController = new CloseController() const routeMatch: RouteMatch = { resolvedPathname } const dev: DevRenderContext | undefined = createDevRenderContext(baseReq) const renderContextBase: Omit< AppPageRouteHandlerContext, 'parsedRequestHeaders' > = { page: normalizedSrcPage, routeMatch, query, params, dev, sharedContext: { buildId, deploymentId, clientAssetToken, }, ``` Sources: [packages/next/src/build/templates/edge-ssr-app.ts:106-136](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts#L106-L136) > [!WARNING] > In the edge SSR application template, `serverComponentsHmrCancellation` is explicitly set to `false`. Because the edge runtime lacks a Node response-close signal, HMR cancellation is treated as a no-op during development. Sources: [packages/next/src/build/templates/edge-ssr-app.ts:201-204](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/edge-ssr-app.ts#L201-L204) ### Middleware and Edge API Templates The middleware template (`middleware.ts`) and Pages Edge API template (`pages-edge-api.ts`) handle lightweight edge routing and API handlers. The middleware template resolves userland code as either `mod.proxy`, `mod.middleware`, or `mod.default`. It verifies that the export is a function, throwing a `ProxyMissingExportError` if validation fails. ```typescript const mod = { ..._mod } const page: string = 'VAR_DEFINITION_PAGE' const isProxy = page === '/proxy' || page === '/src/proxy' const handlerUserland = (isProxy ? mod.proxy : mod.middleware) || mod.default class ProxyMissingExportError extends Error { constructor(message: string) { super(message) // Stack isn't useful here, remove it considering it spams logs during development. this.stack = '' } } // TODO: This spams logs during development. Find a better way to handle this. // Removing this will spam "fn is not a function" logs which is worse. if (typeof handlerUserland !== 'function') { throw new ProxyMissingExportError( `The ${isProxy ? 'Proxy' : 'Middleware'} file "${page}" must export a function named \`${isProxy ? 'proxy' : 'middleware'}\` or a default function.` ) } ``` Sources: [packages/next/src/build/templates/middleware.ts:17-37](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/middleware.ts#L17-L37) | Export Target | Condition / Check | Error or Fallback Behavior | | --- | --- | --- | | `mod.proxy` | `page === '/proxy' || page === '/src/proxy'` | Falls back to `mod.middleware` or `mod.default` | | `mod.middleware` | Standard middleware path | Required to be a valid function export | | `mod.default` | Fallback export option | Throws `ProxyMissingExportError` if type is not a function | ```typescript const mod = { ..._mod } const page: string = 'VAR_DEFINITION_PAGE' const isProxy = page === '/proxy' || page === '/src/proxy' const handlerUserland = (isProxy ? mod.proxy : mod.middleware) || mod.default class ProxyMissingExportError extends Error { constructor(message: string) { super(message) // Stack isn't useful here, remove it considering it spams logs during development. this.stack = '' } } // TODO: This spams logs during development. Find a better way to handle this. // Removing this will spam "fn is not a function" logs which is worse. if (typeof handlerUserland !== 'function') { throw new ProxyMissingExportError( `The ${isProxy ? 'Proxy' : 'Middleware'} file "${page}" must export a function named \`${isProxy ? 'proxy' : 'middleware'}\` or a default function.` ) } ``` Sources: [packages/next/src/build/templates/middleware.ts:17-37](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/middleware.ts#L17-L37) The `errorHandledHandler` wrapper intercepts runtime failures in middleware or proxy code. During non-production builds, if an error is identified as a router error via `isNextRouterError`, its message is modified to state that the Next.js navigation API is forbidden within middleware or proxy scopes before reporting the error through `edgeInstrumentationOnRequestError`. ```typescript function errorHandledHandler(fn: AdapterOptions['handler']) { return async (...args: Parameters) => { try { return await fn(...args) } catch (err) { // In development, error the navigation API usage in runtime, // since it's not allowed to be used in proxy as it's outside of react component tree. if (process.env.NODE_ENV !== 'production') { if (isNextRouterError(err)) { err.message = `Next.js navigation API is not allowed to be used in ${isProxy ? 'Proxy' : 'Middleware'}.` throw err } } const req = args[0] const url = new URL(req.url) const resource = url.pathname + url.search await edgeInstrumentationOnRequestError( err, { path: resource, method: req.method, headers: Object.fromEntries(req.headers.entries()), }, { routerKind: 'Pages Router', routePath: '/proxy', routeType: 'proxy', revalidateReason: undefined, } ) throw err } } } ``` Sources: [packages/next/src/build/templates/middleware.ts:41-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/middleware.ts#L41-L75) > [!NOTE] > `ProxyMissingExportError` clears its error stack property during construction to eliminate log spamming caused by routine export validation checks during local development. Sources: [packages/next/src/build/templates/middleware.ts:23-29](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/middleware.ts#L23-L29) ## Related - [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) - [Route Handlers](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers) --- ## Technical docs: Incremental Cache URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/lib/incremental-cache/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/incremental-cache/index.ts) - [packages/next/src/server/use-cache/use-cache-wrapper.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/use-cache/use-cache-wrapper.ts) - [packages/next/src/server/lib/incremental-cache/file-system-cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/incremental-cache/file-system-cache.ts) - [packages/next/src/server/response-cache/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/response-cache/index.ts) - [packages/next/src/client/components/segment-cache/cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts) - [packages/next/src/server/web/spec-extension/unstable-cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/unstable-cache.ts) - [packages/next/src/server/response-cache/types.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/response-cache/types.ts) - [packages/next/src/server/lib/cache-handlers/default.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/cache-handlers/default.ts) - [packages/next/src/server/route-modules/route-module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/route-module.ts) - [packages/next/src/server/revalidation-utils.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/revalidation-utils.ts) - [packages/next/src/server/lib/patch-fetch.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/patch-fetch.ts) - [packages/next/src/server/async-storage/work-store.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts) - [packages/next/src/server/web/spec-extension/revalidate.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/revalidate.ts) - [packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts) - [packages/next/src/server/resume-data-cache/resume-data-cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts)
## Overview The incremental cache system in Next.js serves as the central coordination layer for persisting, retrieving, and revalidating cached application data, route responses, and server component execution outputs[[packages/next/src/server/lib/incremental-cache/index.ts:159-172], [packages/next/src/server/response-cache/index.ts:118-152], [packages/next/src/server/use-cache/use-cache-wrapper.ts:235-276]]. By unifying disparate caching mechanisms—including patched global `fetch`, unstable_cache, and the `'use cache'` runtime directive—it eliminates redundant computation and data fetching across requests while supporting both static rendering and incremental static regeneration (ISR)[[packages/next/src/server/lib/incremental-cache/index.ts:501-654], [packages/next/src/server/web/spec-extension/unstable-cache.ts:160-323], [packages/next/src/server/lib/cache-handlers/default.ts:74-152]]. The architecture separates storage adapters, such as file-system and in-memory LRU backends, from core orchestration logic, enabling configurable persistence strategies and efficient tag-based invalidation across server instances[[packages/next/src/server/lib/incremental-cache/file-system-cache.ts:38-69], [packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts:10-42], [packages/next/src/server/lib/cache-handlers/default.ts:50-68]]. Sources: [packages/next/src/server/lib/incremental-cache/index.ts:159-172], [packages/next/src/server/lib/incremental-cache/file-system-cache.ts:38-69], [packages/next/src/server/lib/cache-handlers/default.ts:50-68], [packages/next/src/server/response-cache/index.ts:118-152], [packages/next/src/server/web/spec-extension/unstable-cache.ts:160-323], [packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts:10-42] ## Incremental cache core architecture ### Public API and `CacheHandler` lifecycle The `IncrementalCache` class orchestrates data retrieval and storage across fetch requests, route responses, and image generation. It interacts with storage backends via the `CacheHandler` base class, which defines the standard asynchronous interface for persistence operations. ```typescript export class CacheHandler { constructor(_ctx: CacheHandlerContext) {} public async get( _cacheKey: string, _ctx: | GetIncrementalFetchCacheContext | GetIncrementalResponseCacheHandlerContext | GetIncrementalImageCacheContext ): Promise { return {} as any } public async set( _cacheKey: string, _data: IncrementalCacheValue | null, _ctx: | SetIncrementalFetchCacheContext | SetIncrementalResponseCacheHandlerContext | SetIncrementalImageCacheContext ): Promise {} public async revalidateTag( _tags: string | string[], _durations?: { expire?: number } ): Promise {} public resetRequestCache(): void {} } ``` Sources: [packages/next/src/server/lib/incremental-cache/index.ts:113-142] The base `CacheHandler` accepts a `CacheHandlerContext` object during initialization, which supplies file system utilities, development flags, memory cache limits, and prerender manifests. | Context Property | Type | Description | | :--- | :--- | :--- | | `fs` | `CacheFs \| undefined` | Virtual or node file system interface for disk storage. | | `dev` | `boolean \| undefined` | Indicates whether the server is running in development mode. | | `flushToDisk` | `boolean \| undefined` | Determines whether ISR updates should be written immediately to disk. | | `serverDistDir` | `string \| undefined` | Absolute path to the server distribution directory. | | `maxMemoryCacheSize` | `number \| undefined` | Maximum memory allowed for in-memory caching layers. | | `fetchCacheKeyPrefix` | `string \| undefined` | Optional prefix applied to all fetch cache storage keys. | | `prerenderManifest` | `PrerenderManifest \| undefined` | Manifest containing static routes, dynamic routes, and ISR revalidation timings. | | `revalidatedTags` | `string[]` | List of tags marked as revalidated during the current execution. | | `_requestHeaders` | `Record` | Incoming HTTP request headers associated with the cache context. | Sources: [packages/next/src/server/lib/incremental-cache/index.ts:43-53] ### Initialization and custom cache handler loading Route modules initialize the incremental cache per request by invoking `getIncrementalCache` on incoming requests. This method detects the execution environment, loads user-defined custom cache handlers from `nextConfig.cacheHandlers`, and configures directory paths. ```typescript const incrementalCache = new IncrementalCache({ fs: ( require('../lib/node-fs-methods') as typeof import('../lib/node-fs-methods') ).nodeFs, dev: this.isDev, requestHeaders: req.headers, allowedRevalidateHeaderKeys: nextConfig.experimental.allowedRevalidateHeaderKeys, minimalMode: isMinimalMode, serverDistDir: `${projectDir}/${this.distDir}/server`, fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix, maxMemoryCacheSize: nextConfig.cacheMaxMemorySize, flushToDisk: !isMinimalMode && nextConfig.experimental.isrFlushToDisk, previewProps, prerenderManifest, CurCacheHandler: CacheHandler, locales: nextConfig.i18n?.locales, }) ;(globalThis as any).__incrementalCache = incrementalCache return incrementalCache ``` Sources: [packages/next/src/server/route-modules/route-module.ts:546-568] > [!NOTE] > In the [Edge runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime), `getIncrementalCache` bypasses dynamic class loading and returns the global instance stored at `globalThis.__incrementalCache`. Sources: [packages/next/src/server/route-modules/route-module.ts:518-520] ### Retrieval orchestration and resume data cache integration When `IncrementalCache.get()` is invoked with `IncrementalCacheKind.FETCH`, it first checks the Request Resume Data Cache (RDC) available through `workUnitAsyncStorage`. If a valid RDC entry exists and no associated tags have been recently revalidated, it returns the cached entry immediately without calling the underlying `cacheHandler`. ```typescript const workUnitStore = workUnitAsyncStorage.getStore() const resumeDataCache = workUnitStore ? getResumeDataCache(workUnitStore) : null if (resumeDataCache) { const memoryCacheData = resumeDataCache.fetch.get(cacheKey) if (memoryCacheData?.kind === CachedRouteKind.FETCH) { const workStore = workAsyncStorage.getStore() const combinedTags = [...(ctx.tags || []), ...(ctx.softTags || [])] const hasRevalidatedTag = combinedTags.some( (tag) => this.revalidatedTags?.includes(tag) || workStore?.pendingRevalidatedTags?.some( (item) => item.tag === tag ) ) if (hasRevalidatedTag) { // Fall through to cacheHandler lookup } else { return { isStale: false, value: memoryCacheData } } } } ``` Sources: [packages/next/src/server/lib/incremental-cache/index.ts:521-553] > [!WARNING] > If development mode is active and `cache-control` is set to `no-cache` on fetch requests, or if test mode is enabled via `disableForTestmode`, the prerender cache is entirely bypassed and `null` is returned. Sources: [packages/next/src/server/lib/incremental-cache/index.ts:564-573] For non-fetch entries, such as pages and [route handlers](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers), `IncrementalCache` scopes storage keys using `getRouteCacheKey` before delegating retrieval to the configured `cacheHandler`. Sources: [packages/next/src/server/lib/incremental-cache/index.ts:575-584] ## File system and memory backends ### File system cache storage and seed promotions `FileSystemCache` coordinates persistent ISR and fetch data stored on disk with an in-memory `LRUCache` layer initialized when `ctx.maxMemoryCacheSize` is specified. Cache directory paths are resolved via `getFilePath`, directing fetch entries to `.next/cache/fetch-cache`, legacy pages to `.next/server/pages`, and [app router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) outputs to `.next/server/app`. When reading scoped response keys starting with `/${ROUTE_CACHE_DIRECTORY}/`, `FileSystemCache` falls back to legacy path structures and verifies route metadata ownership. > [!NOTE] > During seed reads, lookup operations track active readers and versions in `FileSystemCache.seedReads`. When a seed entry is successfully resolved, `promoteSeed` promotes it atomically to disk via `writeFileAtomic` and populates the memory cache layer. Sources: [packages/next/src/server/lib/incremental-cache/file-system-cache.ts:38-49], [packages/next/src/server/lib/incremental-cache/file-system-cache.ts:73-96], [packages/next/src/server/lib/incremental-cache/file-system-cache.ts:449-492], [packages/next/src/server/lib/incremental-cache/file-system-cache.ts:742-778] ### Multi-file writer and memory cache backends To serialize concurrent disk writes safely across multiple cache entries, `FileSystemCache` relies on `MultiFileWriter`. The default in-memory cache handler (`createDefaultCacheHandler`) manages local runtime caching using an instance of `LRUCache` that computes entry sizes from buffer byte lengths and cache key lengths. ```typescript const memoryCache = new LRUCache( maxSize, (entry, cacheKey) => entry.size + cacheKey.length ) const pendingSets = new Map>() ``` Sources: [packages/next/src/server/lib/cache-handlers/default.ts:64-68] > [!WARNING] > In production environments, cache entries configured with an expiration of zero (`expire === 0`) are treated as dynamic and skipped on write to prevent persisting values that will never be served back from the cache handler. Sources: [packages/next/src/server/lib/cache-handlers/default.ts:166-176] ## Response cache integration ### In-flight batching and minimal mode LRU caching `ResponseCache` manages route response caching, ISR entry resolution, and in-flight request deduplication across concurrent renders using two distinct batchers: `getBatcher` and `revalidateBatcher`. `getBatcher` uses a cache key function combining the route key with `isOnDemandRevalidate` (`${key}-${isOnDemandRevalidate ? '1' : '0'}`), while `schedulerFn` uses `scheduleOnNextTick` to ensure promises are added to pending collections before any asynchronous work begins. ```typescript private readonly getBatcher = Batcher.create< { key: string; isOnDemandRevalidate: boolean }, IncrementalResponseCacheResult, string >({ cacheKeyFn: ({ key, isOnDemandRevalidate }) => `${key}-${isOnDemandRevalidate ? '1' : '0'}`, schedulerFn: scheduleOnNextTick, }) private readonly revalidateBatcher = Batcher.create< string, IncrementalResponseCacheResult >({ schedulerFn: scheduleOnNextTick, }) ``` Sources: [packages/next/src/server/response-cache/index.ts:122-145] In minimal mode, `ResponseCache` utilizes an `LRUCache` indexed by compound cache keys formed via `createCacheKey`, joining the pathname and `invocationID` (or `TTL_SENTINEL` when `invocationID` is absent). Evicted invocation IDs are tracked in `evictedInvocationIDs`, which is bounded to 100 entries using a FIFO policy to prevent unbounded memory growth. > [!NOTE] - If a prefetch request misses the cache, it bypasses `revalidateBatcher` to execute `handleRevalidate` directly. This prevents a prefetch from joining a background ISR fallback-shell upgrade and incorrectly serving a concrete page shell instead of the expected fallback state. Sources: [packages/next/src/server/response-cache/index.ts:108-114], [packages/next/src/server/response-cache/index.ts:198-215], [packages/next/src/server/response-cache/index.ts:414-434] ### ISR entry resolution and stale checks When processing a `get` request, `ResponseCache` checks the underlying `incrementalCache` (when not in minimal mode) to retrieve any existing `IncrementalResponseCacheEntry`. If `previousIncrementalCacheEntry` is present and its `isStale` property is not `-1` (which signals a blocking revalidate is required due to an expired tag or expiration time), the cache resolves immediately with the cached value. ```typescript if ( previousIncrementalCacheEntry && !context.isOnDemandRevalidate && previousIncrementalCacheEntry.isStale !== -1 ) { resolve(previousIncrementalCacheEntry) resolved = true if (!previousIncrementalCacheEntry.isStale || context.isPrefetch) { return previousIncrementalCacheEntry } } ``` Sources: [packages/next/src/server/response-cache/index.ts:377-401] > [!WARNING] > A value of `isStale === -1` forces a blocking revalidation, ignoring non-blocking stale cache entries so that users receive a freshly generated response rather than an expired tag or timed-out cache payload. Sources: [packages/next/src/server/response-cache/index.ts:384-393] ## Fetch patching and unstable cache ### Global fetch patching and request caching Next.js intercepts global network requests through a patched `fetch` implementation that integrates with the Incremental Cache and work unit stores. When a fetch request occurs during rendering, the patched function checks whether the request is cacheable and attempts to retrieve an existing entry using `incrementalCache.get`. If a valid cache entry is found and its state is stale, the request handles revalidation based on the consumer requirements. ```typescript if (entry?.value && entry.value.kind === CachedRouteKind.FETCH) { // If the consumer will persist this result in a server cache, // wait for fresh data so it doesn't persist a stale value. if (willConsumerServerCache(workUnitStore) && entry.isStale) { isForegroundRevalidate = true } else { if (entry.isStale) { workStore.pendingRevalidates ??= {} if (!workStore.pendingRevalidates[cacheKey]) { const pendingRevalidate = doOriginalFetch(true) .then(async (response) => ({ body: await response.arrayBuffer(), headers: response.headers, status: response.status, statusText: response.statusText, })) .finally(() => { workStore.pendingRevalidates ??= {} delete workStore.pendingRevalidates[cacheKey || ''] }) pendingRevalidate.catch(console.error) workStore.pendingRevalidates[cacheKey] = pendingRevalidate } } cachedFetchData = entry.value.data } } ``` Sources: [packages/next/src/server/lib/patch-fetch.ts:1114-1145] > [!WARNING] > When `init.cache` is set to `'no-store'` in the Edge Runtime, the `cache` property is deleted from the options object before execution to prevent errors from platforms like Cloudflare Workers that do not support standard cache configuration flags. Sources: [packages/next/src/server/lib/patch-fetch.ts:1177-1186] ### The `unstable_cache` wrapper and background revalidation The `unstable_cache` helper wraps asynchronous data-fetching functions to cache their return values across invocations. Within an App Router context, `unstable_cache` inspects `workUnitStore` types to aggregate cache tags and manage revalidation intervals. If an entry is stale, it initiates a background revalidation promise stored within `workStore.pendingRevalidates` to avoid duplicate concurrent executions. ```typescript if (cacheEntry.isStale) { if (!workStore.pendingRevalidates) { workStore.pendingRevalidates = {} } if (!workStore.pendingRevalidates[invocationKey]) { const revalidationPromise = workUnitAsyncStorage .run(innerCacheStore, cb, ...args) .then(async (result) => { await cacheNewResult( result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl ) return result }) .catch((err) => { console.error( `revalidating cache with key: ${invocationKey}`, err ) return cachedResponse }) if (willConsumerServerCache(workUnitStore)) { revalidationPromise.catch(() => {}) } workStore.pendingRevalidates[invocationKey] = revalidationPromise } if (willConsumerServerCache(workUnitStore)) { return await workStore.pendingRevalidates[invocationKey] } return cachedResponse } ``` Sources: [packages/next/src/server/web/spec-extension/unstable-cache.ts:264-321] > [!NOTE] > Work unit store types including `cache`, `private-cache`, `prerender`, `prerender-runtime`, and `prerender-legacy` participate in time-to-live reduction by comparing and updating `workUnitStore.revalidate` against the narrower revalidation interval specified by individual cache wrappers. Sources: [packages/next/src/server/web/spec-extension/unstable-cache.ts:182-198] ## Use cache function execution ### Tiered handler orchestration and default memory cache Cache handler functions coordinate through dedicated storage layers, managed via handlers such as `getCacheHandler`, `getDevTieredCacheHandler`, and `getPrivateCacheHandler`. The default implementation provided by `createDefaultCacheHandler` builds upon an in-memory `LRUCache` instance keyed by serialized entries and cache keys. ```typescript export function createDefaultCacheHandler(maxSize: number): CacheHandler { // If the max size is 0, return a cache handler that doesn't cache anything, // this avoids an unnecessary LRUCache instance and potential memory // allocation. if (maxSize === 0) { return { get: () => Promise.resolve(undefined), set: () => Promise.resolve(), refreshTags: () => Promise.resolve(), getExpiration: () => Promise.resolve(0), updateTags: () => Promise.resolve(), } } const memoryCache = new LRUCache( maxSize, (entry, cacheKey) => entry.size + cacheKey.length ) const pendingSets = new Map>() const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE ? console.debug.bind(console, 'DefaultCacheHandler:') : undefined ``` Sources: [packages/next/src/server/lib/cache-handlers/default.ts:50-73] > [!NOTE] > If `maxSize` is configured to `0`, `createDefaultCacheHandler` immediately returns a dummy cache handler interface whose methods resolve to `undefined` or empty promises, bypassing LRU allocation entirely. Sources: [packages/next/src/server/lib/cache-handlers/default.ts:54-62] | Handler Method | Behavior on Invocation | | :--- | :--- | | `get(cacheKey)` | Awaits any pending set operation, retrieves from the memory LRU, checks eviction sentinels and tags, and streams back the buffer payload. | | `set(cacheKey, pendingEntry)` | Registers a pending set promise to serialize the incoming stream to a Buffer, writing it into the LRU cache unless skipped as a dynamic entry. | | `getExpiration(tags)` | Scans the tag manifest for entries, returning the maximum expired timestamp among requested tags or `0`. | | `updateTags(tags, durations)` | Updates the tag manifest with immediate expiration or computed stale/expired timestamps derived from provided durations. | Sources: [packages/next/src/server/lib/cache-handlers/default.ts:75-244] ### Streaming serialization and shared cache state In `packages/next/src/server/use-cache/use-cache-wrapper.ts`, execution is coordinated via `SharedCacheEntry` and `ResolvableSharedCacheResult` classes to deduplicate concurrent cache invocations and manage stream forking. ```typescript class SharedCacheEntry { private stream: ReadableStream /** * Resolves when collection finishes, without waiting for handler writes. */ public readonly pendingMetadata: Promise /** * Resolves with collected metadata after any handler writes settle. Write * failures do not discard the metadata. Collection failures still reject this * promise. */ public readonly pendingCompletion: Promise constructor( stream: ReadableStream, pendingMetadata: Promise, pendingWrite: Promise | undefined ) { this.stream = stream this.pendingMetadata = pendingMetadata this.pendingCompletion = pendingWrite === undefined ? pendingMetadata : pendingWrite.then( () => pendingMetadata, () => pendingMetadata ) } /** * Tee the stream: returns a copy for the caller, replaces the internal stream * with the remaining branch for future callers. Both the leader and joiners * call this — everyone gets a fork. */ fork(): ReadableStream { const [forked, remaining] = this.stream.tee() this.stream = remaining return forked } } ``` Sources: [packages/next/src/server/use-cache/use-cache-wrapper.ts:235-276] > [!WARNING] > Metadata propagation and stream reading are decoupled: `SharedCacheEntry` exposes `pendingMetadata` which resolves as soon as data collection finishes, whereas `pendingCompletion` waits for underlying handler write operations to settle. Sources: [packages/next/src/server/use-cache/use-cache-wrapper.ts:238-264] Concurrent executions join existing cache entries through `ResolvableSharedCacheResult`, ensuring that duplicate requests during generation share the same underlying stream via `.tee()` fork operations without triggering redundant work against origin handlers. ```typescript class ResolvableSharedCacheResult { private readonly deferred = createPromiseWithResolvers() private readonly registrations: Array<{ map: Map> key: string /** * Where to move the entry once the invocation completes, instead of * dropping it. Only set for the request-scoped map, and only for kinds * whose entries are worth retaining; the module-scope cross-request map * must never retain, since its entries would outlive the request that * produced them. */ retentionMap?: Map> }> = [] registerIn( map: Map>, key: string, retentionMap?: Map> ): void { map.set(key, this.deferred.promise) this.registrations.push({ map, key, retentionMap }) } ``` Sources: [packages/next/src/server/use-cache/use-cache-wrapper.ts:302-325] ## Tag validation and revalidation lifecycle ### Expiration tracking and stale tag calculation Tag validity is evaluated against the shared `tagsManifest` map, storing entries with `stale` and `expired` numeric timestamps. The helper functions `areTagsExpired` and `areTagsStale` inspect incoming tag arrays against a given `timestamp` baseline to determine cache validity. ```typescript export const areTagsExpired = (tags: string[], timestamp: Timestamp) => { for (const tag of tags) { const entry = tagsManifest.get(tag) const expiredAt = entry?.expired if (typeof expiredAt === 'number') { const now = performance.timeOrigin + performance.now() // For immediate expiration (expiredAt <= now) and tag was invalidated after entry was created // OR for future expiration that has now passed (expiredAt > timestamp && expiredAt <= now) const isImmediatelyExpired = expiredAt <= now && expiredAt > timestamp if (isImmediatelyExpired) { return true } } } return false } export const areTagsStale = (tags: string[], timestamp: Timestamp) => { for (const tag of tags) { const entry = tagsManifest.get(tag) const staleAt = entry?.stale ?? 0 if (typeof staleAt === 'number' && staleAt > timestamp) { return true } } return false ``` Sources: [packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts:12-42] > [!NOTE] > An entry is considered immediately expired if `expiredAt <= now` and `expiredAt > timestamp`, or if a future expiration time has passed since the cached entry's creation timestamp. Sources: [packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts:17-25] | Function | Comparison Logic | Return Condition | | :--- | :--- | :--- | | `areTagsExpired(tags, timestamp)` | Checks if `expiredAt <= now && expiredAt > timestamp` for any tag entry. | Returns `true` on the first expired match. | | `areTagsStale(tags, timestamp)` | Checks if `staleAt > timestamp` for any tag entry in `tagsManifest`. | Returns `true` if any tag is newer than the cache entry timestamp. | Sources: [packages/next/src/server/lib/incremental-cache/tags-manifest.external.ts:12-42] ### On-demand revalidation and work store propagation On-demand revalidation APIs such as `revalidateTag`, `updateTag`, and `revalidatePath` queue tag invalidations within the active `workStore.pendingRevalidatedTags` array via `revalidate()`. During execution, `withExecuteRevalidates` snapshots the initial revalidation state, runs the callback, computes state differences through `diffRevalidationState`, and dispatches updates via `executeRevalidates`. ```typescript export async function withExecuteRevalidates( store: WorkStore | undefined, callback: () => Promise ): Promise { if (!store) { return callback() } // If we executed any revalidates during the request, then we don't want to execute them again. // save the state so we can check if anything changed after we're done running callbacks. const savedRevalidationState = cloneRevalidationState(store) try { return await callback() } finally { // Check if we have any new revalidates, and if so, wait until they are all resolved. const newRevalidates = diffRevalidationState( savedRevalidationState, cloneRevalidationState(store) ) await executeRevalidates(store, newRevalidates) } } ``` Sources: [packages/next/src/server/revalidation-utils.ts:6-26] > [!WARNING] > Calling `updateTag` outside of a Server Action throws an error requiring `revalidateTag` for Route Handlers, whereas `refresh` restricts dynamic path revalidation specifically to [Server Actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions) with action phase validation. Sources: [packages/next/src/server/web/spec-extension/revalidate.ts:58-103] Tags are grouped by their configured cache profiles for batch processing. The `revalidateTags` function iterates over resolved cache life configurations, invoking `handler.updateTags` across active cache handlers and `incrementalCache.revalidateTag`. ```typescript async function revalidateTags( tagsWithProfile: Array<{ tag: string profile?: string | { expire?: number } }>, incrementalCache: IncrementalCache | undefined, workStore?: WorkStore ): Promise { if (tagsWithProfile.length === 0) { return } const handlers = getCacheHandlers() ?? [] const promises: Promise[] = [] // Group tags by profile for batch processing const tagsByProfile = new Map< | string | { stale?: number; revalidate?: number; expire?: number } | undefined, string[] >() for (const item of tagsWithProfile) { const profile = item.profile // Find existing profile by comparing values let existingKey = undefined for (const [key] of tagsByProfile) { if ( typeof key === 'string' && typeof profile === 'string' && key === profile ) { existingKey = key break } if ( typeof key === 'object' && typeof profile === 'object' && JSON.stringify(key) === JSON.stringify(profile) ) { existingKey = key break } if (key === profile) { existingKey = key break } } const profileKey = existingKey || profile if (!tagsByProfile.has(profileKey)) { tagsByProfile.set(profileKey, []) } tagsByProfile.get(profileKey)!.push(item.tag) } // Process each profile group for (const [profile, tagsForProfile] of tagsByProfile) { // Look up the cache profile from workStore if available let durations: { expire?: number } | undefined if (profile) { let cacheLife: | { stale?: number; revalidate?: number; expire?: number } | undefined if (typeof profile === 'object') { // Profile is already a cacheLife configuration object cacheLife = profile } else if (typeof profile === 'string') { // Profile is a string key, look it up in workStore cacheLife = workStore?.cacheLifeProfiles[profile] if (!cacheLife) { throw new Error( `Invalid profile provided "${profile}" must be configured under cacheLife in next.config or be "max"` ) } } ``` Sources: [packages/next/src/server/revalidation-utils.ts:88-192] ## Related - [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) - [Dynamic Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering) - [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) --- ## Technical docs: Async Storage URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/async-storage
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/app-render/after-task-async-storage-instance.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/after-task-async-storage-instance.ts) - [packages/next/src/server/app-render/action-async-storage-instance.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/action-async-storage-instance.ts) - [packages/next/src/server/async-storage/request-store.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/request-store.ts) - [packages/next/src/server/app-render/work-unit-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage.external.ts) - [packages/next/src/server/app-render/console-async-storage-instance.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/console-async-storage-instance.ts) - [packages/next/src/server/app-render/dynamic-access-async-storage-instance.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage-instance.ts) - [packages/next/src/server/app-render/work-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-async-storage.external.ts) - [packages/next/src/server/app-render/async-local-storage.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts) - [packages/next/src/server/request/cookies.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/cookies.ts) - [packages/next/src/experimental/testmode/context.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/experimental/testmode/context.ts) - [packages/next/src/server/app-render/work-async-storage-instance.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-async-storage-instance.ts) - [packages/next/src/server/web/adapter.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/adapter.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/server/app-render/work-unit-async-storage-instance.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage-instance.ts) - [packages/next/src/server/async-storage/draft-mode-provider.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/draft-mode-provider.ts) - [packages/next/src/server/request/headers.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/headers.ts) - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/src/client/components/segment-cache/navigation-testing-lock.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/navigation-testing-lock.ts) - [packages/next/src/server/lib/trace/request-insights-identity.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/trace/request-insights-identity.ts) - [packages/next/src/server/request/draft-mode.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts) - [packages/next/src/server/app-render/action-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/action-async-storage.external.ts) - [packages/next/src/server/async-storage/with-store.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/with-store.ts) - [packages/next/src/server/after/builtin-request-context.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/after/builtin-request-context.ts) - [packages/next/src/server/app-render/after-task-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/after-task-async-storage.external.ts) - [packages/next/src/server/app-render/console-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/console-async-storage.external.ts) - [packages/next/src/client/components/server-async-storage.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/server-async-storage.ts) - [packages/next/src/server/app-render/dynamic-access-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage.external.ts) - [packages/next/src/server/web/spec-extension/adapters/request-cookies.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/adapters/request-cookies.ts) - [packages/next/src/server/async-storage/work-store.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts) - [packages/next/src/client/components/server-async-storage.browser.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/server-async-storage.browser.ts)
## Overview Next.js uses asynchronous storage infrastructure built on `AsyncLocalStorage` to propagate request-scoped execution contexts, render metadata, and dynamic states across asynchronous boundaries. By maintaining realm-safe singletons via global symbols and fallback shims, the system tracks active rendering phases, request headers, cookies, and draft mode parameters across Node.js servers, worker threads, and the [Edge Runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime). These storage contexts coordinate request lifecycles throughout [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture), managing dynamic data access enforcement and execution boundaries for [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) and [Route Handlers](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/route-handlers). Sources: [packages/next/src/server/app-render/async-local-storage.ts:36-83](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts#L36-L83), [packages/next/src/server/app-render/work-unit-async-storage.external.ts:28-34](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage.external.ts#L28-L34), [packages/next/src/server/request/cookies.ts:36-147](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/cookies.ts#L36-L147) ## Global Storage Infrastructure ### Global AsyncLocalStorage Singletons Next.js initializes and exports several core `AsyncLocalStorage` singletons to manage request contexts, action execution, console logging interception, dynamic access tracking, and background tasks. Each storage instance is created by calling `getOrCreateGlobalAsyncLocalStorage` with a unique identifier string combined with the current Next.js version (`process.env.__NEXT_VERSION`) via `Symbol.for`. ```typescript export function getOrCreateGlobalAsyncLocalStorage( name: string ): AsyncLocalStorage { const key = Symbol.for(`@next/${name}@${process.env.__NEXT_VERSION}`) const globalStore = globalThis as typeof globalThis & { [key: symbol]: AsyncLocalStorage | undefined } return (globalStore[key] ??= createAsyncLocalStorage()) } ``` Sources: [packages/next/src/server/app-render/async-local-storage.ts:73-83](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts#L73-L83) | Singleton Instance Name | Storage Identifier String | Associated Type | | :--- | :--- | :--- | | `actionAsyncStorageInstance` | `'action-async-storage'` | `ActionAsyncStorage` | | `afterTaskAsyncStorageInstance` | `'after-task-async-storage'` | `AfterTaskAsyncStorage` | | `consoleAsyncStorageInstance` | `'console-async-storage'` | `ConsoleAsyncStorage` | | `dynamicAccessAsyncStorageInstance` | `'dynamic-access-async-storage'` | `DynamicAccessStorage` | | `workAsyncStorageInstance` | `'work-async-storage'` | `WorkAsyncStorage` | | `workUnitAsyncStorageInstance` | `'work-unit-async-storage'` | `WorkUnitAsyncStorage` | Sources: [packages/next/src/server/app-render/after-task-async-storage-instance.ts:4-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/after-task-async-storage-instance.ts#L4-L5), [packages/next/src/server/app-render/action-async-storage-instance.ts:4-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/action-async-storage-instance.ts#L4-L5), [packages/next/src/server/app-render/console-async-storage-instance.ts:4-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/console-async-storage-instance.ts#L4-L5), [packages/next/src/server/app-render/dynamic-access-async-storage-instance.ts:4-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage-instance.ts#L4-L5), [packages/next/src/server/app-render/work-async-storage-instance.ts:4-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-async-storage-instance.ts#L4-L5), [packages/next/src/server/app-render/work-unit-async-storage-instance.ts:4-5](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage-instance.ts#L4-L5) > [!NOTE] > Using `Symbol.for` with the Next.js version ensures that if multiple distinct versions of Next.js are evaluated within the same JavaScript realm, their async storage instances remain isolated, preventing incompatible store shape collisions. Sources: [packages/next/src/server/app-render/async-local-storage.ts:69-72](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts#L69-L72) ### Fallback Shims and Environment Safety When `AsyncLocalStorage` is unavailable in the execution environment, `createAsyncLocalStorage` falls back to `FakeAsyncLocalStorage`. The fake shim implements the `AsyncLocalStorage` interface by returning `undefined` for `getStore()` and throwing an invariant error for all lifecycle operations (`disable`, `run`, `exit`, `enterWith`). ```typescript class FakeAsyncLocalStorage implements AsyncLocalStorage { disable(): void { throw sharedAsyncLocalStorageNotAvailableError } getStore(): Store | undefined { // This fake implementation of AsyncLocalStorage always returns `undefined`. return undefined } run(): R { throw sharedAsyncLocalStorageNotAvailableError } exit(): R { throw sharedAsyncLocalStorageNotAvailableError } enterWith(): void { throw sharedAsyncLocalStorageNotAvailableError } static bind(fn: T): T { return fn } } ``` Sources: [packages/next/src/server/app-render/async-local-storage.ts:7-34](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts#L7-L34) ```typescript export function createAsyncLocalStorage< Store extends {}, >(): AsyncLocalStorage { if (maybeGlobalAsyncLocalStorage) { return new maybeGlobalAsyncLocalStorage() } return new FakeAsyncLocalStorage() } ``` Sources: [packages/next/src/server/app-render/async-local-storage.ts:39-46](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts#L39-L46) > [!WARNING] > Module loader symlink resolution bugs (such as those tied to `fs.realpathSync` in `next dev` under package managers like pnpm) can cause the same file to be evaluated multiple times in a single realm, creating duplicate module instances. Storing singletons on `globalThis` via symbol keys prevents context loss across these duplicate module evaluations. Sources: [packages/next/src/server/app-render/async-local-storage.ts:50-68](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/async-local-storage.ts#L50-L68) For client-side compilation, `server-async-storage.ts` is aliased to `server-async-storage.browser.ts`, exporting `undefined` stubs for `actionAsyncStorage`, `workAsyncStorage`, and `workUnitAsyncStorage` to prevent server-only modules from leaking into browser bundles. ```typescript // Browser variant of `./server-async-storage`. The server-only async-storage // singletons don't exist in the browser, so these are `undefined`. Consumers // guard usage behind `typeof window === 'undefined'`, so the stubs are never // dereferenced. export const actionAsyncStorage = undefined export const workAsyncStorage = undefined export const workUnitAsyncStorage = undefined ``` Sources: [packages/next/src/client/components/server-async-storage.browser.ts:1-7](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/server-async-storage.browser.ts#L1-L7), [packages/next/src/client/components/server-async-storage.ts:1-9](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/server-async-storage.ts#L1-L9) ## Work Store Lifecycle ### Store Creation and Prerender Configuration The `WorkStore` is instantiated through factory functions that construct and initialize store instances based on rendering contexts and build options. The `createWorkStore` and `createPrerenderWorkStore` functions invoke `createWorkStoreImpl`, passing parameters that dictate fetch metrics tracking behavior. | Factory Function | Metric Tracking Flag Condition | | :--- | :--- | | `createWorkStore` | `!!process.env.__NEXT_DEV_SERVER` | | `createPrerenderWorkStore` | `!!process.env.__NEXT_DEV_SERVER \|\| !!process.env.NEXT_DEBUG_BUILD \|\| process.env.NEXT_SSG_FETCH_METRICS === '1'` | Sources: [packages/next/src/server/async-storage/work-store.ts:91-102](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts#L91-L102) ### Initialization and Context Capture During initialization, `createWorkStoreImpl` maps properties from `WorkStoreContext` and `RenderOpts` directly onto the `WorkStore` object. It normalizes the route using `normalizeAppPath(page)`, resolves the [incremental cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) by falling back to `(globalThis as any).__incrementalCache` when edge runtime local environments lack an explicit instance, and records the request start time using `performance.timeOrigin + performance.now()`. ```typescript const store: WorkStore = { page, route: normalizeAppPath(page), incrementalCache: // we fallback to a global incremental cache for edge-runtime locally // so that it can access the fs cache without mocks renderOpts.incrementalCache || (globalThis as any).__incrementalCache, cacheLifeProfiles: renderOpts.cacheLifeProfiles, useCacheTimeout: renderOpts.experimental.useCacheTimeout, durableUseCacheEntries: renderOpts.experimental.durableUseCacheEntries, staticPageGenerationTimeout: renderOpts.staticPageGenerationTimeout, isBuildTimePrerendering: renderOpts.isBuildTimePrerendering, fetchCache: renderOpts.fetchCache, isOnDemandRevalidate: renderOpts.isOnDemandRevalidate, requestId: undefined, htmlRequestId: undefined, isDraftMode: renderOpts.isDraftMode, isPrefetchRequest, buildId, deploymentId, reactLoadableManifest: renderOpts?.reactLoadableManifest || {}, assetPrefix: renderOpts?.assetPrefix || '', nonce, afterContext: createAfterContext(renderOpts), cacheComponentsEnabled: renderOpts.cacheComponents, validationLevel: renderOpts.validationLevel, previouslyRevalidatedTags, requestStartTime: performance.timeOrigin + performance.now(), refreshTagsByCacheKind: createRefreshTagsByCacheKind(), runInCleanSnapshot: createSnapshot(), shouldTrackFetchMetrics, clientComponentLoadTracker: undefined, reactServerErrorsByDigest: new Map(), } ``` Sources: [packages/next/src/server/async-storage/work-store.ts:116-152](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts#L116-L152) > [!NOTE] > `renderOpts.store` is temporarily assigned the newly created store reference to support legacy code paths accessing store values outside the active request execution context. Sources: [packages/next/src/server/async-storage/work-store.ts:154-156](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts#L154-L156) ### After-Context and Lazy Tag Refreshing The lifecycle builder constructs an `AfterContext` instance using lifecycle options such as `waitUntil`, `onClose`, and `onTaskError`. Simultaneously, it initializes the `refreshTagsByCacheKind` map by iterating over available cache handler entries and wrapping handlers that expose a `refreshTags` method into `LazyResult` instances. ```typescript function createAfterContext(renderOpts: RequestLifecycleOpts): AfterContext { const { waitUntil, onClose, onAfterTaskError } = renderOpts return new AfterContext({ waitUntil, onClose, onTaskError: onAfterTaskError, }) } /** * Creates a map with lazy results that refresh tags for the respective cache * kind when they're awaited for the first time. */ function createRefreshTagsByCacheKind(): Map> { const refreshTagsByCacheKind = new Map>() const cacheHandlers = getCacheHandlerEntries() if (cacheHandlers) { for (const [kind, cacheHandler] of cacheHandlers) { if ('refreshTags' in cacheHandler) { refreshTagsByCacheKind.set( kind, createLazyResult(async () => cacheHandler.refreshTags()) ) } } } return refreshTagsByCacheKind } ``` Sources: [packages/next/src/server/async-storage/work-store.ts:160-189](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts#L160-L189) ### Static Generation Snapshotting [Static generation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/static-generation) and cache entry creation require isolation from request-specific state. The `runInCleanSnapshot` property on the store is initialized via `createSnapshot()`, supplying a clean `AsyncLocalStorage` snapshot wrapper that prevents cache generation routines from reading request-bound scopes like `cookies()` inside `React.cache()`. ```typescript refreshTagsByCacheKind: createRefreshTagsByCacheKind(), runInCleanSnapshot: createSnapshot(), ``` Sources: [packages/next/src/server/async-storage/work-store.ts:147-148](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/work-store.ts#L147-L148), [packages/next/src/server/app-render/work-async-storage.external.ts:197-200](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-async-storage.external.ts#L197-L200) ## Work Unit Store Hierarchy ### Common Work Unit Stores and Phase Management Work unit stores represent different execution scopes in the [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router), separating active requests, prerenders, and background tasks. Every work unit store extends `CommonWorkUnitStore`, which defines a mutable `phase` property and readonly `implicitTags`. | Work Unit Phase | Description | | :--- | :--- | | `'action'` | Active execution of [Server Actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions) responding to client mutations | | `'render'` | Server-side rendering of Server Component trees and route segments | | `'after'` | Execution of deferred work via background tasks or `after` callbacks | Sources: [packages/next/src/server/app-render/work-unit-async-storage.external.ts:28-34](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage.external.ts#L28-L34) ### Request and Prerender Contexts The `RequestStore` interface models active HTTP requests and supports mutable cookies, draft mode tracking, header access, and incremental resume data caches. It maintains asynchronous API promises and handles development-only flags like `needsRuntimeShell` and `hasIncompatibleShellContent` to distinguish static and runtime prerender behaviors. ```typescript export interface RequestStore extends CommonWorkUnitStore { readonly type: 'request' /** * The URL of the request. This only specifies the pathname and the search * part of the URL. */ readonly url: { /** * The pathname of the requested URL. */ readonly pathname: string /** * The search part of the requested URL. If the request did not provide a * search part, this will be an empty string. */ readonly search: string } readonly headers: ReadonlyHeaders // This is mutable because we need to reassign it when transitioning from the action phase to the render phase. // The cookie object itself is deliberately read only and thus can't be updated. cookies: ReadonlyRequestCookies readonly mutableCookies: ResponseCookies readonly userspaceMutableCookies: ResponseCookies readonly draftMode: DraftModeProvider readonly isHmrRefresh?: boolean readonly serverComponentsHmrCache?: ServerComponentsHmrCache readonly hmrRefreshHash?: string readonly rootParams: Params /** * The resume data cache for this request. Either a mutable * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed * state). Narrow via `resumeDataCache.mutable` to tell them apart. */ resumeDataCache: ResumeDataCache | null ``` Sources: [packages/next/src/server/app-render/work-unit-async-storage.external.ts:36-76](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage.external.ts#L36-L76) > [!NOTE] > `PrerenderStoreModern` covers client, server, and runtime prerendering modes along with validation stores, utilizing conditional properties to track cache population without explicitly branching RSC and SSR code paths. Sources: [packages/next/src/server/app-render/work-unit-async-storage.external.ts:149-154](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/work-unit-async-storage.external.ts#L149-L154) ### Specialized Asynchronous Storages Action execution, background tasks, and dynamic access tracking operate through dedicated `AsyncLocalStorage` instances. `ActionStore` tracks whether execution is part of an action or an App Route handler. `AfterTaskStore` captures the `rootTaskSpawnphase` corresponding to the phase in which the topmost `after` call was invoked. ```typescript export interface ActionStore { readonly isAction?: boolean readonly isAppRoute?: boolean } ``` Sources: [packages/next/src/server/app-render/action-async-storage.external.ts:5-8](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/action-async-storage.external.ts#L5-L8), [packages/next/src/server/app-render/after-task-async-storage.external.ts:7-14](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/after-task-async-storage.external.ts#L7-L14) Dynamic access tracking relies on `DynamicAccessAsyncStore`, which holds an `AbortController` and a `reason` restricted to `'fallback-params'` or `'runtime'`. The `abortOnDynamicAccess` function updates the store reason unless it is already marked as `'runtime'` and aborts the associated controller. ```typescript export interface DynamicAccessAsyncStore { readonly abortController: AbortController reason: DynamicAccessReason | null } export type DynamicAccessReason = 'fallback-params' | 'runtime' ``` Sources: [packages/next/src/server/app-render/dynamic-access-async-storage.external.ts:6-11](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage.external.ts#L6-L11), [packages/next/src/server/app-render/dynamic-access-async-storage.external.ts:16-29](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage.external.ts#L16-L29) > [!WARNING] > Cache evaluation routines reading both fallback and runtime parameters will upgrade the cancellation reason from fallback-only to runtime, preventing stale static optimizations when runtime data is touched. Sources: [packages/next/src/server/app-render/dynamic-access-async-storage.external.ts:21-28](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage.external.ts#L21-L28) ## Request Store Composition ### Request Store Builders and Inputs The construction of a `RequestStore` instance relies on specialized creator functions that initialize phase contexts, route parameters, request headers, cookies, and cache references. `createRequestStoreForRender` initializes a store with a `'render'` phase by default, whereas `createRequestStoreForAPI` defaults to an `'action'` phase with empty root parameters (`{}`) and null resume data caches. Both helper functions delegate initialization to the core `createRequestStore` function, which accepts a `RequestStoreInputs` descriptor containing raw incoming request properties and optional HMR or preview properties. | Creator Function | Default Phase | Root Parameters | Resume Data Cache | | :--- | :--- | :--- | :--- | | `createRequestStoreForRender` | `'render'` | `rootParams` (passed) | `resumeDataCache` | | `createRequestStoreForAPI` | `'action'` | `{}` (empty) | `null` | Sources: [packages/next/src/server/async-storage/request-store.ts:184-244](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/request-store.ts#L184-L244) > [!NOTE] > Side-process consumers, such as the `'use cache'` deadlock probe worker, invoke `createRequestStore` directly with a serializable snapshot of headers and metadata when a native `req`/`res` pair is absent. Sources: [packages/next/src/server/async-storage/request-store.ts:246-253](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/request-store.ts#L246-L253) ### Caching and Lazy Initialization The `RequestStore` object uses internal lazy getters backed by a private `cache` object to construct and memoize expensive adapter instances on first access. Properties including `headers`, `cookies`, `mutableCookies`, `userspaceMutableCookies`, and `draftMode` are instantiated on demand, preventing unnecessary parsing overhead for requests that do not touch them. ```typescript const cache: { headers?: ReadonlyHeaders cookies?: ReadonlyRequestCookies mutableCookies?: ResponseCookies userspaceMutableCookies?: ResponseCookies draftMode?: DraftModeProvider } = {} return { type: 'request', phase, implicitTags, // Rather than just using the whole `url` here, we pull the parts we want // to ensure we don't use parts of the URL that we shouldn't. This also // lets us avoid requiring an empty string for `search` in the type. url: { pathname: url.pathname, search: url.search ?? '' }, rootParams, get headers() { if (!cache.headers) { // Seal the headers object that'll freeze out any methods that could // mutate the underlying data. cache.headers = getHeaders(headers) } return cache.headers }, get cookies() { if (!cache.cookies) { // if middleware is setting cookie(s), then include those in // the initial cached cookies so they can be read in render const requestCookies = new RequestCookies(HeadersAdapter.from(headers)) mergeMiddlewareCookies(headers, requestCookies) // Seal the cookies object that'll freeze out any methods that could // mutate the underlying data. cache.cookies = RequestCookiesAdapter.seal(requestCookies) } return cache.cookies }, set cookies(value: ReadonlyRequestCookies) { cache.cookies = value }, get mutableCookies() { if (!cache.mutableCookies) { const mutableCookies = getMutableCookies(headers, onUpdateCookies) mergeMiddlewareCookies(headers, mutableCookies) cache.mutableCookies = mutableCookies } return cache.mutableCookies }, get userspaceMutableCookies() { if (!cache.userspaceMutableCookies) { const userspaceMutableCookies = createCookiesWithMutableAccessCheck(this) cache.userspaceMutableCookies = userspaceMutableCookies } return cache.userspaceMutableCookies }, get draftMode() { if (!cache.draftMode) { cache.draftMode = new DraftModeProvider( previewProps, headers, this.cookies, this.mutableCookies ) } return cache.draftMode }, ``` Sources: [packages/next/src/server/async-storage/request-store.ts:269-342](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/request-store.ts#L269-L342) Cookie initialization parses request cookies from headers and automatically merges any middleware-set cookies present in the `'x-middleware-set-cookie'` header via `mergeMiddlewareCookies`. The sealed `cookies` property returns a read-only adapter, while `mutableCookies` provides a `ResponseCookies` instance capable of tracking modifications and triggering `onUpdateCookies` callbacks. ```typescript get cookies() { if (!cache.cookies) { // if middleware is setting cookie(s), then include those in // the initial cached cookies so they can be read in render const requestCookies = new RequestCookies(HeadersAdapter.from(headers)) mergeMiddlewareCookies(headers, requestCookies) // Seal the cookies object that'll freeze out any methods that could // mutate the underlying data. cache.cookies = RequestCookiesAdapter.seal(requestCookies) } return cache.cookies }, set cookies(value: ReadonlyRequestCookies) { cache.cookies = value }, get mutableCookies() { if (!cache.mutableCookies) { const mutableCookies = getMutableCookies(headers, onUpdateCookies) mergeMiddlewareCookies(headers, mutableCookies) cache.mutableCookies = mutableCookies } return cache.mutableCookies }, ``` Sources: [packages/next/src/server/async-storage/request-store.ts:295-322](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/request-store.ts#L295-L322) ### Draft Mode and Phase Synchronization Draft mode evaluation is handled by the `DraftModeProvider` class, which inspects incoming headers for on-demand revalidation flags and validates the prerender bypass cookie against the configured `previewModeId`. In non-production environments, `previewModeId` accepts a `'development-id'` fallback match regardless of the exact cookie hash value. | Method / Getter | Action Description | | :--- | :--- | | `isEnabled` | Evaluates whether the prerender bypass cookie matches the preview ID and on-demand revalidation is absent | | `enable()` | Sets the prerender bypass cookie (`__prerender_bypass`) into mutable cookies with `httpOnly: true` and path `/` | | `disable()` | Expires the prerender bypass cookie immediately by setting `expires: new Date(0)` | Sources: [packages/next/src/server/async-storage/draft-mode-provider.ts:11-94](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/draft-mode-provider.ts#L11-L94) > [!CAUTION] > Calling `enable()` when `previewModeId` is undefined throws an immediate invariant error because the bypass cookie value cannot be determined. Sources: [packages/next/src/server/async-storage/draft-mode-provider.ts:59-65](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/draft-mode-provider.ts#L59-L65) When request phases transition or mutable cookies are updated, `synchronizeMutableCookies` converts updated response cookies back into sealed request cookies so subsequent reads reflect the mutations. ```typescript export function synchronizeMutableCookies(store: RequestStore) { // TODO: does this need to update headers as well? store.cookies = RequestCookiesAdapter.seal( responseCookiesToRequestCookies(store.mutableCookies) ) } ``` Sources: [packages/next/src/server/async-storage/request-store.ts:354-359](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/async-storage/request-store.ts#L354-L359) ## Request Data Access Enforcement ### Dynamic Resolution and Bailout Guards When application code invokes `headers()`, `cookies()`, or `draftMode()`, Next.js resolves the request data context via `workAsyncStorage` and `workUnitAsyncStorage`. If either store is missing, execution immediately invokes `throwForMissingRequestStore`. When a work store is present, calls enforce structural constraints, starting with phase validation: if a `workUnitStore` is active and `isRequestApiAllowedInCurrentPhase` evaluates to false, accessing `cookies()` or `headers()` inside an `after()` callback throws an unsupported usage error. If `workStore.forceStatic` is enabled, all dynamic enforcement logic is bypassed, returning an empty, untracked cookies or headers object. If `workStore.dynamicShouldError` is true, a `StaticGenBailoutError` is thrown, aborting static generation. Sources: [packages/next/src/server/request/cookies.ts:36-60](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/cookies.ts#L36-L60), [packages/next/src/server/request/headers.ts:43-94](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/headers.ts#L43-L94) > [!WARNING] > Accessing `cookies()` or `headers()` inside a `"use cache"` block or an `unstable_cache` invocation throws specialized cache error messages (`createCookiesInUseCacheError`, `createHeadersInUseCacheError`, or their unstable counterparts) to prevent non-deterministic dynamic reads inside cached boundaries. Sources: [packages/next/src/server/request/cookies.ts:61-70](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/cookies.ts#L61-L70), [packages/next/src/server/request/headers.ts:62-72](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/headers.ts#L62-L72) ### Work Unit Store Resolution Branches Depending on the specific `workUnitStore.type`, request data access follows distinct execution branches that determine whether data is tracked, delayed, or rejected. | Work Unit Store Type | `cookies()` Behavior | `headers()` Behavior | | :--- | :--- | :--- | | `'cache'` / `'unstable-cache'` | Throws use-cache or unstable-cache error | Throws use-cache or unstable-cache error | | `'build-time-generator'` | Throws wrong-context build time error | Throws wrong-context build time error | | `'prerender'` | Returns hanging session data promise | Returns hanging session data promise | | `'prerender-client'` / `'validation-client'` | Throws `InvariantError` (Client Component usage) | Throws `InvariantError` (Client Component usage) | | `'prerender-legacy'` | Interrupts static generation (`throwToInterruptStaticGeneration`) | Interrupts static generation (`throwToInterruptStaticGeneration`) | | `'prerender-runtime'` | Delays via `stagedRendering` or returns untracked | Delays via `stagedRendering` or returns untracked | | `'private-cache'` | Returns untracked `workUnitStore.cookies` | Returns untracked `workUnitStore.headers` | | `'request'` | Tracks dynamic data and returns mutable or readonly cookies | Tracks dynamic data and returns headers | Sources: [packages/next/src/server/request/cookies.ts:61-142](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/cookies.ts#L61-L142), [packages/next/src/server/request/headers.ts:62-153](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/headers.ts#L62-L153) ### Draft Mode Access and Mutation Tracking The `draftMode()` function returns a promise resolving to a `DraftMode` instance. Accessing `.isEnabled` or invoking `.enable()` and `.disable()` triggers specific enforcement paths. In development environments without a prefetch request, `draftMode()` returns a proxied promise instrumented with `createDraftModeWithDevWarnings` that logs errors if properties are accessed synchronously without unwrapping the promise via `await` or `React.use()`. ```typescript function createDraftModeWithDevWarnings( underlyingProvider: null | DraftModeProvider, route: undefined | string ): Promise { const instance = new DraftMode(underlyingProvider) const promise = Promise.resolve(instance) const proxiedPromise = new Proxy(promise, { get(target, prop, receiver) { switch (prop) { case 'isEnabled': warnForSyncAccess(route, `\`draftMode().${prop}\``) break case 'enable': case 'disable': { warnForSyncAccess(route, `\`draftMode().${prop}()\``) break } default: { // We only warn for well-defined properties of the draftMode object. } } return ReflectAdapter.get(target, prop, receiver) }, }) return proxiedPromise } ``` Sources: [packages/next/src/server/request/draft-mode.ts:118-146](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L118-L146) When `.enable()` or `.disable()` is called, `trackDynamicDraftMode` verifies that the current work unit phase is not `'after'`, throws a `StaticGenBailoutError` if `dynamicShouldError` is enabled, and handles cache and prerender boundaries: - `'cache'` and `'private-cache'` throw `createDraftModeMutationInUseCacheError`. - `'unstable-cache'` throws `createDraftModeMutationInUnstableCacheError`. - `'prerender'` and `'prerender-runtime'` trigger an abort and throw synchronous request access errors requiring `await connection()`. - `'prerender-legacy'` sets `workUnitStore.revalidate = 0` and throws a `DynamicServerError`. Sources: [packages/next/src/server/request/draft-mode.ts:194-271](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L194-L271) ## Context Propagation Across Tasks ### Test Modes and Request Context Propagation Next.js propagates test parameters, proxy routing ports, and test data across asynchronous task boundaries using specialized `AsyncLocalStorage` instances. The test mode infrastructure defines `TestReqInfo` objects containing a request URL, `proxyPort` number, and `testData` string, extracted from incoming requests via `TestRequestReader` implementations. ```typescript export interface TestReqInfo { url: string proxyPort: number testData: string } ``` Sources: [packages/next/src/experimental/testmode/context.ts:3-7](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/experimental/testmode/context.ts#L3-L7) The `withRequest` helper checks for the presence of the `next-test-proxy-port` header on incoming requests. If found, it runs the provided asynchronous or synchronous callback within the `testStorage` AsyncLocalStorage context; otherwise, it executes the callback directly. ```typescript function extractTestInfoFromRequest( req: R, reader: TestRequestReader ): TestReqInfo | undefined { const proxyPortHeader = reader.header(req, 'next-test-proxy-port') if (!proxyPortHeader) { return undefined } const url = reader.url(req) const proxyPort = Number(proxyPortHeader) const testData = reader.header(req, 'next-test-data') || '' return { url, proxyPort, testData } } export function withRequest( req: R, reader: TestRequestReader, fn: () => T ): T { const testReqInfo = extractTestInfoFromRequest(req, reader) if (!testReqInfo) { return fn() } return testStorage.run(testReqInfo, fn) } ``` Sources: [packages/next/src/experimental/testmode/context.ts:16-40](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/experimental/testmode/context.ts#L16-L40) To retrieve the current test context, `getTestReqInfo` checks the active `testStorage` store first, falling back to an explicit request extraction if optional parameters are provided. ```typescript export function getTestReqInfo( req?: R, reader?: TestRequestReader ): TestReqInfo | undefined { const testReqInfo = testStorage.getStore() if (testReqInfo) { return testReqInfo } if (req && reader) { return extractTestInfoFromRequest(req, reader) } return undefined } ``` Sources: [packages/next/src/experimental/testmode/context.ts:42-54](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/experimental/testmode/context.ts#L42-L54) ### Tracing Spans and Platform Contexts Request tracing spans and platform-provided request contexts bridge low-level server initialization and runtime execution via dedicated storage layers. [Request insights](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/development/request-insights) identity tracking (`RequestInsightsIdentity`) covers the portion of `BaseServer` request handling that executes before App Render initializes work storage (`workAsyncStorage`). ```typescript export type RequestInsightsIdentity = { requestId: string kind?: RequestInsightKind htmlRequestId: string url: string | undefined } ``` Sources: [packages/next/src/server/lib/trace/request-insights-identity.ts:5-10](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/trace/request-insights-identity.ts#L5-L10) This metadata is managed through a global AsyncLocalStorage store instance initialized via `request-insights-identity-storage`. ```typescript // This storage covers the part of BaseServer request handling that runs before // App Render creates workAsyncStorage. Once available, workStore remains the // primary identity source for locally recorded spans. function getRequestInsightsIdentityStorage(): AsyncLocalStorage { return getOrCreateGlobalAsyncLocalStorage('request-insights-identity-storage') } export function runWithRequestInsightsIdentity( identity: RequestInsightsIdentity, fn: () => T ): T { return getRequestInsightsIdentityStorage().run(identity, fn) } export function getRequestInsightsIdentity(): | RequestInsightsIdentity | undefined { return getRequestInsightsIdentityStorage().getStore() } ``` Sources: [packages/next/src/server/lib/trace/request-insights-identity.ts:12-30](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/lib/trace/request-insights-identity.ts#L12-L30) Similarly, platform-provided request contexts (such as those containing `waitUntil` promises for deferred execution) are stored on `globalThis` under the symbol `@next/request-context`. `getBuiltinRequestContext` resolves this symbol from global state, while `createLocalRequestContext` wraps an `AsyncLocalStorage` instance to expose a `.get()` and `.run()` interface matching platform requirements. ```typescript export function getBuiltinRequestContext(): | BuiltinRequestContextValue | undefined { const _globalThis = globalThis as GlobalThisWithRequestContext const ctx = _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL] return ctx?.get() } const NEXT_REQUEST_CONTEXT_SYMBOL = Symbol.for('@next/request-context') type GlobalThisWithRequestContext = typeof globalThis & { [NEXT_REQUEST_CONTEXT_SYMBOL]?: BuiltinRequestContext } /** A request context provided by the platform. */ export type BuiltinRequestContext = { get(): BuiltinRequestContextValue | undefined } export type RunnableBuiltinRequestContext = BuiltinRequestContext & { run(value: BuiltinRequestContextValue, callback: () => T): T } export type BuiltinRequestContextValue = { waitUntil?: WaitUntil } export type WaitUntil = (promise: Promise) => void /** "@next/request-context" has a different signature from AsyncLocalStorage, * matching [AsyncContext.Variable](https://github.com/tc39/proposal-async-context). * We don't need a full AsyncContext adapter here, just having `.get()` is enough */ export function createLocalRequestContext(): RunnableBuiltinRequestContext { const storage = createAsyncLocalStorage() return { get: () => storage.getStore(), run: (value, callback) => storage.run(value, callback), } } ``` Sources: [packages/next/src/server/after/builtin-request-context.ts:3-41](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/after/builtin-request-context.ts#L3-L41) ## Related - [Request Lifecycle](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/request-lifecycle) - [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) --- ## Technical docs: Dynamic Rendering URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/app-render/dynamic-rendering.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering.ts) - [packages/next/src/build/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/index.ts) - [packages/next/src/build/templates/app-page-runtime.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts) - [packages/next/src/server/dynamic-rendering-utils.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/build/adapter/build-complete.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/adapter/build-complete.ts) - [packages/next/src/server/config-shared.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/config-shared.ts) - [packages/next/src/server/route-modules/app-route/module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-route/module.ts) - [packages/next/src/client/components/render-tree.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/render-tree.ts) - [packages/next/src/server/app-render/dynamic-rendering-client.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering-client.ts) - [packages/next/src/server/request/search-params.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/search-params.ts) - [packages/next/src/server/request/draft-mode.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts) - [packages/next/src/server/web/spec-extension/unstable-no-store.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/unstable-no-store.ts) - [packages/next/src/client/components/segment-cache/scheduler.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/scheduler.ts) - [packages/next/src/server/render.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx) - [packages/next/src/server/app-render/vary-params.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts) - [packages/next/src/server/request/params.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/params.ts) - [packages/next/src/server/request/fallback-params.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/fallback-params.ts) - [packages/next/src/server/app-render/dynamic-access-async-storage.external.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage.external.ts) - [packages/next/src/server/app-render/postponed-state.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/postponed-state.ts) - [packages/next/src/server/resume-data-cache/resume-data-cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts)
## Overview Dynamic Rendering encompasses the mechanisms Next.js uses to track runtime data access, manage partial prerendering (PPR) shells, and defer or evaluate dynamic route segments, search parameters, and draft mode states. By intercepting dynamic operations through [Async Storage](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/async-storage) execution contexts, the system coordinates [static generation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/static-generation) bailouts, generates artificial hanging promises, and accumulates varying parameters to construct and restore suspended streams in the [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) pipeline. At build time in the [Build Pipeline](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/build-pipeline), route entry configurations determine whether pages are fully static, dynamically rendered on demand, or split into static prerender shells with postponed dynamic holes. The [Server Architecture](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/server-architecture) consumes these manifests to govern cache keys, evaluate prefetch headers, and control stream output during live requests. Sources: [packages/next/src/server/app-render/dynamic-rendering.ts:1282-1293](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering.ts#L1282-L1293), [packages/next/src/server/dynamic-rendering-utils.ts:342-351](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts#L342-L351), [packages/next/src/server/app-render/postponed-state.ts:84-87](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/postponed-state.ts#L84-L87) ## Dynamic Tracking Mechanics ### Validation and Bailout Enforcement The server evaluates execution paths using validation states and store checks to trigger static generation bailouts or runtime errors when disallowed dynamic access occurs. Functions such as `throwIfDisallowedDynamic` and `throwIfDisallowedDynamicInStaticRoute` inspect prelude states, dynamic error collections, and viewport flags to determine whether a route can produce a static shell or must terminate with a `StaticGenBailoutError`. ```typescript export function throwIfDisallowedDynamicInStaticRoute( workStore: WorkStore, prelude: PreludeState, dynamicValidation: DynamicValidationState, serverDynamic: DynamicTrackingState, isFallbackShell: boolean, allowEmptyStaticShell: boolean, isServerPartial: boolean ): void { const reasons = getDisallowedReasonsInStaticRoute( workStore, prelude, dynamicValidation, serverDynamic, isFallbackShell, allowEmptyStaticShell, isServerPartial ) if (reasons.length > 0) { for (const reason of reasons) { logDisallowedDynamicError(workStore, reason) } throw new StaticGenBailoutError() } } ``` Sources: [packages/next/src/server/app-render/dynamic-rendering.ts:1366-1390](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering.ts#L1366-L1390) > [!WARNING] > If a route produces an empty prelude (`PreludeState.Empty`) without recorded dynamic errors during validation, Next.js treats the condition as an internal tracking failure and throws an `InvariantError` rather than a standard bailout. Sources: [packages/next/src/server/app-render/dynamic-rendering.ts:1437-1447](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering.ts#L1437-L1447) ### Declarative Opt-Outs and Abort Controllers Declarative opt-outs via `unstable_noStore` inspect active work stores and evaluate work unit store types to mark scopes as dynamic, though behavior varies depending on whether the execution context operates under dynamic I/O or standard rendering modes. ```typescript export function unstable_noStore() { const callingExpression = 'unstable_noStore()' const store = workAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore() if (!store) { // This generally implies we are being called in Pages router. We should probably not support // unstable_noStore in contexts outside of `react-server` condition but since we historically // have not errored here previously, we maintain that behavior for now. return } else if (store.forceStatic) { return } else { store.isUnstableNoStore = true if (workUnitStore) { switch (workUnitStore.type) { case 'prerender': case 'prerender-client': case 'validation-client': case 'prerender-runtime': // unstable_noStore() is a noop in Dynamic I/O. return case 'prerender-legacy': case 'request': case 'cache': case 'private-cache': case 'unstable-cache': case 'build-time-generator': break default: workUnitStore satisfies never } } markCurrentScopeAsDynamic(store, workUnitStore, callingExpression) } } ``` Sources: [packages/next/src/server/web/spec-extension/unstable-no-store.ts:20-54](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/unstable-no-store.ts#L20-L54) | Work Unit Store Type | Behavior in `unstable_noStore()` | | :--- | :--- | | `prerender`, `prerender-client`, `validation-client`, `prerender-runtime` | No-op under Dynamic I/O | | `prerender-legacy`, `request`, `cache`, `private-cache`, `unstable-cache`, `build-time-generator` | Marks current scope as dynamic | Sources: [packages/next/src/server/web/spec-extension/unstable-no-store.ts:33-47](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/web/spec-extension/unstable-no-store.ts#L33-L47) Additionally, `abortOnDynamicAccess` interacts with `dynamicAccessAsyncStorage` to abort ongoing fetches or cache reads when runtime or fallback parameter dependencies are detected. ```typescript export function abortOnDynamicAccess( reason: DynamicAccessReason, error: Error ) { const store = dynamicAccessAsyncStorageInstance.getStore() if (store !== undefined) { // A cache may read both kinds of data before cancellation finishes. Only // fallback-only dependencies can become static when the params are known. if (store.reason !== 'runtime') { store.reason = reason } store.abortController.abort(error) } } ``` Sources: [packages/next/src/server/app-render/dynamic-access-async-storage.external.ts:16-29](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-access-async-storage.external.ts#L16-L29) ## Hanging Promises Implementation ### Artificial Unresolved Promises and Staged Tracking When Next.js encounters dynamic hooks or runtime data access during pre-rendering or static generation stages, it creates artificial unresolved promises to suspend rendering until dynamic stages or client hydration occur. Functions such as `makeHangingPromise` and `makeUnknownRuntimeDataHangingPromise` construct promises tied to an abort signal and an error expression, optionally tracking URL data or session data access via `workUnitStore`. ```typescript expression: string, workUnitStore: WorkUnitStore | null ): Promise { const promise = makeHangingPromiseWithError( signal, new HangingPromiseRejectionError(route, expression) ) if (workUnitStore === null) { return promise } return trackPromiseUsed( promise, trackURLDataAccessed.bind(null, workUnitStore, expression) ) } ``` Sources: [packages/next/src/server/dynamic-rendering-utils.ts:168-182](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts#L168-L182) Runtime data tracking relies on `PrerenderDataKind` constants to classify whether accessed data affects session storage, URL parameters, or fallback parameters. The internal `trackRuntimeDataAccessed` function inspects the active `workUnitStore` stage to determine whether to deopt the shell, the prefetch, or both. ```typescript const enum PrerenderDataKind { SessionData = 1, UrlData = 2, FallbackParams = 3, } ``` Sources: [packages/next/src/server/dynamic-rendering-utils.ts:353-357](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts#L353-L357) | Prerender Data Kind Value | Constant Name | Target Deopt Scope | | :--- | :--- | :--- | | `1` | `SessionData` | Shell and Prefetch | | `2` | `UrlData` | Prefetch only | | `3` | `FallbackParams` | Prefetch or transient upgradeable fallback | Sources: [packages/next/src/server/dynamic-rendering-utils.ts:354-356](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts#L354-L356), [packages/next/src/server/dynamic-rendering-utils.ts:402-485](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts#L402-L485) > [!NOTE] > Accesses occurring after `RenderStage.NavigationStatic` are ignored because the purpose of runtime tracking is to evaluate whether a runtime prefetch provides more complete data than a static prefetch. Sources: [packages/next/src/server/dynamic-rendering-utils.ts:379-387](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dynamic-rendering-utils.ts#L379-L387) ### Client Hook Hanging Promises and Work Unit Validation On the client-side app rendering and routing context, functions like `useDynamicRouteParams` and `useDynamicSearchParams` evaluate active work unit store types to suspend component execution. When running inside a `prerender-client` context with cache component semantics, these hooks invoke `React.use()` with a hanging promise created via `makeClientHookHangingPromise`. ```typescript export function useDynamicRouteParams(expression: string) { const workStore = workAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore() if (workStore && workUnitStore) { switch (workUnitStore.type) { case 'prerender-client': { const fallbackParams = workUnitStore.fallbackRouteParams if (fallbackParams && fallbackParams.size > 0) { // We are in a prerender with cacheComponents semantics. We are going to // hang here and never resolve. This will cause the currently // rendering component to effectively be a dynamic hole. React.use( makeClientHookHangingPromise( workUnitStore.renderSignal, new ClientHookDynamicError(workStore.route, expression) ) ) } break ``` Sources: [packages/next/src/server/app-render/dynamic-rendering-client.ts:27-46](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering-client.ts#L27-L46) | Work Unit Store Type | `useDynamicRouteParams` Behavior | `useDynamicSearchParams` Behavior | | :--- | :--- | :--- | | `prerender-client` | Suspends via hanging promise if fallback parameters exist | Suspends via hanging promise | | `prerender` / `prerender-runtime` | Throws `InvariantError` | Throws `InvariantError` | | `validation-client` | Bypasses fallback route parameter checks | Bypasses hanging promise for validation | | `cache` / `private-cache` / `unstable-cache` | Throws `InvariantError` | Throws `InvariantError` | | `build-time-generator` | Throws `InvariantError` mentioning function name | Throws `InvariantError` mentioning function name | | `request` | No-op | No-op | Sources: [packages/next/src/server/app-render/dynamic-rendering-client.ts:31-73](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering-client.ts#L31-L73), [packages/next/src/server/app-render/dynamic-rendering-client.ts:93-135](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering-client.ts#L93-L135) > [!WARNING] > Calling search parameter or dynamic route parameter hooks from a server component during standard server prerendering triggers an `InvariantError`, as Next.js expects these expressions to be intercepted before server component inclusion. Sources: [packages/next/src/server/app-render/dynamic-rendering-client.ts:48-51](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering-client.ts#L48-L51), [packages/next/src/server/app-render/dynamic-rendering-client.ts:119-123](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dynamic-rendering-client.ts#L119-L123) ## Fallback Parameters Resolution ### Staged Fallback Parameters and Segment Placeholders ```typescript export type OpaqueFallbackRouteParams = ReadonlyMap /** * Creates an opaque fallback route params object from the fallback route params. * * @param fallbackRouteParams the fallback route params * @returns the opaque fallback route params */ export function createOpaqueFallbackRouteParams( fallbackRouteParams: readonly FallbackRouteParam[] ): OpaqueFallbackRouteParams | null { // If there are no fallback route params, we can return early. if (fallbackRouteParams.length === 0) return null // As we're creating unique keys for each of the dynamic route params, we only // need to generate a unique ID once per request because each of the keys will // be also be unique. const uniqueID = Math.random().toString(16).slice(2) const keys = new Map() // Generate a unique key for the fallback route param, if this key is found // in the static output, it represents a bug in cache components. for (const { paramName } of fallbackRouteParams) { keys.set(paramName, `%%drp:${paramName}:${uniqueID}%%`) } return keys } ``` Sources: [packages/next/src/server/request/fallback-params.ts:13-41](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/fallback-params.ts#L13-L41) > [!NOTE] > Opaque fallback route parameters map unknown parameter names to unique randomized placeholder identifiers (`%%drp:${paramName}:${uniqueID}%%`). These placeholders prevent unprerendered dynamic segments from leaking into rendered UI during static shell generation. Sources: [packages/next/src/server/request/fallback-params.ts:9-41](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/fallback-params.ts#L9-L41) ```typescript export function getStagedFallbackParams(route: { fallbackRouteParams: readonly FallbackRouteParam[] | undefined remainingPrerenderableParams?: readonly FallbackRouteParam[] throwOnEmptyStaticShell?: boolean }): OpaqueFallbackRouteParams | null { const { fallbackRouteParams, remainingPrerenderableParams } = route if (!fallbackRouteParams?.length) { return null } if (route.throwOnEmptyStaticShell === undefined) { throw new InvariantError( 'Expected throwOnEmptyStaticShell for a route with fallback params' ) } // A required shell keeps all of its fallback params deferred. if (route.throwOnEmptyStaticShell || !remainingPrerenderableParams?.length) { return createOpaqueFallbackRouteParams(fallbackRouteParams) } return createOpaqueFallbackRouteParams( fallbackRouteParams.filter( (param) => !remainingPrerenderableParams.some( (prerenderableParam) => prerenderableParam.paramName === param.paramName ) ) ) } ``` Sources: [packages/next/src/server/request/fallback-params.ts:56-86](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/fallback-params.ts#L56-L86) | Helper Function Name | Input Signature | Purpose / Behavior | | :--- | :--- | :--- | | `createOpaqueFallbackRouteParams` | `fallbackRouteParams: readonly FallbackRouteParam[]` | Generates a randomized `OpaqueFallbackRouteParams` map assigning unique wrapper strings to each parameter name. | | `getStagedFallbackParams` | `route: { fallbackRouteParams, remainingPrerenderableParams?, throwOnEmptyStaticShell? }` | Selects which fallback parameters are deferred for a given target shell based on build metadata and remaining prerenderable parameters. | | `buildDynamicSegmentPlaceholder` | `param: Pick` | Constructs bracketed dynamic segment expressions based on parameter repeat and optional properties. | | `getPlaceholderFallbackRouteParams` | `params: Record \| undefined, fallbackRouteParams: readonly FallbackRouteParam[]` | Filters fallback parameters whose active values match generated dynamic segment placeholders. | | `getFallbackRouteParams` | `page: string, routeModule: AppPageRouteModule` | Parses the normalized route, extracts pathname segments from the loader tree, and resolves unknown parameters. | Sources: [packages/next/src/server/request/fallback-params.ts:21-165](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/fallback-params.ts#L21-L165) > [!IMPORTANT] > When `throwOnEmptyStaticShell` is true or no `remainingPrerenderableParams` exist, `getStagedFallbackParams` defers all fallback parameters because the required shell requires a non-empty prelude matching the exact validated shape. Sources: [packages/next/src/server/request/fallback-params.ts:72-75](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/fallback-params.ts#L72-L75) ## Draft Mode Tracking ### Work Unit Scopes and Execution Contexts ```typescript switch (workUnitStore.type) { case 'prerender-runtime': { // TODO(runtime-ppr): does it make sense to delay this? normally it's always microtasky const { stagedRendering } = workUnitStore if (stagedRendering) { return stagedRendering.delayUntilStage( RENDER_STAGES_BY_DATA_KIND.sessionData, 'draftMode', new DraftMode(workUnitStore.draftMode) ) } else { return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore) } } case 'request': return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore) case 'cache': case 'private-cache': case 'unstable-cache': // Inside of `"use cache"` or `unstable_cache`, draft mode is available if // the outmost work unit store is a request store (or a runtime prerender), // and if draft mode is enabled. const draftModeProvider = getDraftModeProviderForCacheScope( workStore, workUnitStore ) if (draftModeProvider) { return createOrGetCachedDraftMode(draftModeProvider, workStore) } // Otherwise, we fall through to providing an empty draft mode. // eslint-disable-next-line no-fallthrough case 'prerender': case 'prerender-legacy': // Return empty draft mode return createOrGetCachedDraftMode(null, workStore) case 'prerender-client': case 'validation-client': { const exportName = '`draftMode`' throw new InvariantError( `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.` ) } case 'build-time-generator': throw new Error( `Route ${workStore.route} used \`${callingExpression}()\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context` ) default: return workUnitStore satisfies never } ``` Sources: [packages/next/src/server/request/draft-mode.ts:40-92](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L40-L92) | Work Unit Type | Action / Behavior on `draftMode()` Access | | :--- | :--- | | `prerender-runtime` | Delays until session data stage via `stagedRendering.delayUntilStage`, or retrieves cached draft mode. | | `request` | Resolves or creates cached draft mode via `createOrGetCachedDraftMode`. | | `cache`, `private-cache`, `unstable-cache` | Resolves provider via `getDraftModeProviderForCacheScope` if enclosed by a valid request store or runtime prerender. | | `prerender`, `prerender-legacy` | Returns an empty draft mode instance. | | `prerender-client`, `validation-client` | Throws an `InvariantError` indicating `draftMode` must not be used within Client Components. | | `build-time-generator` | Throws an `Error` because build-time execution lacks an HTTP request context. | Sources: [packages/next/src/server/request/draft-mode.ts:40-92](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L40-L92) > [!CAUTION] > Invoking `draftMode()` within Client Components (`prerender-client` or `validation-client`) immediately throws an `InvariantError`, as Next.js restricts draft mode hooks to server contexts. Sources: [packages/next/src/server/request/draft-mode.ts:78-84](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L78-L84) ### Mutation Tracking and Bailout Handling ```typescript function trackDynamicDraftMode(expression: string, constructorOpt: Function) { const workStore = workAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore() if (workStore) { // We have a store we want to track dynamic data access to ensure we // don't statically generate routes that manipulate draft mode. if (workUnitStore?.phase === 'after') { throw new Error( `Route ${workStore.route} used "${expression}" inside \`after()\`. The enabled status of \`draftMode()\` can be read inside \`after()\` but you cannot enable or disable \`draftMode()\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after` ) } if (workStore.dynamicShouldError) { throw new StaticGenBailoutError( `Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` ) } if (workUnitStore) { switch (workUnitStore.type) { case 'cache': case 'private-cache': { const error = createDraftModeMutationInUseCacheError( workStore.route, expression ) Error.captureStackTrace(error, constructorOpt) applyOwnerStack(error) workStore.invalidDynamicUsageError ??= error throw error } case 'unstable-cache': throw createDraftModeMutationInUnstableCacheError( workStore.route, expression ) case 'prerender': case 'prerender-runtime': { const error = new Error( `Route ${workStore.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers` ) return abortAndThrowOnSynchronousRequestDataAccess( workStore.route, expression, error, workUnitStore ) } case 'prerender-client': case 'validation-client': const exportName = '`draftMode`' throw new InvariantError( `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.` ) case 'prerender-legacy': workUnitStore.revalidate = 0 const err = new DynamicServerError( `Route ${workStore.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` ) workStore.dynamicUsageDescription = expression workStore.dynamicUsageStack = err.stack throw err case 'request': trackDynamicDataInDynamicRender(workUnitStore) break case 'build-time-generator': throw new Error( `Route ${workStore.route} used \`${expression}\` inside \`${workUnitStore.functionName}\`. This is not supported because \`${workUnitStore.functionName}\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context` ) default: workUnitStore satisfies never } } } ``` Sources: [packages/next/src/server/request/draft-mode.ts:194-271](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L194-L271) | Work Unit Store Type | Mutation Response (`trackDynamicDraftMode`) | | :--- | :--- | | `cache`, `private-cache` | Throws a mutation error created by `createDraftModeMutationInUseCacheError`. | | `unstable-cache` | Throws a mutation error created by `createDraftModeMutationInUnstableCacheError`. | | `prerender`, `prerender-runtime` | Aborts and throws due to synchronous request data access without `await connection()`. | | `prerender-legacy` | Sets `revalidate = 0` and throws a `DynamicServerError`. | | `request` | Tracks dynamic data access via `trackDynamicDataInDynamicRender`. | | `build-time-generator` | Throws an error prohibiting runtime API use inside build-time generator functions. | Sources: [packages/next/src/server/request/draft-mode.ts:213-267](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L213-L267) > [!WARNING] > Attempting to enable or disable draft mode inside an `after()` execution block triggers an error because draft mode status can only be read, not mutated, post-response. Sources: [packages/next/src/server/request/draft-mode.ts:201-205](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/request/draft-mode.ts#L201-L205) ## Vary Params Accumulation ### VaryParamsAccumulator Mechanics ```typescript export class VaryParamsAccumulator implements AsyncIterable { private _resolve: ((result: IteratorResult) => void) | null = null private _done = false private _buffer: VaryParamId[] = [] // The set of param names already yielded. Doubles as the dedupe guard so the // same name is never emitted twice. private _seen: Set = new Set() /** * Records that a param was accessed. Yields the name into the stream the * first time it's seen; subsequent accesses of the same name are no-ops. */ add(id: VaryParamId): void { if (this._done || this._seen.has(id)) { return } this._seen.add(id) if (this._resolve !== null) { this._resolve({ value: id, done: false }) this._resolve = null } else { this._buffer.push(id) } } /** Ends the iteration. Best-effort: if skipped (e.g. on a sync-I/O abort), * the consumer simply reads the params yielded so far. */ close(): void { if (this._done) { return } this._done = true if (this._resolve !== null) { this._resolve({ value: undefined, done: true }) this._resolve = null } } [Symbol.asyncIterator](): AsyncIterator { return { next: () => { if (this._buffer.length > 0) { return Promise.resolve({ value: this._buffer.shift()!, done: false }) } if (this._done) { return Promise.resolve({ value: undefined, done: true }) } return new Promise>((resolve) => { this._resolve = resolve }) }, } } } ``` Sources: [packages/next/src/server/app-render/vary-params.ts:36-90](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L36-L90) | Method / Property | Type / Signature | Behavior | | :--- | :--- | :--- | | `_resolve` | `((result: IteratorResult) => void) \| null` | Pending resolver for the async iterator. | | `_done` | `boolean` | Tracks whether accumulation has been closed. | | `_buffer` | `VaryParamId[]` | Stores parameter names yielded before the iterator pulls them. | | `_seen` | `Set` | Deduplication set ensuring each parameter name is emitted at most once. | | `add()` | `(id: VaryParamId) => void` | Records a parameter access, buffering or resolving immediately. | | `close()` | `() => void` | Ends the async iterable and resolves any waiting iterator promises. | | `[Symbol.asyncIterator]()` | `() => AsyncIterator` | Returns an async iterator consuming the buffer and future additions. | Sources: [packages/next/src/server/app-render/vary-params.ts:36-90](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L36-L90) > [!NOTE] > `VaryParamsAccumulator` acts as an `AsyncIterable` serialized directly by React Flight, streaming accessed parameters incrementally so that aborted prerenders capture exactly the parameters needed for the partial response. Sources: [packages/next/src/server/app-render/vary-params.ts:13-26](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L13-L26) ### Parameter Proxies and Response Accumulation ```typescript export function createVaryingParams( accumulator: VaryParamsAccumulator, originalParamsObject: Params, optionalCatchAllParamName: string | null ): Params { if (optionalCatchAllParamName !== null) { // When there's an optional catch-all param with no value (e.g., // [[...slug]] at /), the param doesn't exist as a property on the params // object. Use a Proxy to track all param access — both existing params // and the missing optional param — including enumeration patterns like // Object.keys(), spread, for...in, and `in` checks. return new Proxy(originalParamsObject, { get(target, prop, receiver) { if (typeof prop === 'string') { if ( prop === optionalCatchAllParamName || Object.prototype.hasOwnProperty.call(target, prop) ) { accumulateVaryParam(accumulator, prop) } } return Reflect.get(target, prop, receiver) }, has(target, prop) { if (prop === optionalCatchAllParamName) { accumulateVaryParam(accumulator, optionalCatchAllParamName) } return Reflect.has(target, prop) }, ownKeys(target) { // Enumerating the params object means the user's code may depend on // which params are present, so conservatively track the optional // param as accessed. accumulateVaryParam(accumulator, optionalCatchAllParamName) return Reflect.ownKeys(target) }, }) } // When there's no optional catch-all, all params exist as properties on the // object, so we can use defineProperty getters instead of a Proxy. This is // faster because the engine can optimize property access on regular objects // more aggressively than Proxy trap calls. const underlyingParamsWithVarying: Params = {} for (const paramName in originalParamsObject) { Object.defineProperty(underlyingParamsWithVarying, paramName, { get() { accumulateVaryParam(accumulator, paramName) return originalParamsObject[paramName] }, enumerable: true, }) } return underlyingParamsWithVarying } export function createVaryingSearchParams( accumulator: VaryParamsAccumulator, originalSearchParamsObject: SearchParams ): SearchParams { // Search params have no fixed schema, so any access — missing-key reads, `in` // checks, or enumeration — must register as varying. A Proxy is required // (rather than per-property getters) so that enumeration of an empty // searchParams object still triggers a vary. All accesses bucket into the // single search params id; the segment is keyed by the whole query string. // TODO: Split into per-param tracking if the cache key evolves. return new Proxy(originalSearchParamsObject, { get(target, prop, receiver) { if (typeof prop === 'string') { accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID) } return Reflect.get(target, prop, receiver) }, has(target, prop) { if (typeof prop === 'string') { accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID) } return Reflect.has(target, prop) }, ownKeys(target) { ``` Sources: [packages/next/src/server/app-render/vary-params.ts:205-289](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L205-L289) | Function | Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `createResponseVaryParamsAccumulator` | None | `ResponseVaryParamsAccumulator` | Creates top-level `head`, `rootParams`, and a `segments` set. | | `createVaryParamsAccumulator` | None | `VaryParamsAccumulator \| null` | Allocates and registers a new segment accumulator in the current work unit. | | `createVaryingParams` | `accumulator, originalParamsObject, optionalCatchAllParamName` | `Params` | Returns a Proxy for optional catch-alls or `defineProperty` getters for standard params. | | `createVaryingSearchParams` | `accumulator, originalSearchParamsObject` | `SearchParams` | Wraps search parameters in a Proxy recording `SEARCH_PARAMS_VARY_ID`. | | `finishAccumulatingVaryParams` | `responseAccumulator` | `void` | Closes `head`, `rootParams`, and all route segment accumulators. | Sources: [packages/next/src/server/app-render/vary-params.ts:123-157](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L123-L157), [packages/next/src/server/app-render/vary-params.ts:205-289](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L205-L289), [packages/next/src/server/app-render/vary-params.ts:305-313](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L305-L313) > [!TIP] > When no optional catch-all parameter exists, `createVaryingParams` uses `Object.defineProperty` property getters rather than a Proxy, allowing JavaScript engines to optimize property access more aggressively. Sources: [packages/next/src/server/app-render/vary-params.ts:244-258](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/vary-params.ts#L244-L258) ## Postponed State Serialization ### State Layout and Serialization Workflow ```mermaid flowchart TD A["Dynamic State"] --> B{"Has Fallback Params?"} B -- Yes --> C["Serialize Fallback Params JSON"] C --> D["Construct postponedString: prefix with param length"] B -- No --> E["Construct postponedString: raw dataString"] D --> F["serializePostponedState"] E --> F F --> G["stringifyResumeDataCache"] G --> H{"Compression Enabled?"} H -- Yes --> I["deflateResumeDataCache (zlib base64)"] H -- No --> J["Keep Raw JSON String"] I --> K["Concatenate: length prefix and cache payload"] J --> K ``` Sources: [packages/next/src/server/app-render/postponed-state.ts:88-164](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/postponed-state.ts#L88-L164) | Function | Parameters | Return Type | Description | | :--- | :--- | :--- | :--- | | `serializePostponedState` | `postponedString, resumeDataCache, isCacheComponentsEnabled, maxPostponedStateSizeBytes, disableResumeDataCacheCompression` | `Promise` | Prefixes postponed payload with length, serializes and optionally compresses resume data cache via zlib. | | `getDynamicHTMLPostponedState` | `postponed, preludeState, fallbackRouteParams, resumeDataCache, isCacheComponentsEnabled, maxPostponedStateSizeBytes, disableResumeDataCacheCompression` | `Promise` | Encodes React postponed state, prelude marker state, and fallback route parameters into a string. | | `getDynamicDataPostponedState` | `resumeDataCache, isCacheComponentsEnabled, maxPostponedStateSizeBytes, disableResumeDataCacheCompression, fallbackRouteParams` | `Promise` | Generates postponed state for dynamic data access without React HTML-resume requirements. | | `parsePostponedState` | `state, maxPostponedStateSizeBytes, disableResumeDataCacheCompression` | `PostponedState` | Parses serialized postponed string back into `DynamicDataPostponedState` or `DynamicHTMLPostponedState`. | | `parseResumeDataCacheFromPostponedState` | `state, maxPostponedStateSizeBytes, disableResumeDataCacheCompression` | `RenderResumeDataCache` | Extracts and parses the `RenderResumeDataCache` portion from a postponed state string. | | `isEmptyHTMLPrelude` | `state` | `boolean` | Quickly checks whether the static shell produced zero bytes before encountering a dynamic hole. | Sources: [packages/next/src/server/app-render/postponed-state.ts:88-192](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/postponed-state.ts#L88-L192), [packages/next/src/server/app-render/postponed-state.ts:225-327](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/postponed-state.ts#L225-L327), [packages/next/src/server/app-render/postponed-state.ts:392-428](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/postponed-state.ts#L392-L428) > [!NOTE] > Next.js restricts runtime execution environment context by enforcing that `stringifyResumeDataCache`, `deflateResumeDataCache`, and `createRenderResumeDataCache` throw an `InvariantError` if invoked inside the `edge` runtime. Sources: [packages/next/src/server/resume-data-cache/resume-data-cache.ts:145-149](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts#L145-L149), [packages/next/src/server/resume-data-cache/resume-data-cache.ts:181-185](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts#L181-L185), [packages/next/src/server/resume-data-cache/resume-data-cache.ts:253-257](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts#L253-L257) ### Resume Data Cache Structures and Decompression Limits ```typescript export interface RenderResumeDataCache { /** * Discriminator. `false` means this cache is read-only and cannot be filled * with new entries. Used by `ResumeDataCache` consumers to narrow the union * via standard discriminated-union narrowing (e.g. `if * (resumeDataCache.mutable)`). */ readonly mutable: false /** * A read-only Map store for values cached by the 'use cache' React hook. * The 'set' operation is omitted to enforce immutability. */ readonly cache: Omit /** * A read-only Map store for cached fetch responses. * The 'set' operation is omitted to enforce immutability. */ readonly fetch: Omit /** * A read-only Map store for encrypted bound args of inline server functions. * The 'set' operation is omitted to enforce immutability. */ readonly encryptedBoundArgs: Omit /** * A read-only Map store for decrypted bound args of inline server functions. * This is only intended for in-memory usage during pre-rendering, and must * not be persisted in the resume store. The 'set' operation is omitted to * enforce immutability. */ readonly decryptedBoundArgs: Omit /** * A read-only in-memory Map store for rendered `ImageResponse` array buffers. * This is only intended for in-memory usage during pre-rendering, and must * not be persisted in the resume store. The 'set' operation is omitted to * enforce immutability. */ readonly imageResponses: Omit } /** * A mutable version of the resume data cache used during pre-rendering. * This cache allows both reading and writing of cached values. */ export interface PrerenderResumeDataCache { /** * Discriminator. `true` means this cache is mutable and can be filled with * new entries during this prerender. Used by `ResumeDataCache` consumers to * narrow the union via standard discriminated-union narrowing (e.g. * `if (resumeDataCache.mutable)`). */ readonly mutable: true /** * A mutable Map store for values cached by the 'use cache' React hook. * Supports both 'get' and 'set' operations to build the cache during * pre-rendering. */ readonly cache: UseCacheCacheStore /** * A mutable Map store for cached fetch responses. * Supports both 'get' and 'set' operations to build the cache during * pre-rendering. */ readonly fetch: FetchCacheStore /** * A mutable Map store for encrypted bound args of inline server functions. * Supports both 'get' and 'set' operations to build the cache during * pre-rendering. */ readonly encryptedBoundArgs: EncryptedBoundArgsCacheStore /** * A mutable Map store for decrypted bound args of inline server functions. ``` Sources: [packages/next/src/server/resume-data-cache/resume-data-cache.ts:17-116](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts#L17-L116) > [!WARNING] > When decompressing a persisted resume data cache using `createRenderResumeDataCache`, the maximum decompressed size defaults to `500 * 1024 * 1024` bytes (or 5 times `maxPostponedStateSizeBytes` if configured), throwing an `ERR_BUFFER_TOO_LARGE` error if breached to protect against zip-bomb payloads. Sources: [packages/next/src/server/resume-data-cache/resume-data-cache.ts:287-312](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/resume-data-cache/resume-data-cache.ts#L287-L312) ## Runtime Postponed Execution ### Shell Streaming and Resume Orchestration ```mermaid flowchart TD A["Incoming Request"] --> B{"Has Postponed State?"} B -- Yes --> C["Read Body with Size Limit"] C --> D{"Size Exceeded?"} D -- Yes --> E["Return 413 Payload Too Large"] D -- No --> F["Decode UTF-8 Postponed State"] B -- No --> G["Evaluate PPR Route & Query"] F --> H["Set Request Meta 'postponed'"] H --> I["Determine isRoutePPREnabled"] G --> I I --> J{"Streaming Metadata Supported?"} J -- No --> K["Force Dynamic PPR Render"] J -- Yes --> L["Proceed with PPR Execution"] ``` Sources: [packages/next/src/build/templates/app-page-runtime.ts:425-441](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L425-L441), [packages/next/src/build/templates/app-page-runtime.ts:481-494](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L481-L494), [packages/next/src/build/templates/app-page-runtime.ts:561-570](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L561-L570) When an application page handles a request, the runtime inspects the incoming body for serialized postponed state when running in minimal mode or resuming execution. The `maxPostponedStateSize` configuration governs how large the incoming suspended state payload can grow before the server rejects it. If the buffer read via `readBodyWithSizeLimit` returns `null`, the request aborts immediately with a `413` status code, emitting an error message derived from `getPostponedStateExceededErrorMessage`. Sources: [packages/next/src/build/templates/app-page-runtime.ts:425-441](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L425-L441) > [!WARNING] > A Partially Static (PPR) shell closes its document head before any dynamic render resumes. If the user agent is identified as an HTML-limited bot via `shouldServeStreamingMetadata`, blocking metadata resolved during resume would be emitted after the head. In response, Next.js forces a dynamic PPR render by setting `shouldForceDynamicPPRRender` to `true`, ensuring blocking metadata remains in the initial document head. Sources: [packages/next/src/build/templates/app-page-runtime.ts:561-570](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L561-L570) ### Testing APIs and Client Cache Interaction In addition to serving standard page responses, the runtime integrates with the [Segment Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/segment-cache) scheduler to serve prefetched static segments while dynamically evaluating missed branches on navigation. ```typescript const hasDebugStaticShellQuery = process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' && typeof query.__nextppronly !== 'undefined' && couldSupportPPR // When enabled, this will allow the use of the `?__nextppronly` query // to enable debugging of the fallback shell. const hasDebugFallbackShellQuery = hasDebugStaticShellQuery && query.__nextppronly === 'fallback' // Whether the testing API is exposed (dev mode or explicit flag) const exposeTestingApi = nextConfig.cacheComponents === true && (routeModule.isDev === true || nextConfig.experimental.exposeTestingApiInProductionBuild === true) ``` Sources: [packages/next/src/build/templates/app-page-runtime.ts:445-460](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L445-L460) The runtime uses `NEXT_INSTANT_TEST_COOKIE` in combination with navigation locks to evaluate whether a request represents an instant navigation test, isolating shell prefetches from runtime streaming content. On the client, `spawnDynamicRequests` and `writeDynamicDataIntoNavigationTask` parse the incoming Flight payload and update cache nodes, marking tasks as fulfilled or triggering lazy fetches when segments require additional dynamic resolution. Sources: [packages/next/src/build/templates/app-page-runtime.ts:472-478](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts#L472-L478), [packages/next/src/client/components/render-tree.ts:1328-1360](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/render-tree.ts#L1328-L1360), [packages/next/src/client/components/render-tree.ts:1895-1922](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/render-tree.ts#L1895-L1922) ## Related - [Incremental Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/incremental-cache) - [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) - [Async Storage](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/async-storage) --- ## Technical docs: App Rendering URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/app-render/create-component-tree.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-component-tree.tsx) - [packages/next/src/client/components/layout-router.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/layout-router.tsx) - [packages/next/src/client/components/render-tree.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/render-tree.ts) - [packages/next/src/build/webpack/loaders/next-app-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-app-loader/index.ts) - [packages/next/src/server/app-render/instant-validation/instant-validation.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/instant-validation/instant-validation.tsx) - [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx) - [packages/next/src/server/app-render/collect-segment-data.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx) - [packages/next/src/client/components/segment-cache/decode-server-response.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/decode-server-response.ts) - [packages/next/src/build/segment-config/app/app-segments.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts) - [packages/next/src/client/components/segment-cache/cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts) - [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts) - [packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/next-devtools/userspace/app/segment-explorer-node.tsx) - [packages/next/src/server/route-modules/app-page/module.render.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts) - [packages/next/src/shared/lib/router/utils/get-segment-param.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx)
## Overview App Rendering manages the generation, transmission, and client-side coordination of React Server Component (RSC) trees across the [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router). It bridges server-side layout and page module execution with client-side tree reconciliation, enabling partial prefetching, segment caching, and [dynamic rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering) bailouts. Sources: [packages/next/src/server/app-render/create-component-tree.tsx:139-159](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-component-tree.tsx#L139-L159), [packages/next/src/client/components/layout-router.tsx:302-318](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/layout-router.tsx#L302-L318), [packages/next/src/client/components/render-tree.ts:721-732](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/render-tree.ts#L721-L732), [packages/next/src/server/app-render/collect-segment-data.tsx:157-166](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L157-L166), [packages/next/src/build/segment-config/app/app-segments.ts:342-345](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L342-L345), [packages/next/src/server/route-modules/app-page/module.render.ts:14-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L14-L22) ## Server Component Tree Construction ### Layout and Segment Resolution The core tree construction algorithm resolves loader trees into React elements by inspecting convention modules, configuring asset injectors, and wrapping components in appropriate runtime boundaries. When assembling a route segment, the builder extracts layout, template, error, loading, not-found, forbidden, and unauthorized modules from the loader tree. Asset injectors track injected CSS, JavaScript, and font preload tags relative to the current layout scope. > [!NOTE] > When `output: "export"` is configured in `next.config.js`, any segment module resolving to `dynamic = "force-dynamic"` immediately throws a `StaticGenBailoutError` to halt static export compilation. ```tsx let dynamic = layoutOrPageMod?.dynamic if (nextConfigOutput === 'export') { if (!dynamic || dynamic === 'auto') { dynamic = 'error' } else if (dynamic === 'force-dynamic') { // force-dynamic is always incompatible with 'export'. We must interrupt the build throw new StaticGenBailoutError( `Page with \`dynamic = "force-dynamic"\` couldn't be exported. \`output: "export"\` requires all pages be renderable statically because there is no runtime server to dynamically render routes in this output format. Learn more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports` ) } } if (typeof dynamic === 'string') { // the nested most config wins so we only force-static // if it's configured above any parent that configured // otherwise if (dynamic === 'error') { workStore.dynamicShouldError = true } else if (dynamic === 'force-dynamic') { workStore.forceDynamic = true if (isPrerendering) { const err = new DynamicServerError( `Page with \`dynamic = "force-dynamic"\` won't be rendered statically.` ) workStore.dynamicUsageDescription = err.message workStore.dynamicUsageStack = err.stack throw err } } else { workStore.dynamicShouldError = false workStore.forceStatic = dynamic === 'force-static' } } ``` Sources: [packages/next/src/server/app-render/create-component-tree.tsx:304-337](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-component-tree.tsx#L304-L337) ### Client and Server Segment Root Wrapping Segment elements are wrapped differently depending on whether the target component is marked as a client component or executed as a server component. Client components receive `ClientSegmentRoot` wrappers containing parameters and slot references, whereas server components receive direct React element creation with server parameter resolution. > [!WARNING] > Root layouts containing both a children slot and at least one parallel route slot trigger error boundary wrapping with `HTTPAccessFallbackBoundary` to support unmatched parallel routes that throw `notFound()`. ```tsx if (isClientComponent) { let clientSegment: React.ReactNode if (cacheComponents) { // Params are omitted when Cache Components is enabled clientSegment = createElement(ClientSegmentRoot, { Component: SegmentComponent, slots: parallelRouteProps, serverProvidedParams: null, }) } else if (isPrerendering) { const promiseOfParams = createPrerenderParamsForClientSegment(currentParams) clientSegment = createElement(ClientSegmentRoot, { Component: SegmentComponent, slots: parallelRouteProps, serverProvidedParams: { params: currentParams, promises: [promiseOfParams], }, }) } else { clientSegment = createElement(ClientSegmentRoot, { Component: SegmentComponent, slots: parallelRouteProps, serverProvidedParams: { params: currentParams, promises: null, }, }) } ``` Sources: [packages/next/src/server/app-render/create-component-tree.tsx:939-970](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-component-tree.tsx#L939-L970) ```tsx } else { const params = createServerParamsForServerSegment( currentParams, optionalCatchAllParamName, varyParamsAccumulator ) let serverSegment: React.ReactNode if (isUseCacheFunction(SegmentComponent)) { const UseCacheLayoutComponent: ComponentType = SegmentComponent serverSegment = createElement( UseCacheLayoutComponent, { ...parallelRouteProps, params: params, $$isLayout: true, }, // Force static children here so that they're validated. // See https://github.com/facebook/react/pull/34846 parallelRouteProps.children ) } else { serverSegment = createElement( SegmentComponent, { ...parallelRouteProps, params: params, }, // Force static children here so that they're validated. // See https://github.com/facebook/react/pull/34846 parallelRouteProps.children ) } ``` Sources: [packages/next/src/server/app-render/create-component-tree.tsx:1043-1078](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-component-tree.tsx#L1043-L1078) ## Differential Tree Traversal on Navigation ### Segment Reconciliation via FlightRouterState During navigation, refresh, or action responses, the server reconciles the requested client tree state against the current loader tree using `walkTreeWithFlightRouterState`. The traversal evaluates whether route parameters, path structures, or search terms have mutated, or if an explicit refetch marker has been supplied. If a segment requires re-rendering, `createComponentTree` executes for that specific slice. If the segment matches the client's cached state, the traversal skips component rendering, accumulates required layout-level CSS and script tags, and recurses down parallel route slots. ```mermaid sequenceDiagram participant W as walkTreeWithFlightRouterState participant R as createRouteTreePrefetch participant I as createTransportTreeFromLoaderTreeImpl participant C as computeSegmentPrefetchHints participant G as getSegmentParam W->>R: createRouteTreePrefetch(...) R->>I: createTransportTreeFromLoaderTreeImpl(...) I->>C: computeSegmentPrefetchHints(...) C->>G: getSegmentParam(loaderTree[0]) ``` Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:70-155](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L70-L155), [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:300-322](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L300-L322) > [!NOTE] > `didRouteOrPathParamChange` performs a strict comparison of actual versus requested segments. For dynamic segments, it evaluates the parameter name, dynamic type, and segment value while ignoring static sibling hint arrays located at index three. ```tsx function didRouteOrPathParamChange( actualSegment: Segment, requestedSegment: Segment ): boolean { // The caller handles the page's search params separately. if ( typeof actualSegment === 'string' || typeof requestedSegment === 'string' ) { // Static segments have to match exactly. return actualSegment !== requestedSegment } // Both segments are dynamic. Compare the param name, type, and value. The // static sibling hints (index 3) aren't part of the segment's identity. return ( actualSegment[0] !== requestedSegment[0] || actualSegment[2] !== requestedSegment[2] || actualSegment[1] !== requestedSegment[1] ) } ``` Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:40-60](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L40-L60) ### Traversal and Prefetching Control Flow When a navigation request is processed, the traversal function walks down the loader tree and evaluates several branching conditions to determine whether to short-circuit component rendering or return structure-only transport nodes. ```tsx if ( isInsideSharedLayout && !experimental.isRoutePPREnabled && // If PPR is disabled, and this is a request for the route tree, then we // never render any components. Only send the router state. (parsedRequestHeaders.isRouteTreePrefetchRequest || // Otherwise, check for the presence of a `loading` component. (isPrefetch && !Boolean(modules.loading) && !hasLoadingComponentInTree(loaderTreeToFilter))) ) { // Send only the router state. // TODO: Even for a dynamic route, we should cache these responses, // because they do not contain any render data (neither segment data nor // the head). They can be made even more cacheable once we move the route // params into a separate data structure. const tree = parsedRequestHeaders.isRouteTreePrefetchRequest ? // Route tree prefetch requests contain some extra information await createRouteTreePrefetch( loaderTreeToFilter, hintTree, prefetchInliningEnabled, ctx.missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, ctx.renderOpts.notFoundParams, rootLayoutIncluded ) : await createTransportTreeFromLoaderTree( loaderTreeToFilter, hintTree, prefetchInliningEnabled, ctx.missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, ctx.renderOpts.notFoundParams, rootLayoutIncluded ) return { tree, head: [null, null], isHeadPartial: true, } } // Similar to the previous branch. This flag is sent by the client to request // only the metadata for a page. No segment data. if (flightRouterState && flightRouterState[3] === 'metadata-only') { const tree = parsedRequestHeaders.isRouteTreePrefetchRequest ? await createRouteTreePrefetch( loaderTreeToFilter, hintTree, prefetchInliningEnabled, ctx.missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, ctx.renderOpts.notFoundParams ) : await createTransportTreeFromLoaderTree( loaderTreeToFilter, hintTree, prefetchInliningEnabled, ctx.missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, ctx.renderOpts.notFoundParams, rootLayoutIncluded ) return { tree, head: rscHead, isHeadPartial: false, } } ``` Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:176-250](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L176-L250) > [!WARNING] > If partial prerendering is disabled and a prefetch request encounters a segment without a `loading` boundary, the traversal short-circuits execution and returns a router state structure without rendering components to avoid loading expensive subtrees. ```tsx (parsedRequestHeaders.isRouteTreePrefetchRequest || // Otherwise, check for the presence of a `loading` component. (isPrefetch && !Boolean(modules.loading) && !hasLoadingComponentInTree(loaderTreeToFilter))) ) { // Send only the router state. // TODO: Even for a dynamic route, we should cache these responses, // because they do not contain any render data (neither segment data nor // the head). They can be made even more cacheable once we move the route // params into a separate data structure. const tree = parsedRequestHeaders.isRouteTreePrefetchRequest ? // Route tree prefetch requests contain some extra information await createRouteTreePrefetch( loaderTreeToFilter, hintTree, prefetchInliningEnabled, ctx.missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, ctx.renderOpts.notFoundParams, rootLayoutIncluded ) : await createTransportTreeFromLoaderTree( loaderTreeToFilter, hintTree, prefetchInliningEnabled, ctx.missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, ctx.renderOpts.notFoundParams, rootLayoutIncluded ) return { tree, head: [null, null], isHeadPartial: true, } } ``` Sources: [packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx:181-220](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/walk-tree-with-flight-router-state.tsx#L181-L220) ### Dynamic Segment Parameter Inspection The traversal utility extracts and parses dynamic route segment parameters to resolve parameter names and dynamic types, including catch-all patterns and interception markers. | Segment Format Pattern | Parsed `paramType` | `repeat` | `optional` | | :--- | :--- | :--- | :--- | | `[[...name]]` | `optional-catchall` | `true` | `true` | | `[...name]` | `catchall` | `true` | `false` | | `[name]` | `dynamic` | `false` | `false` | | `(..)[...name]` | `catchall-intercepted-(..)` | `true` | `false` | | `(..)[name]` | `dynamic-intercepted-(..)` | `false` | `false` | ```tsx if (segment.startsWith('[[...') && segment.endsWith(']]')) { return { // TODO-APP: Optional catchall does not currently work with parallel routes, // so for now aren't handling a potential interception marker. paramType: 'optional-catchall', paramName: segment.slice(5, -2), } } if (segment.startsWith('[...') && segment.endsWith(']')) { return { paramType: interceptionMarker ? `catchall-intercepted-${interceptionMarker}` : 'catchall', paramName: segment.slice(4, -1), } } if (segment.startsWith('[') && segment.endsWith(']')) { return { paramType: interceptionMarker ? `dynamic-intercepted-${interceptionMarker}` : 'dynamic', paramName: segment.slice(1, -1), } } ``` Sources: [packages/next/src/shared/lib/router/utils/get-segment-param.tsx:23-48](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx#L23-L48), [packages/next/src/shared/lib/router/utils/get-segment-param.tsx:72-101](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx#L72-L101) ## Transport Tree Assembly ### Prefetch Hint Policies and Bitmask Generation Next.js builds transport-layer node structures, route trees, and prefetch hints directly from build-time loader trees using `createTransportTreeFromLoaderTree` and `createFullTransportTreeFromLoaderTree`. When prefetch inlining is enabled but no hint tree is available, `getMissingPrefetchHintPolicy` determines the fallback policy based on whether build-time prerendering or runtime prerendering is active. ```typescript export function getMissingPrefetchHintPolicy( isBuildTimePrerendering: boolean, isPrerendering: boolean, cacheComponents: boolean ): MissingPrefetchHintPolicy { if (isBuildTimePrerendering) { return 'mark-stale' } if (isPrerendering || cacheComponents) { return 'disable-prefetching' } return 'none' } ``` Sources: [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:28-46](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L28-L46) `computeSegmentPrefetchHints` evaluates segment-local configurations by inspecting layout or page modules for `instant` and `prefetch` exports. It unions build-time hints from `hintTree`, marks root layout boundaries, identifies closed parameters via `getSegmentParam`, and folds subtree bits upward using `propagateSubtreeBits`. | Missing Prefetch Hint Policy | Condition | Behavior / Prefetch Hint Flag | | :--- | :--- | :--- | | `mark-stale` | `isBuildTimePrerendering` is true | Sets `PrefetchHint.InliningHintsStale` so the client expires the cache entry and re-fetches. | | `disable-prefetching` | `isPrerendering` or `cacheComponents` is true | Sets `PrefetchHint.PrefetchDisabled` to treat segments as unprefetchable without triggering an infinite refetch loop. | | `none` | Standard dynamic page without Cache Components | Skips the inlining hint system and lets normal prefetching proceed. | Sources: [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:33-46](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L33-L46), [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:93-147](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L93-L147) > [!CAUTION] > Fully dynamic Cache Components routes lack manifest entries, requiring the `disable-prefetching` policy fallback. Setting `InliningHintsStale` on these routes would cause an infinite re-fetch loop trying to retrieve non-existent hints. Sources: [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:37-43](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L37-L43), [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:103-111](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L103-L111) ### Transport Node Builders and Specialized Payload Creation `createTransportTreeFromLoaderTreeImpl` recursively walks parallel route slots, populates child transport nodes, and constructs either partial or full transport node structures. The module exposes targeted builder functions for router-state-only responses, prefetch streams, and error payloads. ```typescript export async function createTransportTreeFromLoaderTree( loaderTree: LoaderTree, hintTree: PrefetchHints | null, prefetchInliningEnabled: boolean, missingPrefetchHintPolicy: MissingPrefetchHintPolicy, partialPrefetching: boolean, getDynamicParamFromSegment: GetDynamicParamFromSegment, notFoundParams: readonly string[] | undefined, didFindRootLayout: boolean = false ): Promise { return createTransportTreeFromLoaderTreeImpl( loaderTree, false, hintTree, prefetchInliningEnabled, missingPrefetchHintPolicy, partialPrefetching, getDynamicParamFromSegment, didFindRootLayout, notFoundParams ) } ``` Sources: [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:240-264](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L240-L264) > [!NOTE] > `createFullTransportTreeFromLoaderTree` forces `emitSkippedData` to true, populating every node with skipped segment data via `createSkippedSegmentData()`. This structure serves error payloads where route rendering is bypassed and an error shell is attached directly to the root node data. Sources: [packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts:266-294](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-transport-tree-from-loader-tree.ts#L266-L294) ## Segment Data Collection and Prefetching ### Prerender Warm-up and Shell Boundary Measurement `collectSegmentData` initializes route traversal by warming up the module cache through a single decode of `fullPageDataBuffer` using `createFromReadableStream` wrapped with `createUnclosingPrefetchStream`. This pass extracts `pageShellByteLength` from the page payload's `a` field and determines whether runtime data was accessed by reading `u` via `readFulfilledValue`. ```typescript const pagePayload: InitialRSCPayload = await createFromReadableStream( createUnclosingPrefetchStream(streamFromBuffer(fullPageDataBuffer)), { findSourceMapURL, serverConsumerManifest, } ) await waitAtLeastOneReactRenderTask() if (pagePayload.a !== undefined) { pageShellByteLength = await pagePayload.a } if (pagePayload.u !== undefined) { runtimeDataAccessed = readFulfilledValue(pagePayload.u, false, true) } ``` Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:189-214](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L189-L214) > [!NOTE] > A pending row in `pagePayload.u` reads as `false` and appears only in aborted renders where no runtime access was recorded before abortion. A rejected row evaluates to `true` conservatively because an abort marks any still-pending rows as errored. Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:204-214](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L204-L214) ### Route Tree Traversal and Segment Task Dispatch After warm-up, `collectSegmentData` invokes `prerender` with a `PrefetchTreeData` root element, passing down `segmentTasks`, `shellStageRelease`, and configuration flags. The tree stream prelude is buffered into `treeBuffer` and stored in `resultMap` at `/_tree`, alongside `/_full` containing the entire page data response. ```typescript const prerenderResult = await prerender( , clientModules, { filterStackFrame, signal: abortController.signal, onError: onSegmentPrerenderError, } ) treeStream = prerenderResult.prelude ``` Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:271-299](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L271-L299) > [!CAUTION] > If tree prerendering throws an error, `release.resolve(false)` fires in the `finally` block to prevent spawned segment tasks from hanging indefinitely, while `Promise.allSettled(segmentTasks)` absorbs rejections so failing tasks do not mask the primary tree-render error. Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:304-320](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L304-L320) ### Segment Identity and Fallback Handling `createPrefetchTransportSegment` normalizes segment wire identities when client parameter parsing is enabled (`cacheComponents`). If `segment` is an object and `isClientParamParsingEnabled` is true, the parameter value `k` is set to `null` to ensure byte-identical, cacheable responses across different parameter values, leaving the client to parse values from the pathname. | Result Map Entry | Destination Path / Key | Content Source | | :--- | :--- | :--- | | `/_tree` | `SegmentRequestKey` (`/_tree`) | Buffered `treeStream` from `prerender` | | `/_full` | `SegmentRequestKey` (`/_full`) | Entire `fullPageDataBuffer` | | Segment Prefetches | Resolved from `segmentTasks` | Parallel `Promise.all` resolution of segment buffers | | Fake Fallback Segment | `/todo-remove-fake-segment/__PAGE__` | `Buffer.alloc(0)` emitted when no real `__PAGE__` segment exists | Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:115-127](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L115-L127), [packages/next/src/server/app-render/collect-segment-data.tsx:323-353](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L323-L353) > [!WARNING] > The build requires at least one segment path ending with `__PAGE__` to register the catch-all segment data route. When all page segments are disabled due to runtime prefetching, a dummy entry at `/todo-remove-fake-segment/__PAGE__` with an empty buffer is injected. Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:339-353](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L339-L353) ## Route Segment Configuration Inspection ### Segment Parameter Extraction and Parsing `collectSegments` orchestrates per-segment route configuration inspection for both App Page (`collectAppPageSegments`) and App Route (`collectAppRouteSegments`) modules [packages/next/src/build/segment-config/app/app-segments.ts:183-357](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L183-L357). For each segment encountered while walking the loader tree or path components, `getSegmentParam` inspects the segment string for dynamic path tokens, interception markers, and catch-all delimiters [packages/next/src/shared/lib/router/utils/get-segment-param.tsx:12-51](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx#L12-L51). The parser recognizes the following parameter types and maps them to their respective properties: | Segment Pattern | Parameter Type | `repeat` | `optional` | | :--- | :--- | :--- | :--- | | `[param]` | `dynamic` (or `dynamic-intercepted-`) | `false` | `false` | | `[...param]` | `catchall` (or `catchall-intercepted-`) | `true` | `false` | | `[[...param]]` | `optional-catchall` | `true` | `true` | Sources: [packages/next/src/shared/lib/router/utils/get-segment-param.tsx:23-49](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx#L23-L49), [packages/next/src/shared/lib/router/utils/get-segment-param.tsx:72-101](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx#L72-L101) > [!NOTE] > When an interception marker (such as `(.)`, `(..)`, `(..)(..)`, or `(...)`) prefixes a dynamic or catch-all segment, `getSegmentParam` strips the marker length before evaluating parameter brackets, appending the marker to the parameter type identifier (e.g., `catchall-intercepted-(..)`). Sources: [packages/next/src/shared/lib/router/utils/get-segment-param.tsx:13-39](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/get-segment-param.tsx#L13-L39) ### Configuration Attachment and Validation Server component modules pass through `attach`, which invokes `parseAppSegmentConfig` on the userland export object and verifies segment-level functions [packages/next/src/build/segment-config/app/app-segments.ts:76-157](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L76-L157). If `generateStaticParams` is exported, the compiler checks that the segment runtime is not set to `edge`, throwing an error if incompatible [packages/next/src/build/segment-config/app/app-segments.ts:95-117](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L95-L117). Parameter matching exports (`unstable_paramMatching` and `unstable_generateParamMatching`) undergo strict validation against `PARAM_MATCHING_MODES`: ```typescript export const PARAM_MATCHING_MODES = [ 'not-found', 'blocking', 'fallback', 'dynamic', ] as const ``` Sources: [packages/next/src/build/segment-config/app/app-segments.ts:27-32](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L27-L32) > [!WARNING] > A route cannot export both `unstable_paramMatching` and `unstable_generateParamMatching` simultaneously. Furthermore, any parameter name configured within these exports must exist within `visibleParamNames` collected from current or ancestor segments, or an error is thrown [packages/next/src/build/segment-config/app/app-segments.ts:57-61](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L57-L61), [packages/next/src/build/segment-config/app/app-segments.ts:123-127](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L123-L127). Sources: [packages/next/src/build/segment-config/app/app-segments.ts:57-66](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L57-L66), [packages/next/src/build/segment-config/app/app-segments.ts:123-127](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/segment-config/app/app-segments.ts#L123-L127) ## App Page Entry Module Execution The server entry module for App Page routes manages execution by dynamically loading the compiled route module and exposing lazy wrappers for rendering and prerendering pipelines [packages/next/src/server/route-modules/app-page/module.render.ts:6-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L6-L22). When lazy execution is invoked, `getAppPageModule()` checks whether `process.env.NEXT_MINIMAL` is enabled [packages/next/src/server/route-modules/app-page/module.render.ts:6-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L6-L12). | Function / Constant | Target Type | Behavior / Pipeline | | :--- | :--- | :--- | | `getAppPageModule()` | Helper | Evaluates environment variables and requires `./module.compiled` or throws [packages/next/src/server/route-modules/app-page/module.render.ts:6-12](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L6-L12) | | `lazyRenderAppPage` | `AppPageRender` | Invokes `renderToHTMLOrFlight` on the compiled module [packages/next/src/server/route-modules/app-page/module.render.ts:14-17](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L14-L17) | | `lazyPrerenderAppPage` | `AppPagePrerender` | Invokes `prerenderToHTMLOrFlight` on the compiled module [packages/next/src/server/route-modules/app-page/module.render.ts:19-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L19-L22) | Sources: [packages/next/src/server/route-modules/app-page/module.render.ts:6-22](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L6-L22) > [!CAUTION] > Attempting to execute `lazyRenderAppPage` or `lazyPrerenderAppPage` while `process.env.NEXT_MINIMAL` is active causes `getAppPageModule()` to throw an immediate error stating that lazy rendering cannot be used in minimal mode. Sources: [packages/next/src/server/route-modules/app-page/module.render.ts:7-9](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/app-page/module.render.ts#L7-L9) ## Related - [RSC Transport](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/rsc-transport) - [Stream Handling](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/stream-handling) - [Dynamic Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/dynamic-rendering) - [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) --- ## Technical docs: RSC Transport URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/rsc-transport
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/shared/lib/rsc-transport.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/rsc-transport.ts) - [packages/next/src/server/app-render/action-handler.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/action-handler.ts) - [packages/next/src/client/components/segment-cache/decode-server-response.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/decode-server-response.ts) - [packages/next/src/client/components/router-reducer/fetch-server-response.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/fetch-server-response.ts) - [packages/next/src/client/app-index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx) - [packages/next/src/shared/lib/app-router-types.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/app-router-types.ts) - [packages/next/src/server/app-render/use-flight-response.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/use-flight-response.tsx) - [packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts) - [packages/next/src/client/components/app-router-headers.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/app-router-headers.ts) - [packages/next/src/server/app-render/instant-validation/instant-validation.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/instant-validation/instant-validation.tsx) - [packages/next/src/client/flight-data-helpers.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/flight-data-helpers.ts) - [packages/next/src/server/app-render/encryption.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts) - [packages/next/src/server/app-render/stream-ops.node.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/stream-ops.node.ts) - [packages/next/src/build/templates/app-page-runtime.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts) - [packages/next/src/server/app-render/collect-segment-data.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx) - [packages/next/src/server/app-render/create-component-tree.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/create-component-tree.tsx) - [packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts) - [packages/next/src/server/app-render/dev-validation-error-delivery.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dev-validation-error-delivery.ts) - [packages/next/src/server/dev/serialized-errors.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/serialized-errors.ts) - [packages/next/src/build/webpack/loaders/next-flight-loader/index.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/loaders/next-flight-loader/index.ts) - [packages/next/src/server/app-render/react-server.node.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/react-server.node.ts) - [packages/next/src/server/app-render/flight-render-result.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/flight-render-result.ts) - [packages/next/src/client/components/segment-cache/cache.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/components/segment-cache/cache.ts)
## Overview RSC Transport defines the wire formats, serialization schemas, and transport tree data structures used to transmit React Server Component responses between server renderers and client routers in Next.js. It bridges server-side component tree generation with client-side ingestion, establishing the wire conventions for [Segment Cache](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/segment-cache), [Router Reducer](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/router-reducer), and [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering). Sources: [packages/next/src/shared/lib/rsc-transport.ts:1-15](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/rsc-transport.ts#L1-L15) ## Transport Protocol and Data Structures ### Transport Node Representation The transport protocol governs how React Server Component payloads are structured, serialized, and mapped between server renderers and client routers. Every transport type is prefixed with `Transport` to distinguish the wire format from client-local types like `Segment`, `RouteTree`, `CacheNode`, and `FlightRouterState`, ensuring client code converts out of transport types at the decode boundary and never stores them directly. Tree payloads are represented as hierarchical node structures (`FullTransportNode` and `PartialTransportNode`) built around a shared node shape (`TransportNodeShape`). Full response trees account for every node in the route segment hierarchy, whereas partial trees act as overlays produced during navigations, refreshes, and [server actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions). Parallel routes are structured using `Map` instances for child slots rather than plain objects to prevent megamorphic keyed access caused by hidden class variations across app-defined slot names. | Transport Node Field | Type | Description | | :--- | :--- | :--- | | `s` | `TransportSegment` | The wire segment identity for the route node. | | `d` | `TransportSegmentData` (or optional `d?`) | Segment output data; always present in full nodes, optional in partial nodes. | | `c` | `Map` (or optional) | Parallel route child slots, stored as a `Map` of slot keys to transport nodes. | | `h` | `TransportSegmentData` (or optional) | Segment-level head metadata (such as title or meta tags). | Sources: [packages/next/src/shared/lib/rsc-transport.ts:136-179](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/rsc-transport.ts#L136-L179) > [!NOTE] > `FullTransportNode` is structurally assignable to `PartialTransportNode`, allowing the union type `TransportNode` to collapse to `PartialTransportNode` for the TypeScript type checker while retaining the union spelling to document developer intent. Sources: [packages/next/src/shared/lib/rsc-transport.ts:181-188](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/rsc-transport.ts#L181-L188) ### Segment Encoding and Conversion Route segments alternate between internal representations and wire representations. A segment is encoded as either a plain string (for static segments or special keys like `PAGE_SEGMENT_KEY`) or an object carrying compressed property keys: `n` for the parameter name, `t` for the parameter type, `k` for the parameter cache key, and `s` for static siblings. ```typescript export type TransportSegment = | string | { n: string t: string k: string | null s: string } ``` Sources: [packages/next/src/shared/lib/rsc-transport.ts:259-296](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/rsc-transport.ts#L259-L296) When processing fallback prerenders where dynamic parameters are absent from the initial static shell, the client patches the transport tree by parsing parameter values directly from the rendered pathname and populating missing cache keys via `fillInFallbackTransportTree`. ```typescript function fillInFallbackTransportTree( node: FullTransportNode, pathnameParts: Array, pathnamePartsIndex: number ): FullTransportNode { const originalSegment = node.s let newSegment: TransportSegment let doesAppearInURL: boolean if (typeof originalSegment === 'string') { newSegment = originalSegment doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment) } else { const paramValue = parseDynamicParamFromURLPart( originalSegment.t, pathnameParts, pathnamePartsIndex ) newSegment = { n: originalSegment.n, t: originalSegment.t, k: getCacheKeyForDynamicParam(paramValue), s: originalSegment.s, } doesAppearInURL = true } ``` Sources: [packages/next/src/client/flight-data-helpers.ts:77-101](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/flight-data-helpers.ts#L77-L101) ## Flight Streaming and Response Generation ### Flight Stream Decoding and Consumer Manifests Server-side construction of Flight data streams involves wrapping raw React Server Component outputs into specialized render results and processing streams through `react-server-dom-webpack` client deserializers. The `getFlightStream` function retrieves or initializes responses from either Node.js readable streams or Web `ReadableStream` instances. Client reference manifests supply module mapping metadata—selecting `edgeSSRModuleMapping` for the [edge runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime) or `ssrModuleMapping` for Node.js servers, alongside client module loading configurations and debug channels. ```typescript export function getFlightStream( flightStream: Readable | BinaryStreamOf, debugStream: Readable | ReadableStream | undefined, debugEndTime: number | undefined, nonce: string | undefined ): Promise ``` Sources: [packages/next/src/server/app-render/use-flight-response.tsx:35-40](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/use-flight-response.tsx#L35-L40) > [!NOTE] > When executing under client-side prerendering or validation work units in non-edge runtimes, responses are deferred to the next tick via `process.nextTick` before being stored in the `flightResponses` `WeakMap`. Sources: [packages/next/src/server/app-render/use-flight-response.tsx:119-135](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/use-flight-response.tsx#L119-L135) ### Inlined Data Streams and Payload Instructions To transmit hydration data and incremental payload chunks outside the core React tree render, `createInlinedDataReadableStream` constructs a lazy Web `ReadableStream` that outputs inline script tag blocks. Initial bootstrap instructions, form states, and flight data payloads are serialized into JSON arrays, escaped, and pushed into the global `self.__next_f` array. | Payload Constant | Numeric Value | Description | | :--- | :--- | :--- | | `INLINE_FLIGHT_PAYLOAD_BOOTSTRAP` | `0` | Initializes the global `self.__next_f` stream buffer. | | `INLINE_FLIGHT_PAYLOAD_DATA` | `1` | Transmits stringified Flight text chunks. | | `INLINE_FLIGHT_PAYLOAD_FORM_STATE` | `2` | Supplies initial form state data. | | `INLINE_FLIGHT_PAYLOAD_BINARY` | `3` | Transmits binary chunks encoded in base64 when UTF-8 decoding fails. | Sources: [packages/next/src/server/app-render/use-flight-response.tsx:14-18](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/use-flight-response.tsx#L14-L18), [packages/next/src/server/app-render/use-flight-response.tsx:221-237](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/use-flight-response.tsx#L221-L237) Binary chunks that cannot be embedded directly as valid UTF-8 strings are converted to base64 strings using `Buffer.from` or `btoa` before being bundled into instruction arrays. ```tsx const base64 = typeof Buffer !== 'undefined' ? Buffer.from( chunk.buffer, chunk.byteOffset, chunk.byteLength ).toString('base64') : btoa(String.fromCodePoint(...chunk)) htmlInlinedData = htmlEscapeJsonString( JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64]) ) } ``` Sources: [packages/next/src/server/app-render/use-flight-response.tsx:255-266](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/use-flight-response.tsx#L255-L266) ### Response Wrapping and Content Types Completed Flight streams are wrapped into custom `RenderResult` subclasses to guarantee correct HTTP header assignment. `FlightRenderResult` forces the response content type header to match `RSC_CONTENT_TYPE_HEADER`, preventing downstream proxies or browsers from misinterpreting binary RSC payloads as HTML documents. ```typescript export class FlightRenderResult extends RenderResult { constructor( response: string | AnyStream, metadata: RenderResultMetadata = {}, waitUntil?: Promise ) { super(response, { contentType: RSC_CONTENT_TYPE_HEADER, metadata, waitUntil, }) } } ``` Sources: [packages/next/src/server/app-render/flight-render-result.ts:8-19](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/flight-render-result.ts#L8-L19) ## Client Reference and Action Manifests ### Compiler Identification and Module Mapping During the build process, the Flight client entry plugin traverses Webpack compilation chunks to identify client components and server actions, recording their module identifiers and chunk associations. The plugin creates asset manifests that map server actions and client entries for both Node.js and edge runtime targets, assigning metadata such as async status and browser or server layers. Sources: [packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts:1110-1137](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts#L1110-L1137) ### Action Manifests and Asset Emission Server actions are collected into runtime-specific structures (`serverActions` and `edgeServerActions`), linking action identifiers to their worker module IDs depending on whether their layer matches `WEBPACK_LAYERS.actionBrowser`. The resulting manifests are serialized to JSON and emitted as assets, alongside a JavaScript wrapper assigned to `self.__RSC_SERVER_MANIFEST`. Sources: [packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts:1139-1190](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts#L1139-L1190) > [!NOTE] > Edge server manifests override the encryption key property with the string literal `'process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY'` rather than embedding the build-time static secret directly. Sources: [packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts:1168-1171](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts#L1168-L1171) ### Module Resource Resolution and Import Collection Module paths are normalized using resolved resource data and query parameters to ensure client and server compilers share identical paths. For CommonJS modules, default imports automatically include the `__esModule` identifier alongside requested names to guarantee compatibility with React's client module proxy layer. ```typescript function getModuleResource(mod: webpack.NormalModule): string { const modPath: string = mod.resourceResolveData?.path || '' const modQuery = mod.resourceResolveData?.query || '' // We have to always use the resolved request here to make sure the // server and client are using the same module path (required by RSC), as // the server compiler and client compiler have different resolve configs. let modResource: string = modPath + modQuery // Context modules don't have a resource path, we use the identifier instead. if (mod.constructor.name === 'ContextModule') { modResource = mod.identifier() } // For the barrel optimization, we need to use the match resource instead // because there will be 2 modules for the same file (same resource path) // but they're different modules and can't be deduped via `visitedModule`. // The first module is a virtual re-export module created by the loader. if (mod.matchResource?.startsWith(BARREL_OPTIMIZATION_PREFIX)) { modResource = mod.matchResource + ':' + modResource } if (mod.resource === `?${WEBPACK_RESOURCE_QUERIES.metadataRoute}`) { return getMetadataRouteResource(mod.rawRequest).filePath } return modResource } ``` Sources: [packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts:1239-1265](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts#L1239-L1265) ## Action Bound Argument Cryptographic Serialization ### Bound Argument Encryption and Caching Server action bound arguments are serialized through React Flight via `renderToReadableStream`, capturing arguments into a string payload before cryptographic operations. To guarantee reference equality for objects returned from "use cache" functions when invoked repeatedly within a single render pass, `encryptActionBoundArgs` is wrapped in `React.cache`. A cache key is constructed by combining the `actionId` and the serialized argument string, allowing lookup and reuse of previously encrypted arguments from `resumeDataCache?.encryptedBoundArgs`. ```typescript export const encryptActionBoundArgs = React.cache( async function encryptActionBoundArgs(actionId: string, ...args: any[]) { const workUnitStore = workUnitAsyncStorage.getStore() const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : undefined const { clientModules } = getClientReferenceManifest() ``` Sources: [packages/next/src/server/app-render/encryption.ts:108-115](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts#L108-L115) ```typescript const cacheKey = actionId + serialized const cachedEncrypted = resumeDataCache?.encryptedBoundArgs.get(cacheKey) if (cachedEncrypted) { return cachedEncrypted } const encrypted = await encodeActionBoundArg(actionId, serialized) endReadIfStarted() if (resumeDataCache?.mutable) { resumeDataCache.encryptedBoundArgs.set(cacheKey, encrypted) } return encrypted } ``` Sources: [packages/next/src/server/app-render/encryption.ts:223-239](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts#L223-L239) > [!NOTE] > During development mode in cache components, a dummy debug channel consisting of an empty `WritableStream` is passed to `renderToReadableStream` to strip timing information from debug output. This prevents build/render timestamps from invalidating the cache key. Sources: [packages/next/src/server/app-render/encryption.ts:164-179](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts#L164-L179) ### Decryption and Stream Hydration WorkUnits Decryption reverses the pipeline by fetching cached or newly decoded argument strings using `decryptActionBoundArgs`. The decrypted string is fed into `createFromReadableStream` via a custom `ReadableStream` controller. Depending on the active work unit store type, stream closure behavior is adjusted to handle hanging promises or immediate termination. | Work Unit Store Type | Controller Termination Behavior | Sources | | :--- | :--- | :--- | | `prerender`, `prerender-runtime` | Defers stream closure until prerendering completes or `renderSignal` aborts. | [packages/next/src/server/app-render/encryption.ts:279-293](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts#L279-L293) | | `prerender-client`, `validation-client`, `prerender-legacy`, `request`, `cache`, `private-cache`, `unstable-cache`, `build-time-generator`, `undefined` | Closes the controller immediately via `controller.close()`. | [packages/next/src/server/app-render/encryption.ts:294-303](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts#L294-L303) | Sources: [packages/next/src/server/app-render/encryption.ts:274-307](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/encryption.ts#L274-L307) ## Client Ingestion and Stream Hydration ### Browser-Side Bootstrapping and Inline Script Parsing The client-side [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) bootstraps by evaluating `app-index.tsx`, which interacts with the global `self.__next_f` array to ingest initial Flight data pushed during server-side rendering. Chunks are dispatched into `nextServerDataLoadingGlobal` using a tuple-based `FlightSegment` schema. | Segment Opcode (`seg[0]`) | Payload Type | Description | Sources | | :--- | :--- | :--- | :--- | | `0` | None | Initializes `initialServerDataBuffer = []` to collect subsequent chunks. | [packages/next/src/client/app-index.tsx:81-83](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L81-L83) | | `1` | `string` | Enqueues raw text data or pushes it to the server data buffer. | [packages/next/src/client/app-index.tsx:84-92](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L84-L92) | | `2` | `any` | Assigns form state data to `initialFormStateData`. | [packages/next/src/client/app-index.tsx:93-94](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L93-L94) | | `3` | `string` (Base64) | Decodes Base64-encoded binary chunks into `Uint8Array` arrays. | [packages/next/src/client/app-index.tsx:95-111](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L95-L111) | Sources: [packages/next/src/client/app-index.tsx:60-112](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L60-L112) > [!WARNING] > If a chunk with opcode `1` or `3` arrives before opcode `0` has initialized `initialServerDataBuffer`, `nextServerDataCallback` throws an error stating that the bootstrap script is missing. Sources: [packages/next/src/client/app-index.tsx:84-86](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L84-L86), [packages/next/src/client/app-index.tsx:96-97](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L96-L97) ### React Flight Response Consumption Once the initialization chunks are collected, a `ReadableStream` is constructed to feed React via `nextServerDataRegisterWriter`. When `DOMContentLoaded` fires, any pending writers are closed to finalize hydration. ```tsx function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) { if (initialServerDataBuffer) { initialServerDataBuffer.forEach((val) => { ctr.enqueue(typeof val === 'string' ? encoder.encode(val) : val) }) if (initialServerDataLoaded && !initialServerDataFlushed) { // Instant Navigation Testing API: don't close or error the inline // Flight stream. The static shell has no inline Flight data, so the // stream is empty. Closing it would cause React to log an error about // missing data. Leaving it open lets React treat any holes as // "still suspended." Hydration uses the separately fetched RSC payload // (self.__next_instant_test), not this stream. if (isStreamErrorOrUnfinished(ctr)) { if (!instantTestStaticFetch) { ctr.error( new Error( 'The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.' ) ) } } else { ctr.close() } initialServerDataFlushed = true initialServerDataBuffer = undefined } } initialServerDataWriter = ctr } ``` Sources: [packages/next/src/client/app-index.tsx:127-156](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L127-L156) > [!NOTE] > When cache components and experimental cached navigations are enabled, the hydration stream is teed into two branches: one for React consumption and one for caching purposes. Sources: [packages/next/src/client/app-index.tsx:200-208](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/app-index.tsx#L200-L208) ## Segment Prefetch Payload Packaging ### Tree Construction and Identity Spine Wrapping Segment prefetch payloads are built by constructing a root-anchored transport tree starting from the terminal segment and wrapping upward along the identity spine. Each ancestor node along the spine is linked via its parallel route key, carrying its own prefetch hints if non-zero. If prefetching is disabled for an ancestor, its segment data is omitted, leaving it with identity information only so the client treats it as a non-claimable node. ```tsx let node: PartialTransportNode = { s: spine.segment } if (spine.prefetchHints !== 0) { node.h = spine.prefetchHints } if (terminal !== null) { node.d = createStagedSegmentData( terminal, staleTime, clientModules, streamInfoStage.promise ) } let edgeParallelRouteKey = spine.parallelRouteKey let ancestor = spine.parent let bundleNode = bundle while (ancestor !== null && edgeParallelRouteKey !== null) { const parentNode: PartialTransportNode = { s: ancestor.segment, } if (ancestor.prefetchHints !== 0) { parentNode.h = ancestor.prefetchHints } if (bundleNode !== null) { if (bundleNode.data !== null) { parentNode.d = createStagedSegmentData( bundleNode.data, staleTime, clientModules, streamInfoStage.promise ) } bundleNode = bundleNode.next } parentNode.c = new Map([[edgeParallelRouteKey, node]]) node = parentNode edgeParallelRouteKey = ancestor.parallelRouteKey ancestor = ancestor.parent } ``` Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:1227-1264](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1227-L1264) > [!NOTE] > Root segment request keys are automatically normalized to `/_index` when packaging transport data, while non-root keys retain their original request identifiers. Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:1275-1279](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1275-L1279) ### Prefetch Payload Structure and Stream Encapsulation The assembled transport data is wrapped inside a `PrefetchFlightResponse` payload object alongside shell boundary offsets, runtime flags, and build identifiers before being rendered into a readable stream. Chunks emitted by the renderer are consumed asynchronously into an array while tracking the total byte length to determine the exact shell boundary offset. | Payload Field | Type | Description | Sources | | :--- | :--- | :--- | :--- | | `t` | `PartialTransportData` | The wrapped transport tree and optional head data. | [packages/next/src/server/app-render/collect-segment-data.tsx:1288](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1288) | | `a` | `Promise` | Resolves to the byte length after the shell stage or `null` if the shell is a full response. | [packages/next/src/server/app-render/collect-segment-data.tsx:1289](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1289) | | `u` | `Promise` | Indicates whether a runtime request is needed. | [packages/next/src/server/app-render/collect-segment-data.tsx:1290](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1290) | | `b` | `string` | Optional build identifier. | [packages/next/src/server/app-render/collect-segment-data.tsx:1292-1294](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1292-L1294) | | `r` | `VaryParamsIterable` | Optional root vary parameters. | [packages/next/src/server/app-render/collect-segment-data.tsx:1295-1297](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1295-L1297) | | `f` | `boolean` | Flag set when the payload represents an upgradeable ISR fallback. | [packages/next/src/server/app-render/collect-segment-data.tsx:1298-1300](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1298-L1300) | Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:1287-1301](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1287-L1301) > [!WARNING] > If the abort signal fires during stream consumption, error rows emitted by the abort action are explicitly discarded to match prerender halting behavior. Sources: [packages/next/src/server/app-render/collect-segment-data.tsx:1333-1338](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/collect-segment-data.tsx#L1333-L1338) ## Development Validation Error Transmission ### Flight-Encoded Error Serialization When development validation errors occur during component rendering or validation worker execution, they are serialized into Flight protocol bytes using `serializeValidationErrorsToFlight`. This function retrieves client modules via `getClientReferenceManifest` and invokes `renderToNodeFlightStream` passing the component module, an errors object wrapper, client modules, and stack frame filters active outside production. ```typescript export async function serializeValidationErrorsToFlight( componentMod: AppPageModule, errors: Error[] ): Promise { const { clientModules } = getClientReferenceManifest() const stream = renderToNodeFlightStream( componentMod, { errors }, clientModules, { filterStackFrame } ) const chunks: Uint8Array[] = [] for await (const chunk of stream) { chunks.push(chunk) } return chunks ``` Sources: [packages/next/src/server/app-render/dev-validation-error-delivery.ts:18-35](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dev-validation-error-delivery.ts#L18-L35) > [!WARNING] > Serialization must execute in the runtime that originally generated the errors—such as an in-process render or a validation worker—to ensure matching client-reference manifests capture live `Error` instances complete with stacks and digests. Sources: [packages/next/src/server/app-render/dev-validation-error-delivery.ts:11-17](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/app-render/dev-validation-error-delivery.ts#L11-L17) ### HMR Delivery and Stream Management Serialized error streams are tracked in memory using `errorsRscStreamsByHtmlRequestId` as a mapping from HTML request identifiers to active stream instances. The Hot Module Replacement (HMR) layer interacts with this registry through dedicated lifecycle functions to transmit error payloads to the browser overlay. | Function Name | Parameters | Description | Sources | | :--- | :--- | :--- | :--- | | `sendSerializedErrorsToClient` | `errorsRscStream: AnyStream`, `sendToClient: (message: HmrMessageSentToBrowser) => void` | Converts the RSC stream to a `Uint8Array` and dispatches an `ERRORS_TO_SHOW_IN_BROWSER` HMR message. | [packages/next/src/server/dev/serialized-errors.ts:10-25](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/serialized-errors.ts#L10-L25) | | `sendSerializedErrorsToClientForHtmlRequest` | `htmlRequestId: string`, `sendToClient: (message: HmrMessageSentToBrowser) => void` | Looks up and deletes the error stream for a request ID, then dispatches it. | [packages/next/src/server/dev/serialized-errors.ts:27-40](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/serialized-errors.ts#L27-L40) | | `setErrorsRscStreamForHtmlRequest` | `htmlRequestId: string`, `errorsRscStream: AnyStream` | Stores an error stream against an HTML request ID. | [packages/next/src/server/dev/serialized-errors.ts:42-49](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/serialized-errors.ts#L42-L49) | | `deleteErrorsRscStreamForHtmlRequest` | `htmlRequestId: string` | Deletes the error stream entry for a given request ID. | [packages/next/src/server/dev/serialized-errors.ts:51-53](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/serialized-errors.ts#L51-L53) | Sources: [packages/next/src/server/dev/serialized-errors.ts:10-53](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/dev/serialized-errors.ts#L10-L53) ## Related - [App Rendering](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/app-rendering) - [Server Actions](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/server-actions) - [App Router](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/client-runtime/app-router) --- ## Technical docs: Pages Rendering URL: https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/app-rendering/pages-rendering
Relevant source files The following files were used as context for generating this wiki page: - [packages/next/src/server/render.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx) - [packages/next/src/server/base-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/base-server.ts) - [packages/next/src/pages/_document.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/pages/_document.tsx) - [packages/next/src/client/index.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/client/index.tsx) - [packages/next/src/server/route-modules/pages/pages-handler.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/pages-handler.ts) - [packages/next/src/build/templates/app-page-runtime.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/app-page-runtime.ts) - [packages/next/src/server/next-server.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/next-server.ts) - [packages/next/src/server/load-components.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/load-components.ts) - [packages/next/src/shared/lib/router/router.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/router.ts) - [packages/next/src/build/templates/pages.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages.ts) - [packages/next/src/export/worker.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/export/worker.ts) - [packages/next/src/pages/_app.tsx](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/pages/_app.tsx) - [packages/next/src/export/routes/pages.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/export/routes/pages.ts) - [packages/next-codemod/transforms/cra-to-next.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next-codemod/transforms/cra-to-next.ts) - [packages/next/src/server/route-modules/pages/module.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.ts) - [packages/next/src/server/render-result.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render-result.ts) - [packages/next/src/server/get-page-files.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/get-page-files.ts) - [packages/next/src/shared/lib/page-path/denormalize-page-path.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/page-path/denormalize-page-path.ts) - [packages/next/src/shared/lib/page-path/normalize-page-path.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/page-path/normalize-page-path.ts) - [packages/next/src/shared/lib/page-path/normalize-path-sep.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/page-path/normalize-path-sep.ts) - [packages/next/src/shared/lib/router/utils/interception-routes.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/interception-routes.ts) - [packages/next/src/shared/lib/router/utils/is-dynamic.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/router/utils/is-dynamic.ts) - [packages/next/src/shared/lib/utils.ts](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/utils.ts)
## Overview Pages rendering governs the server-side execution, component tree assembly, and HTML serialization pipeline for legacy Pages Router routes. It provides request dispatching through route modules, coordinates asset resolution with build manifests, manages asynchronous data fetching lifecycles, and integrates static site export workers. Sources: [packages/next/src/server/route-modules/pages/module.ts:124-155](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.ts#L124-L155), [packages/next/src/server/render.tsx:1271-1445](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1271-L1445), [packages/next/src/export/routes/pages.ts:30-145](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/export/routes/pages.ts#L30-L145) ## Pages Route Module Architecture ### Route Module Layer and Request Dispatching The Pages Router leverages a route module architecture built upon the core `RouteModule` abstraction to handle incoming requests and render pages. The compilation output template wraps userland page modules alongside custom App and Document components into a unified `PagesRouteModule` instance. This module accepts request parameters via `PagesRouteHandlerContext`, which bundles the target page identifier, parsed URL query, shared context, and render options (`RenderOpts`), omitting internal `Document` and `App` components. ```typescript export class PagesRouteModule extends RouteModule< PagesRouteDefinition, PagesUserlandModule > { private readonly components: PagesComponents constructor(options: PagesRouteModuleOptions) { super(options) this.components = options.components } public render( req: IncomingMessage, res: ServerResponse, context: PagesRouteHandlerContext ): Promise { return renderToHTMLImpl( req, res, context.page, context.query, context.renderOpts, { App: this.components.App, Document: this.components.Document, }, context.sharedContext, context.renderContext ) } } ``` Sources: [packages/next/src/server/route-modules/pages/module.ts:124-155](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/route-modules/pages/module.ts#L124-L155) The `PagesRouteModule` class implements the `render` method, serving as the bridge that delegates execution directly to `renderToHTMLImpl`. This implementation takes node request (`IncomingMessage`) and response (`ServerResponse`) streams, alongside the context fields, and returns a promise resolving to a `RenderResult` object. ```typescript // Create and export the route module that will be consumed. export const routeModule = new PagesRouteModule({ definition: { kind: RouteKind.PAGES, page: 'VAR_DEFINITION_PAGE', pathname: 'VAR_DEFINITION_PATHNAME', // The following aren't used in production. bundlePath: '', filename: '', }, distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '', relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', components: { // default export might not exist when optimized for data only App: app.default, Document: document.default, }, userland, }) ``` Sources: [packages/next/src/build/templates/pages.ts:46-64](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages.ts#L46-L64) ### Re-exports and Lifecycle Data Methods During the build process, the pages template module acts as a re-export aggregator for userland page modules. It uses a helper utility (`hoist`) to expose default components and data-fetching hooks such as `getStaticProps`, `getStaticPaths`, and `getServerSideProps`, along with legacy aliases like `unstable_getStaticProps` and `unstable_getServerSideProps`. | Export Identifier | Source Userland Symbol | Purpose | | :--- | :--- | :--- | | `default` | `userland['default']` | The main React page component | | `getStaticProps` | `userland['getStaticProps']` | [Static generation](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-system/static-generation) data fetching hook | | `getStaticPaths` | `userland['getStaticPaths']` | Dynamic route paths enumeration for SSG | | `getServerSideProps` | `userland['getServerSideProps']` | Server-side rendering data fetching hook | | `config` | `userland['config']` | Page-specific configuration options | | `reportWebVitals` | `userland['reportWebVitals']` | Performance metrics reporting hook | ```typescript // Re-export the component (should be the default export). export default hoist(userland, 'default') // Re-export methods. export const getStaticProps = hoist(userland, 'getStaticProps') export const getStaticPaths = hoist(userland, 'getStaticPaths') export const getServerSideProps = hoist(userland, 'getServerSideProps') export const config = hoist(userland, 'config') export const reportWebVitals = hoist(userland, 'reportWebVitals') // Re-export legacy methods. export const unstable_getStaticProps = hoist( userland, 'unstable_getStaticProps' ) export const unstable_getStaticPaths = hoist( userland, 'unstable_getStaticPaths' ) export const unstable_getStaticParams = hoist( userland, 'unstable_getStaticParams' ) export const unstable_getServerProps = hoist( userland, 'unstable_getServerProps' ) export const unstable_getServerSideProps = hoist( userland, 'unstable_getServerSideProps' ) ``` Sources: [packages/next/src/build/templates/pages.ts:14-44](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/build/templates/pages.ts#L14-L44) > [!WARNING] > In the [Edge runtime](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/server-runtime/edge-runtime), executing `Document.getInitialProps` is unsupported. If a custom Document component defines `getInitialProps` while targeting the Edge runtime, an explicit error is thrown unless a builtin functional document fallback is available. ```tsx const BuiltinFunctionalDocument: DocumentType | undefined = ( Document as any )[NEXT_BUILTIN_DOCUMENT] if (process.env.NEXT_RUNTIME === 'edge' && Document.getInitialProps) { // In the Edge runtime, `Document.getInitialProps` isn't supported. // We throw an error here if it's customized. if (BuiltinFunctionalDocument) { Document = BuiltinFunctionalDocument } else { throw new Error( '`getInitialProps` in Document component is not supported with the Edge Runtime.' ) } } ``` Sources: [packages/next/src/server/render.tsx:1276-1290](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1276-L1290) ## Component Loading and Assets Resolution ### Component and Document Loading Implementation The server initializes components and resolves required assets through `loadComponents`, which delegates implementation details to `loadComponentsImpl`. For pages path executions (`isAppPath` evaluated as `false`), the loader concurrently requires the custom document (`/_document`) and app (`/_app`) modules alongside the target page module via `requirePage`. ```typescript let DocumentMod = {} let AppMod = {} if (!isAppPath) { ;[DocumentMod, AppMod] = await Promise.all([ requirePage('/_document', distDir, false), requirePage('/_app', distDir, false), ]) } ``` Sources: [packages/next/src/server/load-components.ts:203-210](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/load-components.ts#L203-L210) When `needsManifestsForLegacyReasons` is enabled, development and static generation paths evaluate retry mechanisms (`manifestLoadAttempts` set to 3 in development mode and 1 in production) to handle concurrent file compilation races when loading manifest files from disk. ```typescript if (needsManifestsForLegacyReasons) { // In dev mode we retry loading a manifest file to handle a race condition // that can occur while app and pages are compiling at the same time, and the // build-manifest is still being written to disk while an app path is // attempting to load. const manifestLoadAttempts = isDev ? 3 : 1 ``` Sources: [packages/next/src/server/load-components.ts:212-218](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/load-components.ts#L212-L218) ### Manifest Types and Resolution Paths Depending on whether Turbopack or Webpack is active, manifests are fetched from designated build directories (`distDir`) using specific path constructs. For pages routes, `reactLoadableManifestPath` resolves through `normalizePagePath` to locate the correct page segment folder. | Manifest Constant | File Name / Suffix | Loading Function / Behavior | | :--- | :--- | :--- | | `BUILD_MANIFEST` | `build-manifest.json` | `loadManifestWithRetries` | | `REACT_LOADABLE_MANIFEST` | `react-loadable-manifest.json` | `tryLoadManifestWithRetries` | | `DYNAMIC_CSS_MANIFEST` | `dynamic-css-manifest.json` | `loadManifestWithRetries` (Pages dir + Webpack + Prod) | | `SERVER_REFERENCE_MANIFEST` | `server-reference-manifest.json` | `loadManifestWithRetries` (App path only) | | `SUBRESOURCE_INTEGRITY_MANIFEST` | `subresource-integrity-manifest.json` | `loadManifestWithRetries` (Conditional on `sriEnabled`) | ```typescript if (!process.env.TURBOPACK) { reactLoadableManifestPath = join( /* turbopackIgnore: true */ distDir, REACT_LOADABLE_MANIFEST ) } else if (isAppPath) { reactLoadableManifestPath = join( /* turbopackIgnore: true */ distDir, 'server', 'app', page, REACT_LOADABLE_MANIFEST ) } else { reactLoadableManifestPath = join( /* turbopackIgnore: true */ distDir, 'server', 'pages', normalizePagePath(page), REACT_LOADABLE_MANIFEST ) } ``` Sources: [packages/next/src/server/load-components.ts:220-241](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/load-components.ts#L220-L241) > [!NOTE] > Static metadata routes bypass client-side manifest loading (`hasClientManifest` evaluates to `false` when `isStaticMetadataRoute(page)` is true) to optimize performance. ```typescript // Make sure to avoid loading the manifest for static metadata routes for better performance. const hasClientManifest = !isStaticMetadataRoute(page) ``` Sources: [packages/next/src/server/load-components.ts:243-245](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/load-components.ts#L243-L245) ### Build Manifest and Page File Normalization The core `BuildManifest` structure defines fields for runtime assets, including `devFiles`, `polyfillFiles`, `lowPriorityFiles`, `rootMainFiles`, and a mapping of `pages` where `/_app` and page segments map to read-only string arrays of chunk files. ```typescript export type BuildManifest = { devFiles: readonly string[] polyfillFiles: readonly string[] lowPriorityFiles: readonly string[] rootMainFiles: readonly string[] // this is a separate field for flying shuttle to allow // different root main files per entries/build (ideally temporary) // until we can stitch the runtime chunks together safely rootMainFilesTree: { [appRoute: string]: readonly string[] } pages: { '/_app': readonly string[] [page: string]: readonly string[] } // Per-page Turbopack chunk-group bootstrap params, stored as raw JSON. pagesChunkGroupBootstrapParams?: { [page: string]: object } // The chunk-loading global the runtime drains (default "TURBOPACK"). chunkLoadingGlobal?: string } ``` Sources: [packages/next/src/server/get-page-files.ts:4-21](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/get-page-files.ts#L4-L21) To locate assets for a specific route, `getPageFile` processes the path through `normalizePagePath` and `denormalizePagePath` to resolve the exact manifest key. ```typescript export function getPageFiles( buildManifest: BuildManifest, page: string ): readonly string[] { const normalizedPage = denormalizePagePath(normalizePagePath(page)) let files = buildManifest.pages[normalizedPage] if (!files) { console.warn( `Could not find files for ${normalizedPage} in .next/build-manifest.json` ) return [] } return files } ``` Sources: [packages/next/src/server/get-page-files.ts:49-64](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/get-page-files.ts#L49-L64) Path transformation follows specific normalization rules depending on index positioning and dynamic parameters: | Input Page Path | Transformed Path (`normalizePagePath`) | Denormalized Path (`denormalizePagePath`) | | :--- | :--- | :--- | | `/` | `/index` | `/` | | `/index` | `/index/index` | `/` | | `/index/foo` | `/index/index/foo` | `/foo` | | `/foo/bar` | `/foo/bar` | `/foo/bar` | ```typescript * - `/` -> `/index` * - `/index/foo` -> `/index/index/foo` * - `/index` -> `/index/index` */ export function normalizePagePath(page: string): string { const normalized = /^\/index(\/|$)/.test(page) && !isDynamicRoute(page) ? `/index${page}` : page === '/' ? '/index' : ensureLeadingSlash(page) ``` Sources: [packages/next/src/shared/lib/page-path/normalize-page-path.ts:10-20](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/page-path/normalize-page-path.ts#L10-L20), [packages/next/src/shared/lib/page-path/denormalize-page-path.ts:8-18](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/page-path/denormalize-page-path.ts#L8-L18) > [!WARNING] > Path normalization is not idempotent for routes starting with `/index`. Repeatedly calling `normalizePagePath` nests additional `/index` segments into the path string. ```typescript /** * Takes a page and transforms it into its file counterpart ensuring that the * output is normalized. Note this function is not idempotent because a page * `/index` can be referencing `/index/index.js` and `/index/index` could be * referencing `/index/index/index.js`. Examples: * - `/` -> `/index` * - `/index/foo` -> `/index/index/foo` * - `/index` -> `/index/index` */ ``` Sources: [packages/next/src/shared/lib/page-path/normalize-page-path.ts:5-13](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/page-path/normalize-page-path.ts#L5-L13) ## Data Fetching Execution Lifecycles ### Custom App Initial Props Delegation The initialization and data population of Pages Router pages rely on utility helpers that load data before tree rendering occurs. The core utility `loadGetInitialProps` coordinates data fetching for components such as custom App entries and individual page nodes. ```typescript export async function loadGetInitialProps< C extends BaseContext, IP = {}, P = {}, >(App: NextComponentType, ctx: C): Promise { if (process.env.NODE_ENV !== 'production') { if (App.prototype?.getInitialProps) { const message = `"${getDisplayName( App )}.getInitialProps()" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.` throw new Error(message) } } // when called from _app `ctx` is nested in `ctx` const res = ctx.res || (ctx.ctx && ctx.ctx.res) if (!App.getInitialProps) { if (ctx.ctx && ctx.Component) { // @ts-ignore pageProps default return { pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx), } } return {} as IP } const props = await App.getInitialProps(ctx) if (res && isResSent(res)) { return props } if (!props) { const message = `"${getDisplayName( App )}.getInitialProps()" should resolve to an object. But found "${props}" instead.` throw new Error(message) } if (process.env.NODE_ENV !== 'production') { if (Object.keys(props).length === 0 && !ctx.ctx) { console.warn( `${getDisplayName( App )} returned an empty object from \`getInitialProps\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps` ) } } return props } ``` Sources: [packages/next/src/shared/lib/utils.ts:373-423](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/utils.ts#L373-L423) During development, `loadGetInitialProps` checks whether `getInitialProps` is improperly defined as an instance method rather than a static method on the component prototype, throwing an error if a mismatch is detected. > [!CAUTION] > Defining `getInitialProps` as an instance method instead of a static method on a page component or custom App triggers an immediate development-time error. ```typescript if (process.env.NODE_ENV !== 'production') { if (App.prototype?.getInitialProps) { const message = `"${getDisplayName( App )}.getInitialProps()" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.` throw new Error(message) } } ``` Sources: [packages/next/src/shared/lib/utils.ts:378-385](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/utils.ts#L378-L385) The custom App component (`App`) defines its default `getInitialProps` through `appGetInitialProps`, which delegates data loading directly to the active page component by invoking `loadGetInitialProps` on the supplied `Component` and `ctx` parameters. ```tsx async function appGetInitialProps({ Component, ctx, }: AppContext): Promise { const pageProps = await loadGetInitialProps(Component, ctx) return { pageProps } } ``` Sources: [packages/next/src/pages/_app.tsx:26-32](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/pages/_app.tsx#L26-L32) If a component lacks a `getInitialProps` static method entirely, `loadGetInitialProps` falls back to inspecting nested context properties or returns an empty object. | Condition / Check | Behavior in `loadGetInitialProps` | | :--- | :--- | | `App.prototype.getInitialProps` (Dev-only) | Throws an error instructing the user to remove instance-level definition. | | Missing `App.getInitialProps` with nested `ctx.Component` | Recursively loads initial props from `ctx.Component` using `ctx.ctx`. | | Missing `App.getInitialProps` without nested component | Returns an empty object (`{} as IP`). | | Resolved props evaluate to `null` or `undefined` | Throws an error stating `getInitialProps()` should resolve to an object. | | Resolved props are an empty object (`Object.keys(props).length === 0`) | Emits a development warning regarding de-optimization and prevention of automatic static optimization. | ```typescript if (process.env.NODE_ENV !== 'production') { if (App.prototype?.getInitialProps) { const message = `"${getDisplayName( App )}.getInitialProps()" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.` throw new Error(message) } } // when called from _app `ctx` is nested in `ctx` const res = ctx.res || (ctx.ctx && ctx.ctx.res) if (!App.getInitialProps) { if (ctx.ctx && ctx.Component) { // @ts-ignore pageProps default return { pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx), } } return {} as IP } const props = await App.getInitialProps(ctx) if (res && isResSent(res)) { return props } if (!props) { const message = `"${getDisplayName( App )}.getInitialProps()" should resolve to an object. But found "${props}" instead.` throw new Error(message) } if (process.env.NODE_ENV !== 'production') { if (Object.keys(props).length === 0 && !ctx.ctx) { console.warn( `${getDisplayName( App )} returned an empty object from \`getInitialProps\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps` ) } } ``` Sources: [packages/next/src/shared/lib/utils.ts:378-421](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/shared/lib/utils.ts#L378-L421) ## Component Tree Composition Flow ### Assembling the Custom App and Page Hierarchy The render pipeline constructs the React element tree by wrapping the active page component and its custom App wrapper inside an isomorphic container structure. Within `renderContent`, the server determines whether an error state or normal route rendering is active, forwarding either the `ErrorDebug` component or the core page element tree wrapped with `AppContainerWithIsomorphicFiberStructure` and a root `Body` element (`
`). ```tsx const renderContent = (_App: AppType, _Component: NextComponentType) => { const EnhancedApp = _App || App const EnhancedComponent = _Component || Component return ctx.err && ErrorDebug ? ( ) : ( {renderPageTree(EnhancedApp, EnhancedComponent, { ...props, router, })} ) } ``` Sources: [packages/next/src/server/render.tsx:1351-1369](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1351-L1369) The default custom App class exported by Next.js establishes the baseline component rendering behavior by extracting `Component` and `pageProps` from its instance properties and rendering the page component directly. ```tsx export default class App

extends React.Component< P & AppProps, S > { static origGetInitialProps = appGetInitialProps static getInitialProps = appGetInitialProps render() { const { Component, pageProps } = this.props as AppProps return } ``` Sources: [packages/next/src/pages/_app.tsx:34-45](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/pages/_app.tsx#L34-L45) > [!WARNING] > Returning `router` or `Component` properties inside `getInitialProps` from `_app.js` throws an explicit development-time error to prevent corrupting router state and element reconciliation. ```tsx if ( process.env.__NEXT_DEV_SERVER && (props.router || props.Component) ) { throw new Error( `'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props` ) } ``` Sources: [packages/next/src/server/render.tsx:1315-1322](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1315-L1322) ## Document Shell and Script Injection ### Document Lifecycle and Initialization The document serialization pipeline coordinates the custom or built-in `Document` component lifecycle. When rendering pages, the server inspects whether a custom `Document` defines `getInitialProps`. If an edge runtime context is active alongside a customized `Document.getInitialProps`, Next.js throws an error because the Edge Runtime does not support custom document initial props unless a built-in functional document fallback is available. ```tsx const BuiltinFunctionalDocument: DocumentType | undefined = ( Document as any )[NEXT_BUILTIN_DOCUMENT] if (process.env.NEXT_RUNTIME === 'edge' && Document.getInitialProps) { // In the Edge runtime, `Document.getInitialProps` isn't supported. // We throw an error here if it's customized. if (BuiltinFunctionalDocument) { Document = BuiltinFunctionalDocument } else { throw new Error( '`getInitialProps` in Document component is not supported with the Edge Runtime.' ) } } ``` Sources: [packages/next/src/server/render.tsx:1276-1290](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1276-L1290) ```tsx const hasDocumentGetInitialProps = process.env.NEXT_RUNTIME !== 'edge' && !!Document.getInitialProps ``` Sources: [packages/next/src/server/render.tsx:1383-1385](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1383-L1385) > [!CAUTION] > Using `Document.getInitialProps` inside the Edge runtime triggers an immediate execution error, as initial props loading for documents is prohibited in lightweight edge environments. ```tsx if (process.env.NEXT_RUNTIME === 'edge' && Document.getInitialProps) { // In the Edge runtime, `Document.getInitialProps` isn't supported. // We throw an error here if it's customized. if (BuiltinFunctionalDocument) { Document = BuiltinFunctionalDocument } else { throw new Error( '`getInitialProps` in Document component is not supported with the Edge Runtime.' ) } ``` Sources: [packages/next/src/server/render.tsx:1280-1289](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/server/render.tsx#L1280-L1289) ### HtmlContext and Document Component Elements The document component exposes layout tags (`Html`, `Main`) that consume context via `useHtmlContext`. The `Html` component captures attributes like `lang` and `data-dpl-id` from the deployment identifier while triggering script loader registration items via `handleDocumentScriptLoaderItems`. The `Main` component evaluates to a custom element tag ``, marking the precise insertion boundary where the rendered React component tree gets mounted into the document shell. ```tsx export function Html( props: React.DetailedHTMLProps< React.HtmlHTMLAttributes, HTMLHtmlElement > ) { const { docComponentsRendered, locale, scriptLoader, deploymentId, __NEXT_DATA__, } = useHtmlContext() docComponentsRendered.Html = true handleDocumentScriptLoaderItems(scriptLoader, __NEXT_DATA__, props) return ( ) } export function Main() { const { docComponentsRendered } = useHtmlContext() docComponentsRendered.Main = true // @ts-ignore return } ``` Sources: [packages/next/src/pages/_document.tsx:970-1001](https://github.com/blade47/next.js/blob/d8c1c1b0002db8ccb63b58095f338e8bf423fa99/packages/next/src/pages/_document.tsx#L970-L1001) ### Script Injection and Hydration Tags Script injection relies on manifest data retrieved via `getDocumentFiles`, which combines shared files (`/_app`) and page-specific files. Polyfill scripts are emitted first with `noModule={true}` and deferred attributes depending on optimized loading flags. Dynamic import chunks and regular page scripts are mapped with cache-busting query strings derived from asset query parameters or immutable chunk paths. ```tsx function getDocumentFiles( buildManifest: BuildManifest, pathname: string ): DocumentFiles { const sharedFiles: readonly string[] = getPageFiles(buildManifest, '/_app') const pageFiles: readonly string[] = getPageFiles(buildManifest, pathname) return { sharedFiles, pageFiles, allFiles: [...new Set([...sharedFiles, ...pageFiles])], } } function getPolyfillScripts(context: HtmlProps, props: OriginProps) { // polyfills.js has to be rendered as nomodule without async // It also has to be the first script to load const { assetPrefix, buildManifest, assetQueryString, disableOptimizedLoading, crossOrigin, } = context return buildManifest.polyfillFiles .filter( (polyfill) => polyfill.endsWith('.js') && !polyfill.endsWith('.module.js') ) .map((polyfill) => (