1. 04 Jul, 2026 2 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.78 · 00598045
      next-js-bot[bot] authored
      00598045
    • Hendrik Liebau's avatar
      Add `serverComponentsHmrCancellation` experimental flag (#95462) · 422c93ef
      Hendrik Liebau authored
      This is the first change in a series that will let `next dev` cancel a
      Server Components HMR refresh once a newer refresh supersedes it. Here
      we only introduce the `experimental.serverComponentsHmrCancellation`
      flag and plumb it to every place later changes will read it, without
      adding any behavior yet, so on its own this change is an inert no-op.
      
      The flag is declared in `ExperimentalConfig`, validated in the Zod
      schema, and defaults to `false` in `defaultConfig`. We thread it into
      the runtime config via the `NextConfigRuntime` pick list and
      `getNextConfigRuntime`, expose it to user-bundled client code through
      `define-env` as `process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION`,
      and pass it into the app render options in `base-server.ts` and the
      `app-page` build template. The edge SSR template hardcodes it to
      `false`, because edge rendering does not expose the Node response-close
      signal the cancellation relies on.
      
      So that the following changes are exercised as soon as their behavior
      lands, `config.ts` honors a
      `__NEXT_EXPERIMENTAL_SERVER_COMPONENTS_HMR_CANCELLATION` environment
      variable that forces the flag on while still respecting an explicit user
      config value, mirroring how `cachedNavigations` is rolled out. Both the
      `test-cache-components-dev` and `test-cache-components-prod` CI shards
      export that variable: the development shard so the feature is exercised
      once its behavior lands, and the production shard as a guard that this
      development-only feature stays inert in production even with the flag
      enabled. The default stays `false`; a later change flips it once the
      implementation is complete and drops the shard overrides.
      422c93ef
  2. 03 Jul, 2026 9 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.77 · 65dbff0a
      next-js-bot[bot] authored
      65dbff0a
    • Janka Uryga's avatar
      Avoid unnecessary rendering for validation in dev (#95394) · 127ac058
      Janka Uryga authored
      We're currently doing some unnecessary rendering in dev if Instant
      Validation is disabled. If we had a cache miss,
      `prepareValidationInputs` was always performing a full render, but
      that's not necessary if we're only going to run Static Shell Validation
      -- all we need is to go up to the runtime stage and then abort, which
      avoids waiting for uncached IO that isn't even needed.
      
      This PR fixes this and also reworks `prepareValidationInputs` to not be
      an absolute slog to read through. We do this by:
      1. splitting up the partialPrefetching path from legacy path
      2. separating *what* we need to render from *when* we render it -- if
      rendering work is needed, we return a
      [thunk](https://en.wikipedia.org/wiki/Thunk) (i.e. a lazily evaluated
      value) that will run the render if/when needed.
      
      This simplifies the logic and makes the code shorter (previously, it was
      easy to get lost in `if/else`s that don't fit on one screen)
      
      Unfortunately the lazy evaluation capability isn't currently very useful
      (other than the improved readability of `prepareValidationInputs`):
      - In theory, we could use this to delay the instant validation render
      (if needed) until after Static Shell Validation passes -- that way, if
      it fails, we wouldn't waste a render that gets thrown away. Currently
      this is not the case because the client module warmup uses the chunks
      from instant validation render. I think that we could remove this warmup
      -- we're running right after a dynamic render of the page finished, so
      i'm not sure how we could run into client modules that haven't been
      warmed yet. However, I'm leaving that for a future improvement.
      
      - However, if we need to do two renders (both for static and instant
      validation), this lets us parallelize them pretty elegantly, so it is
      useful for something
      127ac058
    • Janka Uryga's avatar
      fix: work around SWC compress bug (#95457) · 0da4c281
      Janka Uryga authored
      Works around a compiler bug in `SwcJsMinimizerRspackPlugin` that we
      found in #95394
      
      Some conditionals were getting miscompiled, from this:
      ```ts
      if (inputsFromNavigation) {
        if (areStagesCompatible) {
          const instantInputs = needsInstantValidation ? inputsFromNavigation : null
          const staticInputs = inputsFromNavigation
          return { instantInputs, staticInputs }
        }
      
        if (navigationHasAppShell(navigationKind)) {
          const instantInputs = needsInstantValidation ? inputsFromNavigation : null
          const staticInputs = LAZY_RUNTIME_PRERENDER
          return { instantInputs, staticInputs }
        }
      
        const instantInputs = needsInstantValidation ? LAZY_FULL_RENDER : null
        const staticInputs = inputsFromNavigation
        return { instantInputs, staticInputs }
      }
      ```
      into this (in
      `packages/next/dist/compiled/next-server/app-page-turbo.runtime.dev.js`)
      ```js
      if (inputsFromNavigation)
        return areStagesCompatible || navigationHasAppShell(navigationKind)
          ? {
              instantInputs: needsInstantValidation
                ? inputsFromNavigation
                : null,
              staticInputs: inputsFromNavigation,
            }
          : {
              instantInputs: needsInstantValidation ? LAZY_FULL_RENDER : null,
              staticInputs: inputsFromNavigation,
            }
      ```
      In the compiled version, the three branches get incorrectly merged into
      two: if `navigationHasAppShell(navigationKind)`, static inputs are
      `inputsFromNavigation` instead of `LAZY_RUNTIME_PRERENDER`. We're
      guessing that this is a bug in some optimization of conditional returns;
      disabling `compress.conditionals` in the minimizer seems to work around
      it.
      0da4c281
    • Marco Dotzler's avatar
      docs: Update FormEvent to SubmitEvent in form handling example (deprecated in… · 1092d215
      Marco Dotzler authored
      docs: Update FormEvent to SubmitEvent in form handling example (deprecated in React 19.2.10+) (#95453)
      1092d215
    • Vercel Release Bot's avatar
      Update font data (#95441) · c7a51fc6
      Vercel Release Bot authored
      This auto-generated PR updates font data with latest available
      Co-authored-by: 's avatarnext-js-bot[bot] <279046576+next-js-bot[bot]@users.noreply.github.com>
      c7a51fc6
    • Hendrik Liebau's avatar
      Ignore-list internal frames whose source maps chain to original sources (#95448) · dd8b154d
      Hendrik Liebau authored
      Next's dev error output (terminal logs and the browser overlay)
      ignore-lists framework-internal stack frames. The forked
      `EvalSourceMapDevToolPlugin` recomputes this ignore-list per module
      because the vendored `webpack-sources` has no runtime `ignoreList`
      support, so it drops the field when it combines a module's input source
      map with the generated mappings. `shouldIgnorePath` matches on the
      emitted source path, which works while a source resolves back to its
      module. But a Next-internal module that ships an input source map (its
      `.js.map`, which taskfile-swc marks entirely ignore-listed) resolves its
      sources to the original files such as `src/server/web/adapter.ts`, which
      no longer contain the `node_modules`/`next/dist` marker and no longer
      resolve back to a module. Those frames then escape ignore-listing and
      leak into both the terminal output and the overlay.
      
      For such unresolved sources this falls back to the module's own resource
      path, so a frame whose module lives in `node_modules`/`next/dist` stays
      ignore-listed even when its source map points at the original source.
      The fallback applies only to a `NormalModule`, whose sources all belong
      to that one module; a `ConcatenatedModule` merges several modules'
      sources under one map and is left to the path check, which the dev
      `eval-source-map` devtool never produces anyway.
      dd8b154d
    • Hendrik Liebau's avatar
      Type resolved `cacheLife` profiles, dropping runtime asserts (#95428) · f83bc252
      Hendrik Liebau authored
      Runtime `"use cache"` code validated the default cache-life profile on
      every invocation because `cacheLifeProfiles` was typed as optional with
      partial profiles: `assertDefaultCacheLife` on the generate and RDC-read
      paths, a per-`cacheLife()` presence `InvariantError`, and optional
      chaining on reads.
      
      Config normalization already guarantees this once:
      `assignDefaultsAndValidate` builds the config from `{...defaultConfig,
      ...config}`, so `cacheLife` is always present, and it backfills the
      `default` profile's `stale`, `revalidate`, and `expire`. This moves that
      guarantee into the type. A new `ResolvedCacheLifeProfiles` (in
      `config-shared`) types the `default` profile as `Required<CacheLife>`
      and overrides `NextConfigComplete.cacheLife`, and the type is threaded,
      non-optional, through the render options, work store, and the build,
      export, and dev workers. Runtime code now reads
      `cacheLifeProfiles.default` directly, and the asserts, the presence
      guard, and the optional chaining are gone.
      
      The proxy (middleware) work store is the one construction site without a
      resolved profile: the proxy does not support `"use cache"`, so it never
      reads `cacheLife`. It is given a sentinel whose `default` getter throws
      if ever read, matching the "never read" sentinels already used for its
      other unused render options.
      f83bc252
    • Sebastian "Sebbie" Silbermann's avatar
      Split typeof-window server requires into .browser variants (#95201) · d6594bd1
      Sebastian "Sebbie" Silbermann authored
      First batch of fixes that addresses most of the recent bundle size
      regressions.
      d6594bd1
    • Sebastian "Sebbie" Silbermann's avatar
      Collect modules with browser variants statically (#95200) · d3169de7
      Sebastian "Sebbie" Silbermann authored
      Instead of hardcoding the list, we now automatically detect any
      `.browser` sibling and create a compiler alias for that module.
      
      Together with a linting rule, we'll ensure no future regressions are
      handled automatically (detection of conditional require and missing
      .browser sibling).
      
      This isn't the smoothest DX yet. Ideally we'd generate the list at
      Next.js compile time (i.e. before publishing) to avoid having to rerun a
      script (I'll follow-up). Generating the list during build time (next dev
      or next build) is just another tiny cost users would have to pay.
      d3169de7
  3. 02 Jul, 2026 25 commits
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.76 · 7e2efbc8
      next-js-bot[bot] authored
      7e2efbc8
    • dan's avatar
      Fix navigation getting reverted when a Server Action is in flight (#95391) · db4e6231
      dan authored
      Alternative to https://github.com/vercel/next.js/pull/95188.
      Fixes
      https://github.com/vercel/next.js/issues/86151#issuecomment-4802297986.
      
      This fixes a bug where a navigation would spuriously get reverted once a
      Server Action settles.
      
      ## Test Plan
      
      New e2e tests that fail before the fix and pass after the fix. I've
      steered the agent to cover both the broken case now *and* the case that
      the regressing PR (#82674) was originally trying to fix. The test itself
      is reduced from https://github.com/vercel/next.js/pull/95188.
      
      Also, verified before/after in a real tiny app based on the tests.
      Before the fix, it reverts to the previous route; after the fix, it
      stays on the last route as it should.
      
      The tests themselves are a bit wonky and do some timing assertions. I
      had no luck reducing them further.
      
      ## Summary
      
      *Note: Everything below is written by Fable.*
      
      Fixes a regression where a navigation could get reverted shortly after
      it committed if a Server Action was still in flight when the navigation
      started: the destination page renders, then the router snaps back to the
      previous URL. Regressed in 15.5.1 via #82674. Reported in #86151, with a
      repro and initial investigation by @errmakov in #95188.
      
      ### Why?
      
      When a navigation starts while a Server Action is in flight, the router
      discards the action and the navigation takes its place at the head of
      the action queue. The discarded action still runs to completion. Since
      #82674, its completion also called `runRemainingActions`, which advances
      the queue — but the discarded action is no longer at the head of the
      queue, the navigation is. This started the next queued action while the
      navigation was still running, computed against router state that didn't
      include the navigation yet. Those actions send their requests with the
      previous URL, and applying their responses reverts the navigation.
      
      The promise rejection path had the same problem even before #82674: a
      discarded action that rejected would also advance the queue.
      
      ### How?
      
      Only the settlement of the action at the head of the queue may advance
      the queue. A discarded action's settlement (resolve or reject) now only
      records whether the action revalidated, and the deferred refresh is
      flushed once the queue goes idle. This keeps the behavior #82674 was
      after: no refresh for discarded actions that didn't revalidate, and a
      refresh for those that did — including when they settle mid-navigation,
      a case that could previously lose the refresh entirely.
      
      ---------
      Co-authored-by: 's avatarerrmakov <ide404@gmail.com>
      db4e6231
    • Hendrik Liebau's avatar
      Fix false-positive nested-cache error for a short default profile (#95373) · b420536f
      Hendrik Liebau authored
      Overriding the `default` `cacheLife` profile with a short cache life
      (the built-in `expire` is `INFINITE_CACHE`) makes every `'use cache'`
      without an inline `cacheLife()` inherit that short life. In this
      configuration the nested-`'use cache'` error, in both its short-`expire`
      and zero-`revalidate` variants, fired in two cases where it should not
      have.
      
      The error exists to catch a nested cache silently shortening an outer
      cache that has no explicit `cacheLife`, degrading it to a dynamic hole
      the developer did not choose. But with a short default profile, a single
      non-nested `'use cache'` already resolves to a short life with nothing
      nested, so the error fired with no nesting at all: in production this
      killed the build, and in development it threw on the request. And even
      for a genuinely nested cache, the warning is pointless here, because the
      default profile already makes every cache a dynamic hole, so there is no
      silent degradation to surprise the developer.
      
      The throw condition keyed on a short life that was not set through an
      inline `cacheLife()`, and a value inherited from the `default` profile
      is non-explicit, so it matched. This change additionally requires that a
      dynamic nested cache actually propagated its short life upward
      (`dynamicNestedCacheError` is set) and that the `default` profile is
      itself prerenderable. Otherwise the short-lived entry is omitted as a
      dynamic hole instead, exactly as an inline short `cacheLife()` already
      was. Genuine nesting under a prerenderable default profile still errors.
      
      The nesting condition also subsumes the dev-only private-cache
      exclusion: a private cache's `revalidate: 0` is forced by us rather than
      by a nested cache and never carries a nested error, so the explicit
      `kind !== 'private'` check is no longer needed.
      b420536f
    • Hendrik Liebau's avatar
      Skip saving `expire: 0` values in the default cache handler in prod (#95363) · 34dbafb4
      Hendrik Liebau authored
      A `'use cache'` value with an explicit `cacheLife({ expire: 0 })` is
      expired the moment it is produced, so in production the `'use cache'`
      wrapper regenerates it on every read rather than serving the stored
      copy. The entry written to the cache handler is never served back, so
      persisting it is wasted work, and for a remote handler a needless
      round-trip and stored payload.
      
      Whether to skip that write is left to each cache handler. This change
      implements it in the built-in default handler; a custom handler can opt
      into the same behavior. Beyond the saved write, this makes `cacheLife({
      expire: 0 })` a reliable way to keep a value out of the server-side
      cache handler, which covers two cases. In a conditional opt-out, a
      function with an otherwise normal cache life sets `expire: 0` for a
      result that is not worth persisting, for example when an upstream fetch
      errored. In client-only caching, a value is `expire: 0` by design so
      that it lives only in the client cache, via Cached Navigations or
      Runtime Prefetches when the route opts in, and never on the server.
      
      The skip is gated on `!process.env.__NEXT_DEV_SERVER`. In production the
      value is regenerated on every read regardless, so not storing it changes
      nothing that is served. Development keeps storing it, because the
      default handler's minimum retention serves the previously cached value
      across reloads while the entry re-warms in the background.
      
      A new `use-cache-default-handler-expire-zero` end-to-end test enables
      the default handler's debug logging (`NEXT_PRIVATE_DEBUG_CACHE`) and
      asserts on its `set()` decisions. Because the debug output is only
      available from the CLI, the test skips deployment.
      34dbafb4
    • Benjamin Woodruff's avatar
      [ci] Disable mid-stack PR optimization for native PR stacks (#95427) · 6f592dec
      Benjamin Woodruff authored
      https://vercel.slack.com/archives/C04KC8A53T7/p1783018076576349
      
      <img width="1015" height="347" alt="Screenshot 2026-07-02 at 11 57
      05 AM"
      src="https://github.com/user-attachments/assets/74d99079-d165-435a-aece-161862795ef6"
      />
      
      If we're in the middle of a stack, but the PRs below us in the stack are
      already merged, we should not skip CI jobs. This logic isn't smart
      enough to handle that.
      6f592dec
    • dan's avatar
      Fix history push getting treated like replace when followed by refresh (#95392) · ee7f8892
      dan authored
      Currently this drops a history push:
      
      ```tsx
      router.push('/target') // this entry was getting lost
      router.refresh()
      ```
      
      So you end up on `/target`, but the previous page's history entry was
      replaced instead of a new one being pushed. As a result, pressing Back
      yanks you past the previous page.
      
      It seems like a regression from #88046. I verified it's broken in 16.2,
      but it was working in 16.1.
      
      This fixes the regression.
      
      ## Test Plan
      
      New test fails before, works after. Also tried it in a small repro
      project.
      
      ---
      
      *Everything below is written by Claude.*
      
      The push happens when React commits a state whose `pushRef.pendingPush`
      is true (`HistoryUpdater`). Refresh-type actions (`refresh`,
      `hmr-refresh`, `server-patch`) create their state with a fresh `pushRef`
      where `pendingPush` is false. React can skip committing the superseded
      navigation state entirely, so `pendingPush: true` is never observed and
      the push never happens — `HistoryUpdater` replaces the previous page's
      history entry with the new URL instead of pushing a new one. Going back
      after that does nothing: the entry the browser returns to has no state,
      and the popstate handler ignores entries without state.
      
      The old router carried the previous state's `pendingPush` forward unless
      a reducer set it explicitly
      (https://github.com/vercel/next.js/blob/5ccc9078e0/packages/next/src/client/components/router-reducer/handle-mutable.ts#L41-L43),
      and the refresh reducer never set it. That guard was lost in #88046,
      which deleted `handleMutable` and moved the final state assembly into
      `completeSoftNavigation`, where `pushRef` is created fresh with
      `pendingPush: navigateType === 'push'`. This PR restores the old
      behavior there. There's no double push: if the navigation's state did
      commit, the push already happened and consumed the flag
      (`HistoryUpdater` mutates the `pushRef`), and its same-URL check turns a
      leftover flag into a replace anyway.
      
      In dev, an `hmr-refresh` dispatched while compiling the destination
      route on demand can supersede the navigation the same way. That's what's
      behind the recent `browser back to a revalidated page` flakes in
      `navigation.test.ts` (traced in #95385).
      
      <!-- NEXT_JS_LLM_PR -->
      ee7f8892
    • Vercel Release Bot's avatar
    • Partha Shankar's avatar
      fix(config): correctly validate cacheHandlers names (#95358) · 8688f98b
      Partha Shankar authored
      ## What?
      
      The current `cacheHandlers` validation uses `/[a-z-]/`, which only
      checks whether a key contains at least one lowercase letter or hyphen.
      
      As a result, invalid keys such as `abc123`, `abc_123`, `abc.def`, and
      `handler!` are accepted even though they contain characters outside the
      documented allowed set.
      
      ## Why?
      
      The validation error states that handler names must only contain `a-z`
      and `-`, but the current implementation does not enforce that constraint
      because the regex is not anchored.
      
      ## How?
      
      - Replace `/[a-z-]/` with `/^[a-z-]+$/` so the entire handler name is
      validated.
      - Add regression tests covering both valid and invalid handler names.
      
      ## Testing
      
      - Added regression tests in `packages/next/src/server/config.test.ts`.
      
      <!-- NEXT_JS_LLM_PR -->
      8688f98b
    • Benjamin Woodruff's avatar
      [ci] Actually migrate Turbopack jobs back to ARM (#95386) · 24262a82
      Benjamin Woodruff authored
      This is embarrassing, I wasn't paying enough attention when I put up
      #95374. We have to both change the build dependency *and* switch the
      machine type...
      24262a82
    • Hendrik Liebau's avatar
      Recover from blocking routes under Instant Navigation lock when deployed (#95227) · f14048b6
      Hendrik Liebau authored
      The Instant Navigation feature locks navigation to a route's static
      shell so you can inspect the prefetched shell before any dynamic content
      streams in. It is controlled by a cookie: in development the Instant
      Navigation DevTools set and clear it for you, and in any environment you
      can drive it by hand by setting the cookie in the browser's DevTools. A
      blocking route (one with a Suspense boundary above `<body>`, or `export
      const instant = false`) has an empty static shell, so when you do a full
      page load of such a route while the cookie is set, that empty shell is
      served as a blank document with no way to release the lock, and every
      reload renders the same blank shell and leaves you stuck.
      
      Previously the handler threw for an empty shell. In development that
      surfaces as the error overlay, which is what we want, and the catch
      clears the cookie so a reload recovers. It did not recover when
      deployed: the cookie could only be cleared via `Set-Cookie`, which
      cannot take effect there because the empty shell is served from the ISR
      cache with its response headers already committed, so the user stayed on
      the blank shell across reloads. In `next start` it recovered but
      rendered only a generic "Internal Server Error" page.
      
      With this change a deployed blocking route recovers. For the empty-shell
      case we serve a minimal document whose inline script clears the cookie
      client-side, so the next full page load renders the route normally; we
      clear it from the document rather than with `Set-Cookie` because the
      headers are already committed when the shell is served from the cache.
      Development still throws so the error overlay shows. As a secondary
      improvement, `next start` now serves that same document with a readable
      explanation instead of the generic "Internal Server Error" page.
      
      The blocking-route test now asserts the user-facing outcome (after a
      reload the route renders normally) rather than transport details such as
      the status code and `Set-Cookie`, which legitimately differ across dev,
      `next start`, and deploy, and it now runs on deploy as well.
      f14048b6
    • Hendrik Liebau's avatar
      Make Instant Navigation Testing full-page loads work when deployed (#95222) · 31774433
      Hendrik Liebau authored
      This makes full-page loads work under the Instant Navigation Testing API
      on a deployment, not just under `next dev` and `next start`. With the
      API active, a full-page load (a reload, an MPA navigation, or direct URL
      entry) on a deployment failed with a minified React hydration error, and
      releasing the lock then hard-reloaded the page instead of resolving
      client-side. Client-side navigations under the lock already worked; the
      gap was full-page loads.
      
      The API works by injecting an inline script that sets
      `self.__next_instant_test`, which the client reads at `app-index` init
      as its hydration source. That read only happens on a full-page load;
      client-side navigations go through the segment cache and the lock and
      never read it. The script was previously injected at request time
      through a transform stream, which runs only when the function renders
      the document. On a deployed full-page load the browser instead parses
      the prebuilt static prelude served from the edge cache, which was
      prerendered without the cookie and so carried no script, leaving
      `self.__next_instant_test` undefined.
      
      When the testing API is enabled (in development, or in a production
      build via `experimental.exposeTestingApiInProductionBuild`), we embed
      the cookie-guarded bootstrap into the prerendered prelude through
      React's `bootstrapScriptContent`, so it lands in the cached static shell
      and runs before the client bootstrap module. That production-build flag
      is meant for protected preview environments, so a normal production
      build never embeds the script, and even where it is embedded it stays
      inert on requests without the instant-navigation cookie (the prelude is
      shared across all requests). The same content is folded into the dynamic
      render path in `renderToStream`, and the now-redundant request-time
      transform is removed.
      31774433
    • Hendrik Liebau's avatar
      Clear a resurrected instant cookie on unlock so a hard reload recovers (#95398) · f15aa4e6
      Hendrik Liebau authored
      Under the Instant Navigation Testing lock, an MPA page load's bootstrap
      writes the captured cookie value asynchronously via `cookieStore`. When
      a scope is released (the external actor deletes the cookie), that
      pending write can land in the narrow gap between the delete and the
      deleted-event handler that tears the lock down, resurrecting the cookie
      after the scope has ended. If the unlock then falls back to a hard
      reload, which happens when the freshly loaded shell has not hydrated the
      router yet, the reload carries the resurrected cookie, the server serves
      the shell again, and the page re-enters instant mode with no scope left
      to release it, so the deferred content never streams in and the
      navigation hangs.
      
      Once the lock is released, `writeCookieValue`'s guard rejects any
      further captured write, so the deleted-event handler now clears the
      cookie right after `releaseLock` to neutralize a write that resurrected
      it in the gap, and an added guard ignores the re-entrant change event
      that the clear itself produces.
      
      This removes a family of flaky timeouts in
      `instant-navigation-testing-api.test.ts`, where a full-page (MPA)
      navigation inside an `instant()` scope would intermittently never stream
      in its deferred content after the scope exits. [Example failing
      run](https://github.com/vercel/next.js/actions/runs/28572283366/job/84712848241?pr=95227)
      
      ---
      
      <sub>Stack created with <a
      href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
      href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
      f15aa4e6
    • Joseph's avatar
      fix: handle prototype-colliding segment names in segment explorer trie (#95403) · 0d4df38b
      Joseph authored
      Fixes: https://github.com/vercel/next.js/issues/95395
      
      ```console
      let x = {}
      x['constructor']; // function
      x['toString']; // function
      x = Object.create(null);
      x['constructor']; // undefined
      x['toString'] // undefined
      ```
      0d4df38b
    • Andrew Clark's avatar
      Prefetch links nearest the top of the document first (#95393) · c099530e
      Andrew Clark authored
      ### Why
      
      Most viewport prefetches are scheduled via a shared
      `IntersectionObserver`. When several links enter the viewport at once
      (e.g. on initial load), the observer reports them in document order and
      we scheduled them in that order. Because the prefetch scheduler gives
      the highest priority to the *most recently scheduled* task, this meant
      the link **lowest** in the document ended up with the highest priority —
      the opposite of a sensible default.
      
      ### What
      
      Iterate each observer batch in reverse, so the link nearest the **top**
      of the document is scheduled last and therefore prioritized. The topmost
      link isn't guaranteed to be the most important, but as a default
      heuristic it's more reasonable than favoring whichever link happens to
      be lowest in the document.
      
      Also updates the two hover tests in `prefetch-scheduling`, whose
      expected ordering was coupled to the old bottom-first default (the set
      of route trees prefetched within the concurrency limit flips from pages
      7,6,5,4 to 1,2,3,4). The behaviors they assert are unchanged, and a new
      test covers the top-of-document prioritization.
      
      ---
      
      Supersedes #94902, which was opened from a fork. The "Test new and
      changed tests when deployed" jobs cannot pass on fork PRs — `vercel
      link` fails with "No existing credentials found" because
      `secrets.VERCEL_ADAPTER_TEST_TOKEN` is not available to `pull_request`
      runs from forks. This PR is the same change (rebased onto latest canary)
      on an upstream branch so the deploy jobs get credentials.
      
      <!-- NEXT_JS_LLM_PR -->
      c099530e
    • Andrew Clark's avatar
      Fix metadata title dropped on soft navigation with Cache Components (#95315) · 27e225f4
      Andrew Clark authored
      With `cacheComponents` + `partialPrefetching`, navigating to an
      already-prefetched route with a dynamic `generateMetadata` left
      `document.title` permanently empty until a hard reload.
      
      The prefetch cached the head as complete using the server's
      `isHeadPartial` flag, which is unreliable under Cache Components. Derive
      the head's partiality from `isResponsePartial` instead, as segment data
      already does, so a dynamic head is fetched and applied on navigation
      while a fully static head stays complete.
      
      Fixing the flag exposed a latent issue in the prefetch scheduler: during
      a speculative prefetch, the head was unconditionally runtime-prefetched,
      which previously went unnoticed because the head was mismarked as
      complete. The head is now runtime-prefetched only when a segment in the
      new part of the tree is a candidate for runtime prefetching — it rides
      along with that request rather than spawning a standalone one. If
      nothing in the new part of the tree is a runtime prefetch candidate, the
      head is fetched during the navigation instead. This makes the
      scheduler's metadata-only request path dead code, so it's removed.
      
      Fixes #95268.
      
      <!-- NEXT_JS_LLM_PR -->
      27e225f4
    • Hendrik Liebau's avatar
      Cache short-`expire` `'use cache'` values across dev reloads (#95362) · 2850659b
      Hendrik Liebau authored
      Development has recently gained several mechanisms that make `'use
      cache'` reloads fast under Cache Components: `'use cache: private'`
      entries are persisted in a dedicated in-memory handler,
      `cacheMaxMemorySize: 0` uses a real in-memory handler instead of the
      no-op stub, and custom handlers are fronted by a fast built-in handler
      through the tiered handler. One case was still missing. A value that
      opts into a dynamic, client-only life with an explicit short `expire`
      (for example `cacheLife({ expire: 0 })`, or the built-in `'seconds'`
      profile) was treated as a miss on every reload, for both the built-in
      default handler and custom handlers, so reloads re-ran the cache
      function and streamed slowly.
      
      The reason is that `expire` is the value's expiration bound, the longest
      it may still be served before it has to be treated as expired. That is
      its purpose in both dev and production; what differs is which threshold
      the built-in in-memory handler enforces. In `next dev` it serves stale
      entries up to `expire` to keep reloads fast, whereas in production it
      drops them earlier, once past `revalidate`. An `expire` of zero
      therefore leaves the dev handler no window in which a reload can be
      served from the cache, and the wrapper's serve-vs-regenerate check,
      which also keys on `expire`, regenerates instead.
      
      This change extends the same dev-only treatment to those values without
      altering their resolved cache life. The built-in default handler now
      retains an entry for at least `MIN_PRERENDERABLE_EXPIRE` in dev, a
      minimum the custom front handler inherits by being a built-in default
      handler, and the wrapper applies the same minimum when deciding whether
      to serve or regenerate. That affects the retain and serve decisions
      only; the entry keeps its real `expire`, so the staged dev render still
      resolves it at the appropriate stage rather than in the shell stage. A
      short-`expire` entry is also re-warmed in the background on every
      dynamic request render, so a reload serves the previously cached value
      immediately and the freshly recomputed one appears on the next reload.
      This is the same stale-while-revalidate trade-off already accepted for
      the private-cache and `cacheMaxMemorySize: 0` dev optimizations, which
      likewise favor a fast reload over serving a value these configurations
      would not otherwise cache at all. For custom handlers the re-warm
      re-executes the function and writes through to the backing.
      
      Unlike the private-cache case, we deliberately do not force a dynamic
      cache life here, because forcing `revalidate: 0` would leak into the
      cache life propagated to an enclosing `'use cache'` and trip the
      nested-dynamic error with the wrong message. And unlike the size-0 case,
      keeping the resolved life alone is not enough, because a short `expire`
      is exactly what makes the dev handler drop the entry, which is why the
      minimum retention is needed. Because the dev front handler now enforces
      that minimum, the tiered handler can no longer evict a stale front entry
      by writing `expire: 0` (the minimum would keep it alive), so
      `toExpiredEntry` now writes a negative `expire`, which the default
      handler recognizes as an eviction sentinel and reports as missing
      regardless of the retention minimum. This mirrors the existing
      `revalidate = -1` convention, though a negative `expire` means the entry
      is dropped rather than served-but-revalidated.
      
      Everything is gated on `process.env.__NEXT_DEV_SERVER`, so production
      behaves exactly as before: short-`expire` values keep their real cache
      life, and configured handlers are used directly. New development tests
      cover the built-in and custom-handler cases, asserting that a cache-miss
      navigation shows the Suspense fallback while a cache-hit one does not,
      and that a reload serves the cached value yet converges to a fresh one.
      
      
      ---
      
      <sub>Stack created with <a
      href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
      href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
      2850659b
    • next-js-bot[bot]'s avatar
      v16.3.0-canary.75 · 5ffbe9c3
      next-js-bot[bot] authored
      5ffbe9c3
    • Sebastian "Sebbie" Silbermann's avatar
    • Hendrik Liebau's avatar
      [test] Enable deploy tests for the Instant Navigation Testing API suite (#95236) · 051e6979
      Hendrik Liebau authored
      The Instant Navigation Testing API suite set `skipDeployment: true`, so
      it only ran under `next dev` and `next start`, which never exercise the
      real `instant()` flow against a deployment, where the prefetched shell
      is served from the ISR or edge cache rather than rendered per request.
      This removes `skipDeployment` so the suite runs on deploy and can catch
      regressions that are invisible locally.
      
      Running the suite on a deployment surfaced that the `runtime params are
      excluded from instant shell` tests, which asserted that
      `/dynamic-params/unknown` keeps its param out of the instant shell, do
      not hold there. That route defines `generateStaticParams` (for `hello`),
      which makes its fallback shell upgradeable: on a deployment the first
      concrete navigation to a non-listed param triggers a background
      prerender of the upgraded shell with that param, whose result (HTML and
      all segments) is written into the ISR cache. Subsequent prefetches then
      read those upgraded segments, so the prefetch the instant shell reads
      already contains the resolved param and the Suspense fallback never
      appears. The same fallback-shell upgrade is expected under `next start`,
      which is meant to persist the background prerender to disk, but for
      reasons to be investigated separately it does not currently affect these
      prefetches there, so the assertion held under `next dev` and `next
      start` but broke on a deployment.
      
      This upgrade is correct behavior, because a non-listed route param
      legitimately becomes static once the route has been prerendered for it,
      so it is not a reliable runtime value to assert exclusion on. The
      exclusion tests now run against a route that defines no
      `generateStaticParams` and is never upgradeable
      (`ungenerated-params/[slug]`), so its param never enters the prefetched
      shell: under the instant lock the Suspense fallback is shown, and the
      resolved value appears only after the lock is released. The
      client-navigation, page-load, and hover-prefetch variants share that
      route with a stable param and are grouped with the existing
      ungenerated-params case, whose duplicate client-navigation test is
      removed.
      
      With the exclusion tests moved off it, the `dynamic-params/[slug]` route
      only serves the statically generated `hello` slug, so it is renamed to
      `static-params/[slug]` and continues to back the `statically generated
      params are included in instant shell` tests. The `runtime params are
      excluded from instant shell` describe now holds only the search-param
      cases and is renamed to `search params are excluded from instant shell`.
      
      A larger set of tests now stays skipped on deploy. Any test that drives
      a full-page load under the instant lock, whether a plain-anchor MPA
      navigation or a reload, relies on the lock re-engaging on the freshly
      loaded document through the prerendered-shell bootstrap
      (`self.__next_instant_test`), which is only embedded into the
      deploy-served prelude in #95222. Without it the lock engages unreliably
      on a deployment, so the out-of-band client fetch is not blocked and the
      deferred data never streams back, and these tests time out or fail. The
      `clears the instant cookie and serves an error when the static shell is
      empty` test stays skipped for a separate reason, a blocking route whose
      empty static shell would otherwise leave the user stuck, which #95227
      fixes.
      051e6979
    • Hendrik Liebau's avatar
      Await reused in-flight prefetch entries under Instant Navigation lock (#95301) · 97b71d02
      Hendrik Liebau authored
      A locked instant() navigation could time out flakily on routes that use
      runtime prefetching (e.g. `allow-runtime` pages). The navigation reads
      the segment cache only after its prefetch drains, but the prefetch only
      awaits the entries it spawned itself. When an earlier prefetch in the
      scope had already started a more-specific runtime upgrade (a
      `PPRRuntime` page entry) that was still in flight, the navigation reused
      that entry without tracking it, drained without waiting for it, and read
      while it was still pending. The read then fell back to the less-specific
      fulfilled `RuntimeShell` entry (the static shell with no resolved
      value), so the awaited content never surfaced and the test timed out.
      The race only lost under CPU contention, which is why it reproduced in
      the prod flake-detection job on slow containers but almost never
      locally.
      
      This change tracks an in-flight entry at the point the navigation reuses
      it. In `readOrCreateSegmentCacheEntry`, when a locked navigation reuses
      an existing `Pending` entry it did not spawn, it now registers that
      entry on the navigation's prefetch via
      `trackNavigationLockPrefetchEntry`, so the prefetch awaits it before the
      navigation reads. The read then finds the resolved entry rather than the
      shell.
      
      The fix is content-neutral: the entry is looked up by the concrete vary
      path, so it is whatever the navigation would read at that key
      regardless. Tracking only controls whether the navigation awaits the
      entry now versus suspends on it during render, so it cannot surface an
      entry the navigation would not otherwise read, and it leaves session
      ownership untouched (so reads still never miss). Tracking is deduped, so
      reusing an entry the navigation already spawned is a no-op.
      
      This also lowers the per-action timeout in the
      `instant-navigation-testing-api` test suite to below jest's test
      timeout, so a future stalling `waitFor` fails with its own locator
      (naming the element that never appeared) instead of a bare test-level
      timeout that hides which assertion hung. That edit also marks the suite
      as changed, so CI's flake-detection job re-runs the previously flaky
      runtime-prefetch tests and confirms they are now stable.
      
      
      ---
      
      <sub>Stack created with <a
      href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
      href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
      97b71d02
    • Hendrik Liebau's avatar
      [test] Park the blocking-fallback segment on a withheld param (#95300) · 58a0c3db
      Hendrik Liebau authored
      The `blocking-fallback/[lang]/[scope]` fixture's deeper page previously
      rendered a static title and gated its only dynamic work on a `cookies( `
      read. Under instant() the committed app shell is allowed to read reque t
      cookies without blocking, which is exactly what the cookie assertions n
      this suite rely on, so a segment gated only on cookies renders into th
      shell and its title commits while the lock is held. Under CPU load thi
      surfaced as a flaky leak of `blocking-scope-title` during the parke
      navigation, and instrumenting the lock's read path confirmed the cause
      the test failed precisely when the app-shell (RuntimeShell) entry
      committe the deeper segment and passed when the speculative static
      prefetch (PPR) e try committed, a commit-order race between the two
      prefetch responses
      
      This change makes `ScopePage` await `params` before rendering anything.
      Because `scope` is an uncovered fallback param (the route has no
      `generateStaticParams`), awaiting it suspends the whole segment during
      the app-shell prerender and keeps both the title and the cookie value
      out of the committed shell regardless of which prefetch wins. The
      segment streams in only after the lock releases, when the real dynamic
      render resolves `params`.
      
      The underlying app-shell-versus-speculative-prefetch race is a known,
      likely temporary limitation; the `cookies in the instant shell` describe
      block documents the related case and the planned fix of opting
      cookie-reading routes into partial or runtime prefetching. The test
      comment is updated to describe this param-gated parking instead of the
      previous cookie-based description.
      
      
      ---
      
      <sub>Stack created with <a
      href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
      href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
      58a0c3db
    • Hendrik Liebau's avatar
      Make `instant()` resilient to a leaked navigation-testing cookie (#95375) · 64fbcb60
      Hendrik Liebau authored
      The Instant Navigation Testing helper threw `An instant() scope is
      already active` whenever it found the `next-instant-navigation-testing`
      cookie set at acquire time. Because Playwright reuses one browser
      context across every test in a file, a cookie left behind by an earlier
      scope poisoned the shared jar and made every following `instant()` call
      fail fast, cascading through the suite.
      
      The cookie can outlive its scope: under the lock, each MPA page load
      asynchronously re-writes it via `cookieStore`, and that write can land
      right after the scope's release deletes it but before the client
      observes the deletion, resurrecting a captured-state entry that the
      change handler then ignores.
      
      Nesting is now tracked in-process, keyed on the browser context, rather
      than inferred from cookie presence. The context is the right granularity
      because the instant cookie is context-scoped: concurrent scopes on the
      same context share one cookie and conflict, while scopes on separate
      contexts or browsers are independent and must both run. On acquire we
      clear any stale cookie instead of throwing, and the release re-reads and
      re-deletes until the cookie stays gone, defeating the resurrection race.
      New tests cover recovery from a leaked cookie and concurrent scopes
      across separate contexts.
      
      
      ---
      
      <sub>Stack created with <a
      href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
      href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
      64fbcb60
    • Benjamin Woodruff's avatar
      [ci] Avoid running full CI mid-stack for GH-native stacks, same as we do for Graphite (#95218) · a26a1d64
      Benjamin Woodruff authored
      Running CI only on the top and bottom of the stack avoids expensive
      `O(n^2)` behavior when merging one PR at a time and recursively rebasing
      all the others starting at the bottom of the stack.
      
      GitHub added this to the webhook/GH actions object for us to be able to
      do this: https://vercel.slack.com/archives/C01SKER9S1G/p1777926655162839
      
      Prior to this PR being part of a stack, fails open (runs full CI):
      <img width="1938" height="993" alt="Screenshot 2026-06-26 at 3 03 37 PM"
      src="https://github.com/user-attachments/assets/54d6055a-2860-45b3-a03a-a9356b3db2a4"
      />
      
      Example mid-stack run (skips the full e2e jobs):
      <img width="1917" height="664" alt="Screenshot 2026-06-26 at 3 24 33 PM"
      src="https://github.com/user-attachments/assets/9ee466da-f3ea-4298-b5b8-2527d197c121"
      />
      
      https://github.com/vercel/next.js/actions/runs/28268549361/job/83760907003?pr=95219
      a26a1d64
    • Aurora Scharff's avatar
      Remove 'silence this warning' from instant validation fix output (#95187) · 41114a31
      Aurora Scharff authored
      ## What
      
      Removes the `silence this warning` phrasing from the structured fix
      lines in instant validation output:
      
      - `- [block] Set \`export const instant = false\` to ~~silence this
      warning and~~ allow a blocking route`
      - `- [ignore] Set \`export const instant = false\` to ~~silence this
      warning and~~ opt the route out of instant-navigation validation`
      - `- [ignore] Set \`export const instant = false\` to ~~silence this
      warning and~~ opt the dropped segment out of instant-navigation
      validation`
      
      ## Why
      
      The line called itself a warning while being logged via `Error:`. This
      PR originally renamed it to `silence this error`, but that has the
      mirror problem: at validation level `warning` or `manual-warning` (or
      when the check only surfaces in dev) nothing blocks, so "error"
      over-claims.
      
      The verb is also wrong either way. Setting `instant = false` doesn't
      silence a problem that still exists. It declares that blocking is
      acceptable for the route, so validation stops treating it as one.
      Removing the clause leaves wording that is correct at every validation
      level and matches the dev overlay cards ("Allow blocking route",
      "Disable validation on this route") and the docs sections the lines link
      to.
      
      ## How
      
      - `blocking-route-messages.ts`, `dynamic-rendering-utils.ts`: drop
      `silence this warning and` from the `[block]` lines
      - `instant-messages.ts`: drop it from the `[ignore]` lines (unrendered
      segment, link prefetch)
      - `errors.json`: regenerated, append-only (codes 1394-1405)
      - Storybook fixture and 15 test files updated to the new strings
      
      <!-- NEXT_JS_LLM_PR -->
      41114a31
    • Dmitrii's avatar
      fix(turbopack): allow `#/` prefixed subpath import specifiers (#94461) · 2aa1e457
      Dmitrii authored
      ## What?
      
      Fixes Turbopack failing to resolve imports using the common `"#/*":
      "./src/*"` pattern in `package.json` `imports` field.
      
      ## Why?
      
      The resolver had an early-rejection check that incorrectly blocked all
      specifiers starting with `#/`:
      
      ```rust
      if specifier == "#" || specifier.starts_with("#/") || specifier.ends_with(/) {
          // emit error, return unresolvable
      }
      ```
      
      Node.js and webpack (enhanced-resolve) both support the widely-used
      TypeScript pattern:
      
      ```json
      "imports": {
        "#/*": "./src/*"
      }
      ```
      
      When a user writes `import x from '#/greeting'`, the specifier
      `#/greeting` starts with `#/`, so Turbopack was erroneously rejecting it
      before attempting the `imports` field lookup. Only bare `#` and
      directory-trailing `/` specifiers should be rejected early —
      `#/something` is perfectly valid and should reach the `imports` field
      resolver.
      
      Since Turbopack is a drop-in webpack replacement in Next.js, it should
      support the same resolution patterns. The `AliasMap` already handles
      wildcard pattern matching correctly once the early rejection is bypassed
      — removing the `starts_with("#/")` guard is sufficient.
      
      ## How?
      
      - Remove `specifier.starts_with("#/")` from the early rejection
      condition in `resolve_package_internal_with_imports_field`
      - Add a test fixture (`subpath-imports-slash`) that validates `#/*`
      wildcard imports resolve correctly
      
      ## Testing
      
      New test case in
      `turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/subpath-imports-slash`:
      
      ```json
      { "imports": { "#/*": "./src/*" } }
      ```
      
      ```js
      import greeting from '#/greeting.js'
      it('should resolve #/* subpath imports', () => {
        expect(greeting).toBe('hello')
      })
      ```
      
      Closes #94290
      2aa1e457
  4. 01 Jul, 2026 4 commits