# Next.js — Admin Guide

Audience: administrators, architects, and developers who deploy, operate, extend, or contribute to Next.js. This guide documents the framework's architecture, its complete configuration surface, deployment shapes, security posture, and internals — derived directly from the source tree at commit `d3e41fb` (`next@16.3.0-canary.90`).

---

## 1. Executive Summary

**What it is.** Next.js is a full-stack React framework distributed as the npm package `next`, plus a companion scaffolder `create-next-app`. It provides file-system routing, a development server with hot-code reloading, a production build pipeline, and a rich command-line interface. Its self-description is "The React Framework."

**What it's built with.** The published `next` package is TypeScript compiled to `dist/`, bundling a large set of vendored dependencies under `next/dist/compiled/*` (webpack, commander, semver, and dozens more). The high-performance compiler and bundler — **SWC** and **Turbopack** — are Rust, delivered as platform-specific native binaries (`@next/swc-*`) and, in this monorepo, live under `turbopack/crates/` and `crates/`. React and React DOM are peer dependencies supplied by the host application.

**Deployment shape.** A Next.js app is normally a long-running Node.js server (`next start`) fronting a `.next/` build directory. Two alternative outputs exist: `output: 'standalone'` (a self-contained `.next/standalone` bundle for containers) and `output: 'export'` (static HTML/CSS/JS in `out/`, no server).

**Operational burden.** Low-to-moderate. There is no database, no broker, and no external service dependency in the framework itself — a build step plus a Node process. The main operational concerns are Node version alignment (`>=20.9.0`), memory during Turbopack builds, image-optimization sizing (`sharp`), and cache-handler configuration for multi-instance deployments.

---

## 2. Architecture

### 2.1 Component inventory

This repository is a **pnpm + Turborepo monorepo**. The product is a small set of published packages; the overwhelming majority of the 28,697 files are test fixtures (`test/e2e/**`) and example apps (`examples/**`).

| Component | Path | Role |
|---|---|---|
| **`next`** (the framework) | `packages/next` | The published package: CLI, dev/prod server, build pipeline, router, config loader, image optimizer. |
| **`create-next-app`** | `packages/create-next-app` | Standalone scaffolder CLI + project templates. |
| **`@next/*` sub-packages** | `packages/next-*`, `packages/font`, `packages/eslint-*` | Font loader, codemods, polyfills, React Refresh utils, ESLint config, etc. |
| **Turbopack** | `turbopack/crates/*` | The Rust bundler and its `turbo-tasks` incremental engine. |
| **Native compiler bindings** | `crates/`, `@next/swc-*` | SWC-based transforms delivered as per-platform native binaries. |
| **Examples** | `examples/*` | ~hundreds of runnable integration examples (CMS, auth, DB, tooling). |
| **Test suites** | `test/e2e`, `test/production`, `test/development`, `test/unit` | The bulk of the tree; Playwright/Jest-driven. |
| **Benchmarks & apps** | `bench/`, `apps/bundle-analyzer` | Performance harnesses and the bundle-analyzer web UI. |

### 2.2 Runtime data flow

```
                         ┌──────────────────────────────────────────┐
                         │  next  (packages/next/src/bin/next.ts)    │
                         │  commander CLI dispatcher                 │
                         └───────────────┬──────────────────────────┘
             ┌───────────────┬───────────┼───────────────┬───────────────┐
             ▼               ▼           ▼               ▼               ▼
          next dev       next build   next start      next info      next typegen
             │               │           │
   forks child server   build() →     startServer()
   (server/lib/         .next/ output  (production)
    start-server)          │
             │             ▼
             │      ┌───────────────┐
             ▼      │  Bundler       │   Turbopack (Rust, turbo-tasks)
   ┌──────────────┐ │  selection     │   ── or ──
   │ Dev server   │ │ parseBundlerArgs│  webpack (vendored)
   │ Fast Refresh │ └───────┬────────┘
   │ HMR + overlay│         ▼
   └──────────────┘   SWC transforms (@next/swc native binary)
                            │
                            ▼
                     .next/  (or .next/standalone, or out/ for export)
```

The CLI (`bin/next.ts`) is a **commander** program. `next dev` forks the real server into a child process (`server/lib/start-server`) so it can size the child's heap (`--max-old-space-size` ≈ 50% of system RAM) and restart it cleanly on specific exit codes. `next build` runs `build()` and exits explicitly to avoid hanging on open handles. Bundler choice (Turbopack vs. webpack) is resolved by `parseBundlerArgs` from the `--turbopack`/`--webpack` flags.

### Data Layer

Next.js ships **no application database**. The framework's own persistent state is:

- **Build output** under `distDir` (default `.next/`), including a `cache/` subtree (Turbopack persistent cache when enabled).
- **Response cache** governed by the **cache handler** system (`cacheHandler` / `cacheHandlers`) — see §2.3.
- **Dev-server state file** `dev-state.json` under the OS cache directory (`getCacheDirectory('nextjs-nodejs')`), used to detect "rage restarts."
- **Telemetry storage** (anonymous), togglable via `next telemetry`.

### Caching

Caching is central and pluggable:

- **In-memory cache** sized by `cacheMaxMemorySize` (default **50 MB**; `0` disables it).
- **Cache handlers.** `cacheHandler` sets a single custom handler module; the newer `cacheHandlers` object routes `default`/`remote`/`static` (and named) handlers, each configurable via env (`NEXT_DEFAULT_CACHE_HANDLER_PATH`, `NEXT_REMOTE_CACHE_HANDLER_PATH`, `NEXT_STATIC_CACHE_HANDLER_PATH`).
- **`cacheLife` profiles.** Named cache profiles (`default`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `max`) with `stale`/`revalidate`/`expire` seconds — see the exact defaults in §4.3.
- **`cacheComponents`** (default `false`) opts the app into combining a prerendered shell with dynamically streamed content, and enables the `cacheLife`/`cacheTag` APIs and Partial Prerendering.
- **`expireTime`** (default `31536000`, one year) — the stale window the server may serve.

> [!IMPORTANT]
> For horizontally scaled deployments (multiple `next start` instances), the default filesystem/in-memory cache is per-instance. Configure a shared **remote cache handler** so all instances see consistent revalidations.

---

## 3. System Requirements

| Requirement | Value | Source |
|---|---|---|
| Node.js | `>=20.9.0` | `packages/next/package.json` → `engines.node` |
| React / React DOM | `^18.2.0` or `^19.0.0` | `peerDependencies` |
| Platforms | `linux`, `darwin` (macOS), `win32` (Windows) | `next info` platform handling |
| CPU architecture | native `@next/swc` binary must exist for platform/arch | `next info --verbose` swc check |

**Optional capabilities:**

| Package | Purpose |
|---|---|
| `sharp` `^0.34.5` | Native image optimization (recommended for production image use). |
| `sass` `^1.3.0` | Sass/SCSS support. |
| `@playwright/test` `^1.51.1` | `next experimental-test`. |
| `@opentelemetry/api` `^1.1.0` | OTEL tracing integration. |
| `babel-plugin-react-compiler` | React Compiler. |

> [!NOTE]
> The `next` binary enforces the Node range at startup via `semver.satisfies` against `__NEXT_REQUIRED_NODE_VERSION_RANGE` and exits non-zero if unmet. It also warns when running x86-64 Node under Rosetta 2 on Apple Silicon.

---

## 4. Configuration Mastery

Config is read from `next.config.{js,mjs,ts,mts}` and typed as `NextConfig` (`packages/next/src/server/config-shared.ts`). Values below are the exact defaults from the frozen `defaultConfig` object. Options are grouped for readability.

### 4.1 Core / output

| Key | Type | Default | Purpose |
|---|---|---|---|
| `distDir` | `string` | `'.next'` | Build output directory. |
| `cleanDistDir` | `boolean` | `true` | Clear `distDir` on build (except caches). |
| `output` | `'standalone' \| 'export'` | *(unset)* | Alternate build output shape. Auto-`'standalone'` if `NEXT_PRIVATE_STANDALONE` is set. |
| `basePath` | `string` | `''` | Serve the app under a sub-path. |
| `assetPrefix` | `string` | `''` | CDN origin prefix for static assets. |
| `trailingSlash` | `boolean` | `false` | Redirect to/from trailing slash. |
| `useFileSystemPublicRoutes` | `boolean` | `true` | Serve `pages/` files by filename. |
| `pageExtensions` | `string[]` | `['tsx','ts','jsx','js']` | Recognized route file extensions. |
| `generateBuildId` | `() => string \| null` | `() => null` | Custom build ID generator. |
| `generateEtags` | `boolean` | `true` | Emit `ETag` headers. |
| `deploymentId` | `string` | *(unset)* | Per-deployment identifier added to requests. |
| `outputFileTracingRoot` | `string` | `''` | Root above which files are traced for tracing/standalone. |
| `outputFileTracingExcludes` / `outputFileTracingIncludes` | `Record<string,string[]>` | *(unset)* | Manual trace overrides. |
| `outputHashSalt` | `string` | *(unset)* | Salt for content-addressed output filenames (combined with `NEXT_HASH_SALT`). |
| `env` | `Record<string,string>` | `{}` | Build-time inlined environment variables. |

### 4.2 Networking / routing

| Key | Type | Default | Purpose |
|---|---|---|---|
| `headers` | `() => Header[]` | *(unset)* | Custom HTTP headers per path. |
| `redirects` | `() => Redirect[]` | *(unset)* | Redirect rules. |
| `rewrites` | `() => Rewrite[] \| {beforeFiles,afterFiles,fallback}` | *(unset)* | Rewrite rules. |
| `i18n` | `I18NConfig \| null` | `null` | Internationalized routing (`locales`, `defaultLocale`, `domains`). |
| `poweredByHeader` | `boolean` | `true` | Emit `X-Powered-By: Next.js`. |
| `compress` | `boolean` | `true` | gzip responses. |
| `httpAgentOptions` | `{ keepAlive?: boolean }` | `{ keepAlive: true }` | HTTP keep-alive. |
| `crossOrigin` | `'anonymous' \| 'use-credentials'` | *(unset)* | `crossorigin` attr on generated scripts. |
| `skipProxyUrlNormalize` | `boolean` | *(unset)* | Skip proxy URL normalization (replaces deprecated `skipMiddlewareUrlNormalize`). |
| `skipTrailingSlashRedirect` | `boolean` | *(unset)* | Suppress the trailing-slash redirect. |
| `allowedDevOrigins` | `string[]` | *(unset)* | Origins allowed to reach the dev server. |
| `reactMaxHeadersLength` | `number` | `6000` | Cap on React-emitted header length. |

### 4.3 Caching

| Key | Type | Default | Purpose |
|---|---|---|---|
| `cacheMaxMemorySize` | `number` (bytes) | `52428800` (50 MB) | In-memory cache size; `0` disables. |
| `cacheHandler` | `string` | `process.env.NEXT_CACHE_HANDLER_PATH` | Path to a custom cache handler. |
| `cacheHandlers` | `{default,remote,static,...}` | env-driven | Named cache handler routing. |
| `cacheComponents` | `boolean` | `false` | Prerendered shell + streamed dynamic content; enables `cacheLife`/`cacheTag`/PPR. |
| `expireTime` | `number` (s) | `31536000` | Stale-serve window (one year). |
| `staticPageGenerationTimeout` | `number` (s) | `60` | Timeout generating a static page. |

**`cacheLife` default profiles** (`stale` / `revalidate` / `expire`, in seconds):

| Profile | stale | revalidate | expire |
|---|---|---|---|
| `default` | (→ `staleTimes.static`) | 900 (15 min) | ∞ (`INFINITE_CACHE`) |
| `seconds` | 30 | 1 | 60 |
| `minutes` | 300 | 60 | 3600 |
| `hours` | 300 | 3600 | 86400 |
| `days` | 300 | 86400 | 604800 |
| `weeks` | 300 | 604800 | 2592000 |
| `max` | 300 | 2592000 | 31536000 |

### 4.4 Compiler / bundler

| Key | Type | Default | Purpose |
|---|---|---|---|
| `reactStrictMode` | `boolean \| null` | `null` | React Strict Mode. |
| `reactCompiler` | `boolean \| ReactCompilerOptions` | *(unset)* | Enable React Compiler (`compilationMode`, `panicThreshold`). |
| `reactProductionProfiling` | `boolean` | `false` | React profiling in production. |
| `typedRoutes` | `boolean` | `false` | Statically typed links/router. |
| `typescript` | `{ ignoreBuildErrors?, tsconfigPath? }` | `{ ignoreBuildErrors: false }` | TS build behavior. |
| `transpilePackages` | `string[]` | *(unset)* | Transpile listed packages (replaces `next-transpile-modules`). |
| `serverExternalPackages` | `string[]` | *(unset)* | Keep packages external in the server bundle. |
| `bundlePagesRouterDependencies` | `boolean` | `false` | Bundle node_modules for Pages server bundles. |
| `modularizeImports` | `Record<string, {transform,...}>` | *(unset)* | Rewrite imports to reduce bundle size. |
| `turbopack` | `TurbopackOptions` | *(unset)* | `resolveAlias`, `resolveExtensions`, `rules`, `root`, `debugIds`, etc. |
| `webpack` | `NextJsWebpackConfig \| null` | `null` | Custom webpack config function. |
| `productionBrowserSourceMaps` | `boolean` | `false` | Emit browser source maps in prod. |
| `compiler` | object | `{}` | `removeConsole`, `reactRemoveProperties`, `styledComponents`, `emotion`, `styledJsx`, `relay`, `define`, `defineServer`, `runAfterProductionCompile`. |

### 4.5 Images, logging, dev

| Key | Type | Default | Purpose |
|---|---|---|---|
| `images` | `ImageConfig` | built-in defaults | Image Optimization (`remotePatterns`, `formats`, `deviceSizes`, etc.). |
| `logging` | `LoggingConfig \| false` | `{ serverFunctions: true }` | Fetch/request/server-function/browser-console logging. |
| `devIndicators` | `false \| { position }` | `{ position: 'bottom-left' }` | Dev tools indicator placement. |
| `onDemandEntries` | `{ maxInactiveAge, pagesBufferLength }` | `{ 60000, 5 }` | Dev in-memory page retention. |
| `watchOptions` | `{ pollIntervalMs }` | *(unset)* | File-watch polling interval. |
| `agentRules` | `boolean` | `true` | Auto-generate `AGENTS.md`/`CLAUDE.md` for AI agents in `next dev`. |
| `sassOptions` | `{ implementation?, ... }` | `{}` | Sass compiler options. |

> [!TIP]
> The `experimental` key holds **hundreds** of unstable flags (e.g. `ppr`, `staleTimes`, `optimizeCss`, `serverMinification`, `cpus`, `webpackMemoryOptimizations`, `turbopackFileSystemCacheForBuild`). They change without notice between canaries — pin your Next.js version if you depend on any of them, and treat them as opt-in only.

---

## 5. Deployment

### 5.1 Standard Node.js server

```bash
next build
next start -p 8080 -H 0.0.0.0
```

Requires the full project (including `node_modules`) on the host. `--keepAliveTimeout` tunes idle connection handling behind a load balancer.

### Docker

Use `output: 'standalone'` to ship only what's needed:

```javascript
// next.config.js
module.exports = { output: 'standalone' }
```

```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY . .
RUN npm ci && npm run build

FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]
```

> [!CAUTION]
> On **Windows + pnpm**, standalone output can contain symlinks resolving outside `.next/standalone` (issue #95450). Validate the standalone artifact inside the target container image before shipping.

### 5.2 Static export

```javascript
// next.config.js
module.exports = { output: 'export' }
```

`next build` writes static assets to `out/`. Serve with any static host/CDN — no Node.js runtime. Note: features requiring a server (Image Optimization with `sharp`, dynamic API routes, on-demand revalidation) are unavailable in exported sites.

### 5.3 Behind a CDN

Set `assetPrefix` to your CDN origin and `basePath` if serving under a sub-path. `supportsImmutableAssets` lets deployments that support immutable assets skip the `?dpl` deployment-id parameter.

---

## 6. Security

Next.js is a framework, not a hardened appliance — its security posture is mostly about what **you** configure.

### Authentication
The framework provides **no built-in auth**. Authentication is application code (the `examples/` tree includes Passport, NextAuth-style, Supabase, and other integrations). Route protection is implemented via Middleware/Proxy and your own session handling.

### Authorization & Access Control
Enforced in application code (Server Components, Route Handlers, Middleware). `allowedDevOrigins` restricts which origins may talk to the **dev** server. `clientParamParsingOrigins` (experimental) governs which origins may write rewritten headers on non-relative rewrites.

### TLS / Certificates
Production TLS is expected to be terminated by your reverse proxy/load balancer. For **development only**, `next dev --experimental-https` generates a self-signed certificate (or accepts `--experimental-https-key/cert/ca`). Do not use dev certs in production.

### Secrets handling
- Server-only environment variables are never sent to the browser; only `NEXT_PUBLIC_`-prefixed variables are inlined client-side.
- `next info --verbose` deliberately **redacts** sensitive fields (`cwd`, `commandLine`, `host`, `cpus`, `networkInterfaces`) from the Node diagnostic report before printing.
- `--experimental-upload-trace` warns that the uploaded trace "includes sensitive data" — use only against trusted endpoints.

### Network exposure
`next dev` and `next start` bind `0.0.0.0` by default, exposing the server on all interfaces. Restrict with `-H 127.0.0.1` in untrusted networks, or bind behind a proxy.

> [!WARNING]
> `poweredByHeader` defaults to `true`, advertising `X-Powered-By: Next.js`. Set it to `false` to reduce fingerprinting. Use the `headers()` config to add security headers (CSP, HSTS, `X-Frame-Options`, etc.).

### Content-integrity
Subresource Integrity (SRI) support exists in the build (`SubresourceIntegrityAlgorithm`). `crossOrigin` sets the `crossorigin` attribute on generated scripts.

---

## 7. Operations

### 7.1 Start / stop

- **Start (prod):** `next start` (after `next build`). Handles `SIGINT`/`SIGTERM` and closes gracefully.
- **Start (dev):** `next dev` forks a child server; on certain exit codes it auto-restarts. It writes CPU profiles on exit when `--experimental-cpu-prof` is set.
- **Stop:** `Ctrl+C` (SIGINT). The dev process kills its child with escalating signals (SIGINT/SIGTERM → SIGKILL after `NEXT_EXIT_TIMEOUT_MS`, default 100 ms).

### Logging
Controlled by the `logging` config (default `{ serverFunctions: true }`):
- `logging.fetches.fullUrl` / `hmrRefreshes` — fetch logging detail.
- `logging.incomingRequests` — `false` or a `{ ignore: RegExp[] }` filter to silence noisy paths.
- `logging.serverFunctions` — Server Function invocation logs (default on).
- `logging.browserToTerminal` — forward browser console output to the terminal (`true`/`'warn'`/`'error'`).

### Monitoring & Health Checks
- **OpenTelemetry:** integrate via the optional `@opentelemetry/api` peer dependency; Next.js emits spans for requests/renders/fetches.
- **Request Insights:** `next experimental-request-insights` inspects framework spans from a running dev server (enable with `experimental.requestInsights`); records request/render/fetch/cache behavior without an external OTEL collector.
- **Health check:** implement a Route Handler (e.g. `app/health/route.ts`) returning `200` for your load balancer — the framework ships no default endpoint.

### Backup & Restore
The framework holds no application data. Back up **your** application source, `.env*` files, and any external cache-handler store. The `.next/` directory is a rebuildable artifact — you can always regenerate it with `next build`.

---

## 8. Performance Tuning

- **Bundler:** benchmark `--turbopack` vs. `--webpack` for your codebase; Turbopack is the default focus for new work.
- **Build memory:** `next build --experimental-debug-memory-usage` surfaces memory pressure. `experimental.webpackMemoryOptimizations` and `experimental.parallelServerBuildTraces` help large webpack builds.
- **Dev server heap:** `next dev` auto-sets `--max-old-space-size` to ~50% of system RAM (override via `NODE_OPTIONS` or disable the override with `NEXT_DISABLE_MEM_OVERRIDE`).
- **Static generation concurrency:** `experimental.staticGenerationMaxConcurrency` (default 8) and `staticGenerationMinPagesPerWorker` (default 25) tune the prerender workers.
- **Image optimization:** install `sharp`; tune `experimental.imgOptConcurrency`, `imgOptTimeoutInSeconds` (default 7), and `imgOptMaxInputPixels`.
- **CPU profiling:** `--experimental-cpu-prof` on `dev`/`build`/`start` writes `.next-profiles/*.cpuprofile` on exit; upload with `next internal upload-trace`.
- **Persistent Turbopack cache:** `experimental.turbopackFileSystemCacheForBuild` enables an on-disk build cache; `next internal post-build` compacts the Turbopack database afterward.

> [!TIP]
> `next internal static-routes-info` reports per-route bundle sizes (server JS, source maps, client JS/CSS) — the fastest way to find bloated routes after a build.

---

## 9. Integrations

### Plugin / Extension System
Next.js is extended through configuration hooks rather than a plugin registry:

- **Bundler loaders:** webpack via `webpack(config, ctx)`; Turbopack via `turbopack.rules` (webpack-loader-compatible).
- **SWC transforms:** the `compiler` config enables built-in transforms (`styledComponents`, `emotion`, `relay`, `removeConsole`, `define`).
- **Cache handlers:** pluggable modules via `cacheHandler`/`cacheHandlers`.
- **Deployment adapters:** `adapterPath` (or `NEXT_ADAPTER_PATH`) points at a custom adapter module for platform integration.
- **React Compiler:** opt-in via `reactCompiler` + `babel-plugin-react-compiler`.
- **Instrumentation:** `instrumentationClientInject` injects client side-effect modules before hydration; `instrumentation-client.{ts,js}` runs your client instrumentation.

### First-party companions
`create-next-app` (scaffolding), `@next/font` → `next/font` (fonts), `@next/codemod` (used by `next upgrade`), `eslint-config-next` (linting config), and `@next/mdx`-class packages live in `packages/`.

---

## 10. Developer Internals

### 10.1 Repository structure

```
next.js/
├── packages/
│   ├── next/                 # the framework (published as `next`)
│   │   └── src/
│   │       ├── bin/next.ts   # commander CLI entry point
│   │       ├── cli/          # per-command implementations (next-dev, next-build, …)
│   │       ├── server/       # dev + prod server, config loader (config-shared.ts)
│   │       ├── build/        # build pipeline, swc bindings, output logging
│   │       ├── client/       # client runtime, router, dev hot-reloader
│   │       └── shared/       # code shared across server/client
│   ├── create-next-app/      # scaffolder + templates/
│   └── next-*, font, eslint-*# companion packages
├── turbopack/crates/*        # Rust: Turbopack + turbo-tasks incremental engine
├── crates/                   # Rust: next-core, next-api, SWC plugins
├── examples/*                # runnable integration examples
├── test/{e2e,production,     # the bulk of the tree
│         development,unit}/
├── bench/                    # performance harnesses
└── apps/bundle-analyzer/     # bundle-analyzer web UI
```

### 10.2 CLI internals

`bin/next.ts` builds a `NextRootCommand extends Command` (commander). A shared `preAction` hook sets `NODE_ENV` per command (`dev` → `development`, else `production`), sets `NEXT_RUNTIME='nodejs'`, warns on non-standard `NODE_ENV`, warns on Rosetta, and rejects `--inspect` for non-`dev`/`start` commands. Each subcommand lazy-imports its implementation module from `../cli/*` to keep startup fast.

The **`next internal`** command group (explicitly "not covered by semver") exposes: `trace` (Turbopack trace server, alias `turbo-trace-server`), `query-trace` (query a running trace server via its MCP endpoint on port 5748), `post-build` (Turbopack DB compaction), `upload-trace` (upload CPU profiles to Vercel Blob), and `static-routes-info` (per-route bundle sizes).

### 10.3 Key module reference

| Module | Responsibility |
|---|---|
| `server/config-shared.ts` | `NextConfig` type + `defaultConfig` — the config contract. |
| `server/config.ts` | Loads/normalizes `next.config`, backfills defaults. |
| `server/lib/start-server.ts` | Boots the HTTP server (dev child + prod). |
| `build/index.ts` | The production build pipeline. |
| `build/swc/*` | Loads native SWC bindings; `loadBindings`, `getSupportedArchTriples`. |
| `cli/next-dev.ts` | Dev orchestration: fork child, memory sizing, restart handling. |
| `cli/next-info.ts` | Environment diagnostics (redacts sensitive fields). |
| `lib/bundler.ts` | `parseBundlerArgs` — Turbopack vs. webpack selection. |

### Testing Strategy

Testing dominates the repository:

- **`test/e2e`** — end-to-end app scenarios (the largest set; thousands of fixture apps under `test/e2e/app-dir/**`).
- **`test/production`** — production-build behavior.
- **`test/development`** — dev-server/HMR behavior.
- **`test/unit`** — unit tests (`test/unit/eslint-plugin-next/*`, etc.).
- **Runners:** Jest (`jest.config.js`) and Playwright, orchestrated by `run-tests.js`. Environment flags like `IS_TURBOPACK_TEST`, `NEXT_TEST_MODE`, `NEXT_TEST_REACT_VERSION`, and `TEST_CONCURRENCY` parameterize runs across bundlers and React versions.
- Contributors can run `next experimental-test` to exercise `next/experimental/testmode` (Playwright) against an app.

---

## 11. Troubleshooting (operator-grade)

### Error: `You are using Node.js <v>. For Next.js, Node.js version ">=20.9.0" is required.`
**Cause:** Host Node below the required range. **Solution:** Upgrade Node to ≥20.9.0. **Prevention:** Pin Node in your base image / `.nvmrc`.

### Native binary fails to load (`next-swc` / DLOPEN)
**Cause:** Missing or mismatched `@next/swc-<platform>` binary. **Solution:** Run `next info --verbose` — it verifies the swc install and (on Linux/macOS/Windows) inspects shared-object dependencies with `ldd`/`otool`/`dumpbin`. Reinstall dependencies for the correct platform/arch. **Prevention:** Build the image on the same OS/arch you deploy to; avoid copying `node_modules` across architectures.

### Turbopack build OOM / multi-GB memory on Apple Silicon (issue #92055)
**Cause:** `@next/swc-darwin-arm64` allocates large non-reclaimable memory during Turbopack compilation. **Solution:** Track upstream; try latest canary; for CI, consider `--webpack` or raise container memory. **Prevention:** Monitor build memory with `--experimental-debug-memory-usage`.

### Standalone symlinks escape `.next/standalone` (Windows + pnpm, issue #95450)
**Cause:** Traced symlinks resolve outside the standalone dir. **Solution:** Validate the artifact in-container; consider a hoisted/non-symlinked install for the build stage. **Prevention:** Build standalone images on Linux CI.

### Dev server restarts unexpectedly ("rage restart")
**Cause:** The dev parent restarts the forked child on specific exit codes; frequent manual restarts within 90 s are flagged as rage restarts (telemetry only). **Solution:** Usually benign; investigate the child's crash logs if persistent. **Prevention:** N/A — this is recovery behavior, not an error.

### `Non-standard NODE_ENV` warning in CI
**Cause:** `NODE_ENV` set to a non-standard value or one conflicting with the command. **Solution:** Unset it and let Next.js choose, or use only `production`/`development`/`test`. **Prevention:** Remove `NODE_ENV` overrides from build scripts.

### Config type errors with `next.config.ts`
**Cause:** TS config not resolving natively. **Solution:** Add `--experimental-next-config-strip-types` to the invoking command (sets `__NEXT_NODE_NATIVE_TS_LOADER_ENABLED`). **Prevention:** Keep the config's imports resolvable from the project root.

### Catch-all route error: `Catch-all must be the last part of the URL.`
**Cause:** A `[...param]` segment isn't the final path segment. **Solution:** Reorder route files so catch-alls are terminal. **Prevention:** Follow router file conventions.

---

## 12. Potential Improvements

Observations from the source and issue tracker (not prescriptions):

- **Turbopack memory on macOS arm64** (issue #92055) is an active pain point; deployments building on Apple Silicon should budget extra RAM or build on Linux CI until fixed.
- **`--inspect-wait`** is stubbed (`// TODO: Implement --inspect-wait` in `next-start.ts`) — full inspector-wait support is pending.
- **SWC/Turbopack minifier correctness** — several recently-closed issues (#95941, #95940) involved the minifier dropping template-literal tails; keep production builds on a version past those fixes and validate minified output for template-heavy code.
- **Static-generation retry** (`experimental.staticGenerationRetryCount`) is unset by default; large sites with flaky data sources may want to set it.
- **Cache-handler documentation surface** — the `cacheHandler`/`cacheHandlers` split (single vs. named handlers) is easy to misconfigure for multi-instance deployments; standardize on `cacheHandlers.remote` for shared state.

---

## 13. Quick Reference

**Commands**

```bash
next dev [-p 3000] [-H 0.0.0.0] [--turbopack|--webpack]   # develop (default cmd)
next build [--turbopack|--webpack] [--profile]            # production build → .next/
next start [-p 3000] [--keepAliveTimeout <ms>]            # serve the build
next info [--verbose]                                     # diagnostics
next typegen                                              # route types (no full build)
next upgrade [--revision latest|canary|rc|beta|<version>] # upgrade
next telemetry [status|enable|disable]                    # anonymous telemetry
next experimental-analyze [--port 4000]                   # bundle analyzer UI
next internal <trace|post-build|static-routes-info|…>     # internal (no semver)
```

**Key paths**

| Path | What |
|---|---|
| `.next/` | Default build output (`distDir`). |
| `.next/standalone/` | `output: 'standalone'` bundle. |
| `out/` | `output: 'export'` static site. |
| `.next-profiles/` | CPU profiles (`--experimental-cpu-prof`). |
| `next.config.{js,mjs,ts,mts}` | Configuration. |

**Ports / defaults**

| Item | Default |
|---|---|
| Dev/prod server port | `3000` (env `PORT`, flag `-p`) |
| Hostname | `0.0.0.0` (flag `-H`) |
| Bundle analyzer port | `4000` |
| Turbopack trace MCP port | `5748` |
| In-memory cache | 50 MB (`cacheMaxMemorySize`) |
| Static gen timeout | 60 s |
| Node.js required | `>=20.9.0` |

**Notable environment variables**

`PORT`, `NODE_ENV`, `NEXT_PUBLIC_*` (client-inlined), `NEXT_PRIVATE_STANDALONE` (→ `output: 'standalone'`), `NEXT_CACHE_HANDLER_PATH`, `NEXT_ADAPTER_PATH`, `NEXT_HASH_SALT`, `NODE_OPTIONS`, `NEXT_DISABLE_MEM_OVERRIDE`, `NEXT_EXIT_TIMEOUT_MS`.

---

_Generated July 2026 from vercel/next.js at d3e41fb. AI-generated documentation. The library is checked by sampling (three repositories so far); this repository was the one sampled in the latest review, which scored its User Guide 55 out of 70 and found 1 factual error in about 30 checked claims. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
