33334 Commits

Author SHA1 Message Date
nextjs-bot d5f649b2f4 v16.2.3 v16.2.3 2026-04-08 18:24:27 +00:00
Sebastian "Sebbie" Silbermann 28739286a8 [16.x] Avoid consuming cyclic models multiple times (#75)
* Avoid consuming cyclic models multiple times

* make types-and-precompiled work
2026-04-08 11:18:58 -07:00
Zack Tanner d7c7765360 [backport]: Ensure app-page reports stale ISR revalidation errors via onRequestError (#92282) (#92519)
Backports:
- #92282
2026-04-08 08:08:57 -07:00
Will Binns-Smith c573e8c4f3 fix(server-hmr): metadata routes overwrite page runtime HMR handler (#92273)
### What?

Fix server HMR becoming unresponsive after a metadata route is loaded in
the same Node.js process as an app page.

### Why?

Turbopack loads separate runtime chunks for app pages and metadata
routes (`robots.ts`, `sitemap.ts`, `manifest.ts`, `icon.tsx`, etc.) in
the same Node.js process. Each runtime chunk embeds `dev-nodejs.ts` and
produces a distinct `__turbopack_server_hmr_apply__` closure bound to
its own `moduleFactories` and `devModuleCache`.

Previously each runtime simply overwrote
`globalThis.__turbopack_server_hmr_apply__`, so the last chunk to load
silently won. Navigating to `/robots.txt` before an HMR update caused
the metadata route runtime to overwrite the page runtime's handler.
Subsequent HMR updates were dispatched only to the metadata route
runtime, which has no knowledge of the page module — the page appeared
frozen and stopped reflecting file changes.

### How?

Replace the bare assignment with a multicast registry:

1. Each runtime appends its own `__turbopack_server_hmr_apply__` handler
to `globalThis.__turbopack_server_hmr_handlers__[]`.
2. The first runtime to register installs a shared dispatcher as
`globalThis.__turbopack_server_hmr_apply__` that iterates all registered
handlers at call time (not install time), so newly loaded runtimes are
always included.
3. On full cache reset, `hot-reloader-turbopack.ts` resets
`__turbopack_server_hmr_handlers__` to `[]` so stale handlers from
evicted chunks don't accumulate into the next generation.

Because `dev-nodejs.ts` is embedded into the Turbopack binary via
`include_dir!`, this fix requires rebuilding the native binary.

### Tests

`test/development/app-dir/server-hmr/server-hmr.test.ts` — extended with
`metadata route hmr` tests that load a metadata route before patching a
page file, verifying HMR updates still reach the page runtime after a
second runtime chunk is loaded.

---------

Co-authored-by: Will Binns-Smith <wbinnssmith@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-07 16:34:28 -07:00
Tobias Koppers 57b8f65906 next-core: deduplicate output assets and detect content conflicts on emit (#92292)
Adds deduplication and conflict detection to the asset emission stage in
`crates/next-core/src/emit.rs`, and a new `IssueStage::Emit` variant in
`turbopack-core`.

Before emitting, assets are grouped by their output path. If multiple
assets map to the same path:

- If their content is identical, one is silently chosen (deduplication).
- If their content differs, both versions are written to
`<node_root>/<content_hash>.<ext>` and an `EmitConflictIssue` is raised
for each conflict. All assets are still emitted — conflicts do not abort
the build.

Previously, duplicate output assets for the same path were emitted
unconditionally — whichever write happened last silently won. This
masked build graph bugs where two different modules produced conflicting
output files. Reporting conflicts as issues (rather than silently
overwriting) makes them visible and easy to diagnose without breaking
the build.

- Collect all assets with their resolved paths via `try_flat_join`.
- Bucket them into two `FxIndexMap<FileSystemPath,
Vec<ResolvedVc<Box<dyn OutputAsset>>>>` — one for node-root assets and
one for client assets.
- For each bucket entry, call `check_duplicates`: compare every asset
against the first using `assets_diff`. If content differs, emit an
`EmitConflictIssue` as a turbo-tasks collectible — but still return the
first asset so emission continues.
- `assets_diff` is a `#[turbo_tasks::function]` that takes only
`(asset1, asset2, extension, node_root)` — the `asset_path` stays out of
the task key to avoid unnecessary task cardinality. When file content
differs, it hashes each version with xxh3, writes them to
`<node_root>/<hash>.<ext>`, and returns the paths in the detail message
so the user can diff them.
- `EmitConflictIssue` implements the `Issue` trait with
`IssueStage::Emit` (new variant added to `turbopack-core`),
`IssueSeverity::Error`, a descriptive title, and a detail message
explaining the type of conflict.
- Node-root and client assets are emitted in parallel via
`futures::join!` (not `try_join!`) to ensure deterministic error
reporting — both branches always run to completion so errors are
reported in a consistent order.

---------

Co-authored-by: Tobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-07 14:10:54 -07:00
Tobias Koppers f158df18bd Fix styled-jsx race condition: styles lost due to concurrent rendering (#92459)
### What?

Fix a race condition in the Pages Router SSR path where styled-jsx
styles were dropped from the rendered HTML.

### Why?

`styledJsxInsertedHTML()` reads and flushes the styled-jsx style
registry. Previously it was called concurrently with the page render via
`Promise.all`:

```js
const [rawStyledJsxInsertedHTML, content] = await Promise.all([
  renderToString(styledJsxInsertedHTML()),
  (async () => { /* render the page */ })(),
])
```

Because both ran at the same time, `styledJsxInsertedHTML()` could (and
in practice did) execute and flush the registry **before** the page
render had finished populating it. The result was that dynamic
styled-jsx styles — those with interpolated expressions that compute
their class names at runtime via DJB2 hashing — were silently dropped
from the SSR output, causing a flash of unstyled content on first load.

This is particularly visible in production deployments where all
components use dynamic styled-jsx (numeric `jsx-*` class names), since
those styles only exist in the registry after rendering completes.

### How?

Serialize the two operations: render the page first, then call
`styledJsxInsertedHTML()`. Since the registry is fully populated by the
time it is read, all styles are captured correctly.

A new e2e test (`test/e2e/styled-jsx-dynamic`) exercises this scenario
with multiple nested components that all use dynamic styled-jsx with
interpolated props, covering the exact FOUC pattern seen in production.

<!-- NEXT_JS_LLM_PR -->

Co-authored-by: Tobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-07 12:07:04 -07:00
Tobias Koppers 356d605b58 turbo-tasks-backend: stability fixes for task cancellation and error handling (#92254)
Bug fixes and a refactoring in `turbo-tasks-backend` targeting stability
issues that surface when filesystem caching is enabled:

1. **Preserve `cell_type_max_index` on task error** — when a task fails
partway through execution, `cell_counters` only reflects the
partially-executed state. Previously, `cell_type_max_index` was updated
from these incomplete counters, which removed entries for cell types not
yet encountered. This caused `"Cell no longer exists"` hard errors for
tasks that still held dependencies on those cells. The fix skips the
`cell_type_max_index` update on error, keeping it consistent with the
preserved cell data (which already wasn't cleared on error).

This bug manifested specifically with `serialization = "hash"` cell
types (e.g. `FileContent`), where cell data is transient and readers
fall back to `cell_type_max_index` to decide whether to schedule
recomputation.

2. **Fix shutdown hang and cache poisoning for cancelled tasks** — three
related fixes for tasks cancelled during shutdown:
- `task_execution_canceled` now drains and notifies all
`InProgressCellState` events, preventing `stop_and_wait` from hanging on
foreground jobs waiting on cells that will never be filled.
- `try_read_task_cell` bails early (before calling `listen_to_cell`)
when a task is in `Canceled` state, avoiding pointless listener
registrations that would never resolve.
- Cancelled tasks are marked as session-dependent dirty, preventing
cache poisoning where `"was canceled"` errors get persisted as task
output and break subsequent builds. The session-dependent dirty flag
causes the task to re-execute in the next session, invalidating stale
dependents.

3. **Extract `update_dirty_state` helper on `TaskGuard`** — the "read
old dirty state → apply new state → propagate via
`ComputeDirtyAndCleanUpdate`" pattern was duplicated between
`task_execution_canceled` and `task_execution_completed_finish`. The new
`update_dirty_state` default method on `TaskGuard` handles both
transitions (to `SessionDependent` or to `None`) and returns the
aggregation job + `ComputeDirtyAndCleanUpdateResult` for callers that
need post-processing (e.g. firing the `all_clean_event`).

These bugs caused observable failures when using Turbopack with
filesystem caching (`--cache` / persistent cache):

- `"Cell no longer exists"` panics/errors on incremental rebuilds after
a task error.
- Hangs on `stop_and_wait` during dev server shutdown.
- Stale `"was canceled"` errors persisted in the cache breaking
subsequent builds until the cache is cleared.

Changes are in `turbopack/crates/turbo-tasks-backend/src/backend/`:

**`mod.rs`:**
- Guard the `cell_type_max_index` update block inside `if
result.is_ok()` to skip it on error, with a cross-reference comment to
`task_execution_completed_cleanup` (which similarly skips cell data
removal on error — the two must stay in sync).
- Move the `is_cancelled` bail in `try_read_task_cell` before the
`listen_to_cell` call to avoid inserting phantom `InProgressCellState`
events that would never be notified.
- In `task_execution_canceled`: switch to `TaskDataCategory::All`
(needed for dirty state metadata access), notify all pending in-progress
cell events, and mark the task as `SessionDependent` dirty via the new
helper.
- In `task_execution_completed_finish`: replace ~77 lines of inline
dirty state logic with a call to
`task.update_dirty_state(new_dirtyness)`, preserving the
`all_clean_event` post-processing and the `dirty_changed` variable under
`#[cfg(feature = "verify_determinism")]`.

**`operation/mod.rs`:**
- Add `update_dirty_state` default method on `TaskGuard` trait (~60
lines), co-located with the existing `dirty_state()` reader. Takes
`Option<Dirtyness>`, applies the transition, builds
`ComputeDirtyAndCleanUpdate`, and returns
`(Option<AggregationUpdateJob>, ComputeDirtyAndCleanUpdateResult)`.
- Add `ComputeDirtyAndCleanUpdateResult` to the public re-exports.

---------

Co-authored-by: Tobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-07 11:51:03 -07:00
Tobias Koppers 3b77a6e267 Fix DashMap read-write self-deadlock in task_cache causing hangs (#92210) 2026-04-07 11:45:34 -07:00
Joseph b2f208ae98 Backport: new view-transitions guide, update and fixes (#92264)
Publishing: 

1. `6a2045936f` - docs: add middleware bypass note to CDN caching guide
(#92132)
2. `495d50f187` - docs: document revalidateTag's required second
argument in upgrade guide (#92134)
3. `faa4b99296` - docs: local images referenced by remote source
(#92178)
4. `0167a02695` - Docs/adapters review (#92223)
5. `2622a53942` - docs: vt demo guide (#92249)

---------

Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Aurora Scharff <66901228+aurorascharff@users.noreply.github.com>
2026-04-02 17:46:50 +02:00
nextjs-bot 52faae3d94 v16.2.2 v16.2.2 2026-03-31 23:39:18 +00:00
Luke Sandberg 8d0f77bfa2 Backport: #92177
Fixes #91708

set the legacy_x86_64_support feature on qfilter to support older intel cpus
2026-03-31 16:17:14 -07:00
Benjamin Woodruff e151e5f842 Fix CI for glibc linux builds 2026-03-31 16:10:23 -07:00
Luke Sandberg 1a319ea4dc [backport] Fix CSS HMR on Safari (#92174)
## Summary
- Backport of #92123 to `next-16-2` release branch
- Cherry-picked the CSS HMR Safari fix and regenerated turbopack-tests
snapshot goldens for the release branch

## Test plan
- [x] `UPDATE=1 cargo nextest r -p turbopack-tests` — all 297 tests pass
- [x] `pnpm build-all` — clean build, no issues with
`generated-native.d.ts`
2026-03-31 15:05:38 -07:00
Will Binns-Smith c0edad2762 Turbopack: exclude metadata routes from server HMR (#92034)
### What?

Metadata routes (`manifest.ts`, `robots.ts`, `sitemap.ts`, `icon.tsx`,
`apple-icon.tsx`, etc.) were not being hot-reloaded in Turbopack dev
mode — changes to those files would not be reflected on subsequent
requests until a full server restart.

### Why?

PR #91466 extended `usesServerHmr = true` in `clearRequireCache()` (in
`hot-reloader-turbopack.ts`) from `app-page` entries only to **all**
`app`-type entries (pages + route handlers). The motivation was correct:
regular route handlers like `app/api/hello/route.ts` use Turbopack's
in-place module update model and benefit from server HMR.

However, metadata routes (`/manifest.webmanifest/route`,
`/robots.txt/route`, etc.) are also `app`-type entries but they are
**not** suitable for in-place server HMR. When `usesServerHmr = true`
for a metadata route, `clearRequireCache()` skips two critical
invalidation steps:

1. Deleting the compiled chunk from `require.cache`
2. Calling `__next__clear_chunk_cache__()`

Without those steps, the old module stays in-memory and all subsequent
requests to `/manifest.webmanifest` (etc.) return the stale content.

### How?

Added an `!isMetadataRoute(entryPage)` guard to the `usesServerHmr`
expression in `clearRequireCache()`. This restores full cache
invalidation for metadata routes on every rebuild while leaving regular
route handler server HMR (added in #91466) intact.

```ts
// Before
const usesServerHmr =
  serverFastRefresh &&
  entryType === 'app' &&
  writtenEndpoint.type !== 'edge'

// After
const usesServerHmr =
  serverFastRefresh &&
  entryType === 'app' &&
  writtenEndpoint.type !== 'edge' &&
  !isMetadataRoute(entryPage)   // ← metadata routes always clear the cache
```

`isMetadataRoute('/manifest.webmanifest/route')` → `true` (excluded from
server HMR)
`isMetadataRoute('/api/hello/route')` → `false` (keeps server HMR, no
regression)

Also added a regression test: `metadata route hmr > reflects manifest.ts
changes on fetch/refresh` in the `server-hmr` test suite, with a
`manifest.ts` fixture that starts at `name: 'Version 0'`. The test
patches the file and asserts the updated JSON is returned on the next
fetch.

Fixes #91981

---------

Co-authored-by: Will Binns-Smith <wbinnssmith@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 15:03:31 -07:00
Will Binns-Smith d6446990d9 Turbopack: enable server HMR for app route handlers (#91466)
App router handlers are already built with the Turbopack runtime, so
they can use server HMR. **We also already get subscription events for
their chunks.** However, unlike app pages which use
`__next_app__.require()` for dynamic devModuleCache lookup, route
handlers capture userland exports statically in AppRouteRouteModule at
construction time. This change makes routes behave a lot like pages,
dynamically loading the user's code when requests are made. This way, we
can freely invalidate and reload it when changes are made without
evicting the entire require cache.

Only `next dev` uses this lazy evaluation, as `next start` continues to
eagerly import route handlers.

This change removes the `isAppPage` restriction from `usesServerHmr`,
extending server HMR coverage to all App Router entries (pages and route
handlers) built with the Node.js runtime.

For route handlers, we also clear the entry chunk from Node.js
`require.cache` on each rebuild so the next `requirePage()` call
re-executes the entry and obtains fresh module exports from
`devModuleCache` (which HMR updates in-place).

Test Plan: Added an additional e2e test, `with-dep`
2026-03-31 15:03:19 -07:00
Will Binns-Smith 34de2cac29 next.config.js: Accept an option for serverFastRefresh (#91968)
### What?

Adds `experimental.serverFastRefresh` to `next.config.js` so users (and
Next.js plugins) can opt out of server-side Fast Refresh without needing
to pass a CLI flag.

Also adds a `--server-fast-refresh` positive CLI flag (hidden) alongside
the existing `--no-server-fast-refresh`, and emits a warning when the
CLI flag and config value conflict. This is a necessary implementation
detail for `commander` to detect when no option is provided.

### Why?

Certain Next.js plugins have encountered issues with server Fast Refresh
and need a way to disable it programmatically via config rather than
requiring users to modify their start scripts. The CLI-only opt-out
(`--no-server-fast-refresh`) was insufficient for this use case.

### How?

- **`config-shared.ts` / `config-schema.ts`**: Added
`experimental.serverFastRefresh?: boolean` to the `ExperimentalConfig`
type and Zod schema.
- **`router-server.ts`**: Resolves the effective `serverFastRefresh`
value at startup by combining the CLI flag (`opts.serverFastRefresh`)
and `nextConfig.experimental.serverFastRefresh`, with CLI taking
precedence. Emits a `Log.warn` when both are set to conflicting values.
Defaults to `true` when neither is specified.
- **`bin/next.ts`**: Fixed the Commander option definition for
`--no-server-fast-refresh`. Commander's `--no-X` pattern implicitly
creates a positive `--server-fast-refresh` option defaulting to `true`,
which meant `opts.serverFastRefresh` was never `undefined` and the
config value could never take effect. Fixed by explicitly registering a
hidden `--server-fast-refresh` option with `.default(undefined)`.
- **Tests**: Added two new test suites in
`test/development/app-dir/server-hmr/server-hmr.test.ts`:
- `server-hmr config opt-out` — verifies that setting
`experimental.serverFastRefresh: false` in config causes unmodified
dependencies to be re-evaluated (i.e., server HMR is disabled).
- `server-hmr CLI/config conflict warning` — verifies that passing
`--no-server-fast-refresh` when config has `serverFastRefresh: true`
logs the conflict warning.

### Test Plan

- [x] Added e2e development tests
(`test/development/app-dir/server-hmr/server-hmr.test.ts`) — all 8 tests
pass

---------

Co-authored-by: Will Binns-Smith <wbinnssmith@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 15:00:21 -07:00
Jude Gao c4779d1b08 [create-next-app] Skip interactive prompts when CLI flags are provided (#91840)
When AI agents run `create-next-app` with explicit flags like
`--typescript --tailwind --eslint --app --src-dir`, the CLI still enters
interactive mode and prompts for any unspecified options:

```
➜ npx create-next-app my-app --typescript --tailwind --eslint --app --src-dir --use-pnpm
✔ Would you like to use React Compiler? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes
? Would you like to include AGENTS.md to guide coding agents to write up-to-date Next.js code? › No / Yes
```

Agents can sometimes answer these interactive prompts correctly, but
often they can't. When they fail to navigate the prompts, they fall back
to scaffolding the project themselves from scratch — generating files
based on stale training data. This means they might initialize an app
using deprecated patterns or pin to an older version of Next.js (e.g.
15) instead of the latest. Using `create-next-app` non-interactively is
the best way to ensure agents always produce up-to-date scaffolding.

Previously, `hasProvidedOptions` only skipped the initial "use
recommended defaults?" meta-prompt but still showed individual prompts
for each missing option. Now when any config flags are provided, all
remaining options use the recommended defaults without prompting.

The resolved defaults are printed to stdout so the caller knows exactly
what was assumed and which flags to pass to override:

```
Using defaults for unprovided options:

  --eslint                ESLint (use --biome for Biome, --no-eslint for None)
  --no-react-compiler     No React Compiler (use --react-compiler for React Compiler)
  --agents-md             AGENTS.md (use --no-agents-md for No AGENTS.md)
  --import-alias          "@/*"

To customize, re-run with explicit flags.
```

The `displayConfig` array is extended with a `flags` field so this
output is auto-generated from the same source of truth used for the
interactive prompts. Existing behavior for `--yes`, CI mode, and fully
interactive mode (no flags) is unchanged.
2026-03-31 14:53:34 -07:00
JJ Kasper edcf19ae13 Backport: TypeScript v6 deprecations for baseUrl and moduleResolution (#92130)
backports: https://github.com/vercel/next.js/pull/91855
backports: https://github.com/vercel/next.js/pull/91847
2026-03-31 09:38:57 -07:00
JJ Kasper eee3f524e9 backport: Move expanded adapters docs to API reference (#92115) (#92129)
## Summary
- move adapter implementation docs from
`app/api-reference/config/next-config-js/adapters` to
`app/api-reference/adapters`
- keep `adapterPath` as an entry page that points to the new adapters
section
- add matching Pages Router pointer docs under
`pages/api-reference/adapters`
- update existing docs links that referenced old `adapterPath#...`
anchors to the new adapters routes

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
2026-03-31 08:56:27 -07:00
Joseph 6d31c3905a Backport: docs - 16.2.1 (#91885)
Backporting

1. `0e598d2131` — docs: use ErrorInfo type consistently in catchError
docs (#91744)
2. `70760c201b` — docs: add catchError benefits over userspace error
boundaries (#91745)
3. `1f920cd057` — docs: platform portability and infrastructure
documentation (#91237)
4. `5d2b57b051` — docs: add verified adapters section (#91849)

---------

Co-authored-by: Jiwon Choi <devjiwonchoi@gmail.com>
Co-authored-by: Jimmy Lai <laijimmy0@gmail.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
2026-03-25 23:41:22 -07:00
nextjs-bot ed7d2cef24 v16.2.1 v16.2.1 2026-03-20 23:23:58 +00:00
Joseph 3e37bb42d2 docs: post release amends (#91715)
Fixes based on feedback post release

Fixes: https://github.com/vercel/next.js/pull/91715
2026-03-20 15:01:21 -07:00
Abhishek Mardiya a15ec6e970 docs: fix broken Activity Patterns demo link in preserving UI state guide (#91698)
## What?

Fixes a broken link in the Preserving UI State guide:
https://nextjs.org/docs/app/guides/preserving-ui-state#examples

The "Activity Patterns demo" link currently points to a non-working URL.

## Why?

The demo link returns a 404 / invalid page, which makes the example
section confusing for readers.

## Changes

- Updated the Activity Patterns demo link to the correct URL.

## Notes

No functional changes, docs only.

@icyJoseph @delbaoliveira
2026-03-20 15:01:21 -07:00
JJ Kasper 600cd2fedb Fix adapter outputs for dynamic metadata routes (#91680)
## Summary

This fixes adapter `onBuildComplete` outputs for dynamic metadata
routes.

## Bug

`handleBuildComplete` skipped metadata routes too aggressively via
`isStaticMetadataFile(...)`, so dynamic metadata routes (for example
`robots.txt` / `sitemap.xml` using `connection()`) were omitted from
`outputs.appRoutes`.

## Fix

Only skip metadata routes when they are actually prerendered/static
(present in prerender manifests). Dynamic metadata routes are now
included in adapter `outputs.appRoutes` as expected.

## Tests

Added e2e coverage in `test/e2e/app-dir/adapter-dynamic-metadata`:
- verifies dynamic `robots.txt`, `sitemap.xml`, and `favicon.ico`
functionality
- verifies adapter output classification for non-deploy runs
- skips output-shape verification in deploy mode
- skips the suite in dev mode
2026-03-20 14:30:40 -07:00
Niklas Mischkulnig 27886d3cfb Turbopack: fix webpack loader runner layer (#91727)
Otherwise you get a `Dependency tracking is disabled` / infinite loop
when trying to use both turbopack.rules.loader and turbopackLoader at
the same time
2026-03-20 14:30:40 -07:00
Hendrik Liebau 88fc4308e2 Fix server actions in standalone mode with cacheComponents (#91711)
The `staticPathKey` condition added in #91231 inadvertently applies to
server action requests on dynamic SSG routes when `cacheComponents` is
enabled.

Server action fetch requests from the client do not send the `RSC`
header (`rsc: 1`). They only send `Accept: text/x-component` and the
`Next-Action` header. This means `isRSCRequest` and
`isDynamicRSCRequest` are both `false` for action requests. The new
`staticPathKey` condition (`isSSG && pageIsDynamic &&
prerenderInfo?.fallbackRouteParams`) evaluates to `true` for dynamic PPR
routes, setting `staticPathKey` even though `ssgCacheKey` is `null` for
actions.

With `staticPathKey` set, the request enters the fallback rendering
block, which serves the cached fallback HTML shell with the action
result appended to it, instead of responding with just the RSC action
result.

The fix excludes server action requests from the `staticPathKey`
computation by adding `!isPossibleServerAction` to the condition,
restoring the pre-#91231 behavior where `staticPathKey` was always
`null` for server actions in production.

fixes #91662
closes #91677
closes #91669
2026-03-20 14:30:40 -07:00
Tobias Koppers 37aed862ed turbo-persistence: remove Unmergeable mmap advice (#91713)
Remove the `MADV_UNMERGEABLE` (Unmergeable) mmap advice from
`turbo-persistence`'s `advise_mmap_for_persistence` helper in
`mmap_helper.rs`.

The WSL (Windows Subsystem for Linux) kernel does not support
`MADV_UNMERGEABLE` and returns an error when it is applied, causing
turbo-persistence to fail on WSL. See:
https://x.com/von_cronen/status/2034944304712392891

Additionally, `MADV_UNMERGEABLE` is already the **default** state for
memory pages — KSM (Kernel Same-page Merging) is opt-in via
`MADV_MERGEABLE`. Explicitly setting `MADV_UNMERGEABLE` on pages that
were never marked mergeable is a no-op on standard kernels, so the call
provides no benefit while breaking WSL users.

The `MADV_DONTFORK` advice is retained, as it has a clear correctness
benefit (prevents mmap regions from being inherited by child processes
on `fork()`).

Removed the `mmap.advise(memmap2::Advice::Unmergeable)` call and its
associated doc comment from
`turbopack/crates/turbo-persistence/src/mmap_helper.rs`.

Co-authored-by: Tobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-20 14:30:34 -07:00
Tobias Koppers d6195eca8c Fix layout segment optimization: move app-page imports to server-utility transition (#91701)
## Summary

- Add `'turbopack-transition': 'next-server-utility'` to all server-side imports in the `app-page.ts` template so they are properly placed in the server utility layer, rather than relying on `SharedMerged` chunk groups to handle them
- Remove the now-unnecessary `next-server-utility` transition from `fillMetadataSegment` import in `app_page_loader_tree.rs`
- Add `SharedMultiple` chunk group variant to support multiple shared entries without a merge tag
  - This avoid passing the `parent` into `SharedMerged`, which did break the layout segment optimization.
- Refactor `app_module_graphs` to combine `client_shared_entries` + `has_layout_segments` into a single `Option` parameter, simplifying the API and removing the dead code path for non-page endpoints

## Test plan

- [ ] Verify dev and production builds work with app pages that have layout segments
- [ ] Verify route handlers still build correctly (no client runtime entries passed)
- [ ] Run existing app-dir e2e tests
2026-03-20 14:30:00 -07:00
Niklas Mischkulnig 6cb97d6d75 Turbopack: lazy require metadata and handle TLA (#91705)
A regression from #88487

1. Make metadata import lazy with `() => require()`, just like for the layout segments
2. Properly await the return value to better handle TLA modules

This align with Webpack which does this:

<img width="1535" height="509" alt="Bildschirmfoto 2026-03-20 um 11 58 00" src="https://github.com/user-attachments/assets/f2864c86-ccce-4884-8417-c8ae06c05f78" />


Closes PACK-6927
Closes #91700
Closes https://github.com/vercel/next.js/issues/91676
2026-03-20 14:28:49 -07:00
Luke Sandberg e6b101ae71 [turbopack] Respect {eval:true} in worker_threads constructors (#91666)
### What?

Fixed Turbopack incorrectly trying to resolve inline JavaScript code as module references when `new Worker()` is called with `{ eval: true }` option.

Now we skip creating a reference when `eval:true`, and report warnings if we cannot tell what the value is

### Why?

Libraries like jsPDF create Worker threads by passing inline JavaScript code as the first argument along with `{ eval: true }` as the second argument. Turbopack was incorrectly treating this inline code as a file path and attempting to resolve it as a module reference, causing build failures.

### How?

Added logic to detect when the `eval: true` option is passed to the Worker constructor. When this option is present, Turbopack now skips creating a worker reference since the first argument contains executable code rather than a file path. Added comprehensive test coverage using jsPDF to verify the fix works correctly.

Fixes #91642
2026-03-20 14:28:49 -07:00
nextjs-bot 0aa15fdfe2 setup release branch 2026-03-18 18:55:15 +00:00
nextjs-bot c5c94dffbf v16.2.0 v16.2.0 2026-03-18 17:10:38 +00:00
Hendrik Liebau 649d302635 Unflake router events deploy test (#91589)
[Flakiness
metrics](https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest%20%40git.repository.id%3A%22github.com%2Fvercel%2Fnext.js%22%20%40test.status%3A%22fail%22%20%40test.name%3A%22basePath%20should%20use%20urls%20with%20basepath%20in%20router%20events%20for%20hash%20changes%22&agg_m=count&agg_m_source=base&agg_t=count&currentTab=overview&eventStack=&fromUser=false&index=citest&start=1773244604685&end=1773849404685&paused=false)

After upgrading Playwright in #91250 (which brought some performance
improvements), some tests are now exposed to be missing retries around
assertions. `test/e2e/basepath/router-events.test.ts` is one of those
tests, and this PR adds a `retry` around the event log assertion. We're
also replacing the deprecated `check` utility with `retry` when waiting
for the router to be ready.
2026-03-18 16:34:53 +00:00
Joseph bcd9c19a61 docs: Clarify ignoreBuildErrors behavior (#91367)
Just a complementary note to the TS config reference.
2026-03-18 16:54:42 +01:00
nextjs-bot 3683192a6b v16.2.0-canary.104 v16.2.0-canary.104 2026-03-18 13:29:38 +00:00
Richard Zhang b61823d7b9 SRI turbopack documentation (#90477)
<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
Updates the Subresource Integrity (SRI) documentation to reflect that
the feature is now supported on both Webpack and Turbopack bundlers.

Previously, the documentation stated that SRI was "only available with
webpack bundler". This has been updated to remove that restriction
following the implementation in PR #90152.

### Changes
- Removed webpack-only limitation from SRI documentation in Content
Security Policy guide
- Removed `experimental.sri.algorithm` from the list of unplanned
Turbopack features

Fixes the documentation to align with the current implementation.
<!-- CURSOR_AGENT_PR_BODY_END -->

[Slack
Thread](https://vercel.slack.com/archives/D0AGHCN7K2T/p1771984911390169?thread_ts=1771984911.390169&cid=D0AGHCN7K2T)

<div><a
href="https://cursor.com/agents/bc-0b4d6ed8-9e06-5c78-9a4d-b352a7c2e97d"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-0b4d6ed8-9e06-5c78-9a4d-b352a7c2e97d"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Richard Zhang <richardjzhang@users.noreply.github.com>
Co-authored-by: Joseph <joseph.chamochumbi@vercel.com>
2026-03-18 09:59:35 +01:00
Josh Story 0ca967b863 Add group depth tracking to instant validation boundary discovery (#91208)
The depth-based instant validation previously only iterated
URL-consuming segments as potential shared/new boundaries. Route groups
between URL segments were invisible — when a route group layout with
Suspense was shared in a client navigation, its Suspense appeared to
cover blocking code in the validation render even though it wouldn't in
reality.

This adds a second dimension to the validation iteration: group depth.
At each URL depth, we now also step through route group boundaries. A
new `discoverValidationDepths` function walks the LoaderTree and returns
an array where each entry represents the max group depth at that URL
depth. The validation loop iterates from deepest group depth to
shallowest within each URL depth, stopping on the first error.

Key design decisions:
- URL depth and group depth counters are advanced before the boundary
check, making the boundary condition a simple `nextUrlDepth > depth &&
currentGroupDepth >= groupDepth`
- The synthetic `(slot)` segment that Next.js inserts for parallel slots
is excluded from group depth counting since it doesn't represent a real
navigation boundary
- Group depths are discovered from the LoaderTree rather than the URL
pathname, making the tree the source of truth for validation bounds
2026-03-17 22:14:19 -07:00
Zack Tanner a41bef94c5 improve allowedDevOrigins error (#91521)
This improves the blocked-request warning so it names the actual dev
resource being requested and gives clearer guidance on how to allow it.
When the source host is known, the message includes an inline
`allowedDevOrigins` config snippet; when the source is missing or
opaque, it explains why Next.js cannot infer a host to allow.
2026-03-17 17:35:29 -07:00
Benjamin Woodruff 75c51c6541 Turbopack: Use debug = "line-tables-only" for dev builds (#91539)
This defaults to `true`: https://doc.rust-lang.org/cargo/reference/profiles.html#debug

Nobody on the team uses a debugger often enough for this to be worth the time tradeoff: https://kobzol.github.io/rust/rustc/2025/05/20/disable-debuginfo-to-improve-rust-compile-times.html

I'm gathering some rough numbers, and I'll add them to the PR.

After `cargo clean` and one `cargo build -p next-napi-bindings` with each profile (Linux arm64):

```
du -sh target/*
4.0K    target/CACHEDIR.TAG
7.9G    target/debug
14G     target/dev-with-debug
7.5M    target/generated
```

This is nearly half the size.

Due to cargo quirks, the `dev` profile defaults to the `target/debug` directory. Of course, any disk size wins you get are more than offset if you need to use a debugger and end up with an additional profile.

```
hyperfine -w 1 -r 5 -p 'cargo clean' 'cargo build --profile dev-with-debug -p next-napi-bindings' 'cargo build -p next-napi-bindings'
```

...pending...

(this is on https://github.com/bgw/benchmark-scripts/, on my M2 Macbook inside of a Linux VM this takes closer to 2m20s)
2026-03-17 17:20:12 -07:00
Benjamin Woodruff 39e705ca9f Turbopack: Merge release-with-assertions-no-lto profile into release-with-assertions (#91530)
- More profiles means more bloat to the `target` directory and more cold builds.
- There's no practical use case where we'd be okay with the performance hit of `debug-assertions` and not okay with the performance hit of `lto = false`. Neither profile was suitable for benchmarking.
- `release-with-assertions-no-lto` is too long to type and was giving me carpal tunnel.
2026-03-17 16:36:59 -07:00
Luke Sandberg 4de2201764 [turbopack] Share scratch buffer across shards using thread local (#90167)
Instead of allocating a scratch buffer for every shard, buffer them in a thread local.
2026-03-17 16:31:42 -07:00
nextjs-bot 668981482a v16.2.0-canary.103 v16.2.0-canary.103 2026-03-17 23:26:26 +00:00
Benjamin Woodruff 489eaef21e docs(turbopack): Remove old architecture.md file from turbopack crate (#91473)
All the stuff in this file is either better documented elsewhere or out-of-date and misleading.
2026-03-17 16:24:52 -07:00
Zack Tanner b2b802c043 block disallowed dev origins by default (#91507)
This removes the warn-only default behavior and enforces the dev-origin guard by default. Cross-origin requests to internal dev resources now block unless they match the built-in local allowlist or an explicit `allowedDevOrigins` entry. The tests are expanded to cover default blocking, configured-but-not-allowlisted hosts, missing Referer in the no-cors path, and same-site requests without an Origin, and the docs are updated to match the new behavior.
2026-03-17 16:02:33 -07:00
Tim Neutkens 97f420911d Move adapterPath from experimental to stable top-level config (#91535)
## Move `adapterPath` from experimental to stable

Graduates `adapterPath` from `experimental.adapterPath` to a top-level
`NextConfig` option, following the same pattern used for
`cacheHandlers`, `cacheComponents`, `typedRoutes`, and other options
that moved out of experimental.

### Changes

- **Type definition** (`config-shared.ts`): Added `adapterPath` to
`NextConfig` interface, marked `ExperimentalConfig.adapterPath` as
`@deprecated`, moved default value to top-level in `defaultConfig`,
updated `NextConfigRuntime` and `getNextConfigRuntime`
- **Zod schema** (`config-schema.ts`): Added `adapterPath` to top-level
`configSchema`
- **Backward compat** (`config.ts`): Added
`warnOptionHasBeenMovedOutOfExperimental` call so existing
`experimental.adapterPath` configs still work with a deprecation
warning, updated `applyModifyConfig` to read from `config.adapterPath`
- **Runtime references**: Updated `build/index.ts`, `app-page.ts`,
`app-route.ts`, `pages-handler.ts` to use `config.adapterPath` /
`nextConfig.adapterPath`
- **Tests**: Updated 4 test fixture `next.config` files
- **Docs**: Updated app router doc (removed `version: experimental`
frontmatter, top-level config example), pages router doc title, and v16
upgrade guide
2026-03-17 23:28:08 +01:00
nextjs-bot 668f8e3a60 Upgrade React from c80a0750-20260312 to 3f0b9e61-20260317 (#91522) 2026-03-17 22:37:18 +01:00
Tobias Koppers ee1f9d79ad Remove webpack stats generation from Turbopack (#91515)
### What?

Remove the `TURBOPACK_STATS` feature that generated webpack-compatible
`webpack-stats.json` files from Turbopack's output.

**Deleted:**
- `crates/next-api/src/webpack_stats.rs` — the entire 305-line Rust
implementation that built webpack-format stats (assets, chunks, modules,
entrypoints) from Turbopack's module graph

**Rust changes:**
- `crates/next-api/src/lib.rs` — removed `mod webpack_stats;`
- `crates/next-api/src/project.rs` — removed
`should_create_webpack_stats()` which read the `TURBOPACK_STATS` env var
- `crates/next-api/src/pages.rs` — removed `generate_webpack_stats`
import and stats output emission
- `crates/next-api/src/app.rs` — same

**TypeScript changes:**
- `packages/next/src/shared/lib/constants.ts` — removed `WEBPACK_STATS =
'webpack-stats.json'` constant
- `packages/next/src/shared/lib/turbopack/manifest-loader.ts` — removed
`loadWebpackStats()`, `writeWebpackStats()`, `mergeWebpackStats()`, the
`webpackStats` field, webpack type imports, and the `TURBOPACK_STATS`
env guard in `writeManifests()`
- `packages/next/src/server/dev/turbopack-utils.ts` — removed
`shouldCreateWebpackStats` flag and two `loadWebpackStats()` call sites
- `packages/next/src/build/handle-entrypoints.ts` — same

### Why?

This feature is no longer needed and adds dead complexity. It was opt-in
via `TURBOPACK_STATS=1` but nothing in the current codebase or tooling
depends on it.

### How?

Pure deletion — no behavior change for any existing user, as the feature
was opt-in via an environment variable that is no longer checked.

**Intentionally left untouched:**
- Webpack's own `stats.json` generation (non-Turbopack path)
- The Turbopack bundle analyzer / `analyze` feature
- `route-bundle-stats.json` in `.next/diagnostics/`

Co-authored-by: Tobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-17 13:58:51 -07:00
Zack Tanner d0a0474d3d fix allowedDevOrigins for no-cors requests (#91506)
This PR makes configured `allowedDevOrigins` apply to cross-site no-cors dev asset requests. When browsers omit Origin for subresource loads, the dev guard now falls back to `Referer` so explicit allowlisted hosts can load `/_next/*` resources in development.

Previously, when `allowedDevOrigins` was configured, cross-site no-cors requests to internal Next.js dev resources were still blocked even for allowlisted hosts, because that code path never consulted the allowlist.
2026-03-17 13:57:40 -07:00
Hendrik Liebau 89c6e73c81 Unflake two "use cache" tests (#91529)
[Flakiness
metric](https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest%20%40git.repository.id%3A%22github.com%2Fvercel%2Fnext.js%22%20%40test.name%3A%28%22use-cache%20should%20cache%20results%20for%20cached%20functions%20imported%20from%20client%20components%22%20OR%20%22use-cache%20should%20cache%20results%20for%20cached%20functions%20passed%20to%20client%20components%22%29%20%40test.status%3A%22fail%22%20%40duration%3A%3E%3D1ns&agg_m=count&agg_m_source=base&agg_t=count&citest_explorer_sort=timestamp%2Casc&cols=%40test.status%2Ctimestamp%2C%40test.suite%2C%40test.name%2C%40duration%2C%40test.service%2C%40git.branch&currentTab=overview&eventStack=&fromUser=false&index=citest&start=1772476060657&end=1773772060657&paused=false)

I'm not sure why these tests recently got much more flaky (they were
somewhat flaky before), but they definitely were missing `retry` blocks
around the assertions after clicking the reset button.
2026-03-17 12:47:27 -07:00
Tobias Koppers 4494261bd7 Remove devCacheControlNoCache experimental option (hard-code no-cache) (#91503)
### What?

Removes the `experimental.devCacheControlNoCache` config option entirely
and hard-codes `no-cache, must-revalidate` as the dev server
`Cache-Control` header value.

Previously the option controlled whether the dev server responded with:
- `no-store, must-revalidate` (default, `false`)
- `no-cache, must-revalidate` (opt-in, `true`)

This PR first flips the default to `true`, then removes the option
altogether — making `no-cache, must-revalidate` unconditional in all dev
code paths.

### Why?

`no-cache` is strictly better than `no-store` for the dev server:
- `no-cache` allows the browser to revalidate (conditional
`If-None-Match`/`If-Modified-Since` requests), letting the server
respond with `304 Not Modified` when nothing changed → faster page loads
during development.
- `no-store` forces a full re-fetch every time, discarding valid cached
responses.

Since `no-cache` is the correct behavior for all dev users, the toggle
has no remaining value and can be removed to simplify the codebase.

### How?

**Two commits:**

1. `bcec825` — Flip the default from `false` → `true`; update
tests/fixtures/manifest to reflect the new default.

2. `e6e919f` — Remove the option entirely:
- Deleted `devCacheControlNoCache?: boolean` from `ExperimentalConfig`
interface, `config-schema.ts` Zod schema, `defaultConfig`,
`NextConfigRuntime`, and `getNextConfigRuntime()`.
- Replaced all four conditional ternaries in `base-server.ts`,
`router-server.ts`, `pages-handler.ts`, and `app-page.ts` with the
hard-coded string `'no-cache, must-revalidate'`.
- Deleted the `dev-cache-control-no-cache-disabled` test suite (was
testing the `false` path which no longer exists).
- Simplified the remaining `dev-cache-control-no-cache` test (removed
experimental framing).
   - Synced `rspack-dev-tests-manifest.json`.

---------

Co-authored-by: Tobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
2026-03-17 20:13:01 +01:00