- 02 Aug, 2025 10 commits
-
-
nextjs-bot authored
-
Luke Sandberg authored
### Improve performance of chunk bootstrapping leveraging arrays and maps Currently we bootstrap the set of the modules in a chunk by passing an object to the runtime, this is suboptimal for a few reasons: * The runtime just wants to iterate the object and copy it into a runtime datastructure and iterating objects is relatively slow * The browser needs to spend time computing the 'shape' of this object and possibly changing internal representations The solution to both these problems is of course, Arrays!. so instead of an object like ``` { [moduleId]: (__turbopack_context__) => {},...} ``` we use an array like this ``` [ moduleId, (__turbopack_context__) => {}] ``` * a non-empty sequence of module ids come first - we may have more than one to support scope hoisted modules * the factory function Because these objects are temporary this should make both constructing and iterating them faster. Finally, in the runtime what we want to do is copy these modules into a global map that is represented as an `Object`. Because we are constantly inserting new keys, this is a suboptimal case and a `Map` should be faster for both insertions and lookups. So this adapts the moduleFactory type to use an es6 `Map` which is more optimized for this particular usecase. Ideally we would do the same for the moduleCache but that would complicate `require.cache` usecases. We could perhaps leverage a `Proxy` to maintain support but this is left as future work. ### Aside: why are arrays faster than objects? Arrays are faster to parse because they incur fewer 'shape transitions' (background reading: https://v8.dev/blog/fast-properties vs https://v8.dev/blog/elements-kinds). Basically for every new property v8 parses on the object literal it changes the hidden type (or 'shape'). For arrays the same thing happens but the process is much simpler as there is a fixed set of possible shapes and the browser will hit the terminal one after evaluating the second element. Also arrays are simply faster to iterate than objects (but this is generally a non-controversial statement). ### Performance Based on the `module-cost` benchmark this is a consistent win in all scenarios | Scenario | Metric | HEAD (ms) | CHANGE (ms) | Delta (ms) | % Change | |----------|--------|-----------|-------------|------------|----------| | **Pages API ESM** | Load Duration | 33.46 | 27.87 | -5.59 | -16.7%✅ | | | Execution Duration | 63.22 | 62.54 | -0.68 | -1.1%✅ | | **Pages API CommonJS** | Load Duration | 44.11 | 33.76 | -10.35 | -23.5%✅ | | | Execution Duration | 32.05 | 25.70 | -6.35 | -19.8%✅ | | **Client ESM** | Load Duration | 34.74 | 27.65 | -7.09 | -20.4%✅ | | | Execution Duration | 46.13 | 40.35 | -5.78 | -12.5%✅ | | **Client CommonJS** | Load Duration | 30.43 | 24.48 | -5.95 | -19.6%✅ | | | Execution Duration | 25.15 | 17.18 | -7.97 | -31.7%✅ | ### Risks The biggest risk of this change is subtle bugs introduced due to `string` vs `number` confusion. I found one subtle issue in how we rewrite `new Worker()` constructors, there could be more not covered by tests. -
Tobias Koppers authored
### What? In development give the module factory a useful name, so it's clear in stack traces that this is the module evaluation part of the execution. This also fixes some bugs with the stack trace parser, which seems to struggle if function names contain brackets. The automatically inferred function name would be the module id, which contains brackets.
-
Sebastian "Sebbie" Silbermann authored
-
Sebastian "Sebbie" Silbermann authored
`eslint-plugin-react-hooks` is also published in React's nightly release cycle. I want to start dog fooding it in Next.js so that we can spot issues as early as possible. It also includes some new heuristics that are important to flag React Compiler incompatibilities. Compat with the React Compiler of the Next.js codebase is especially relevant for Next DevTools which uses the React Compiler. I'll follow-up on these violations. Each need different treatment.
-
Tobias Koppers authored
### What? Write SST while processing blocks to avoid keeping all blocks in memory. Reduces temporary memory used by persisting.
-
Tobias Koppers authored
### What? move block offset map to the end of the file to enable streaming write of the SST file.
-
Josh Story authored
The RSC payload ideally would be constructed during the prerender. However it is not currently sync and RSC doesn't provide a top level way to produce an object child from a function at the root so we generate the component tree before starting the render. However we use the workUnitStore type to govern certain behaviors within the RSC payload generation for instance preparing things like searchParams and params props for layouts and pages. So at the moment we scope the RSC generation inside the same workUnitStore instance that will also scope the prerender. This is fine except there are certain things that apply in the prerender context that do not apply in the component tree generation. Namely we do not want to track Sync IO as need to abort the prerender. This would lead to the entire prerender being aborted before it even begins. There are a few options. We could create a new workUnitStore type. This isn't great b/c we have so many places where we need to exhaustively check this. We could use a new phase to similarly track whether we're before render or not however this has the same problem of all places where phase is considered needing to be aware of this additional possible phase. Instead I think we ought to leave the logic of the code that determines what to do simple and continue to track the sync IO but we just reset the dynamic tracking and abort controllers so that the render starts afresh with these.
-
Benjamin Woodruff authored
Yes, `lazy_regex` makes this code slightly cleaner, and it does have the nice side-effect of compile-time checking the regexes but: - We've got test coverage for all of these regexes. - It adds a proc macro, proc macros are detrimental to build performance. - It doesn't really clean up the code that much versus the new stdlib `LazyLock`. - This is the only crate using it. So I don't think it's worth it.
-
Ben Gubler authored
## Overview Generates `.next/types/routes.d.ts` file that provides typed route definitions and global `PageProps`/`LayoutProps` types for App Router components, eliminating the need for manual imports and providing full type safety for routing. ## Generated Type Structure ```typescript // Route union types type AppRoutes = "/" | "/blog/[slug]" | "/dashboard/[...path]" type LayoutRoutes = "/" | "/dashboard" type PageRoutes = never // for pages directory type RedirectRoutes = "/old-path" type RewriteRoutes = "/api/proxy/[...path]" // Parameter mapping with full dynamic route support type ParamMap = { "/": {} "/blog/[slug]": { "slug": string } "/dashboard/[[...path]]": { "path"?: string[] } // optional catch-all "/api/[...segments]": { "segments": string[] } // required catch-all } // Parallel route slots for layouts type LayoutSlotMap = { "/dashboard": "analytics" | "team" "/": never } ``` ## Usage Examples ```typescript // Page component - no imports needed, full parameter typing export default function BlogPost(props: PageProps<'/blog/[slug]'>) { const { slug } = await props.params // slug is typed as string const searchParams = await props.searchParams // Record<string, string | string[] | undefined> return <div>Post: {slug}</div> } // Layout with parallel routes - automatic slot typing export default function DashboardLayout(props: LayoutProps<'/dashboard'>) { return ( <div> {props.children} {props.analytics} {/* Typed parallel route slot */} {props.team} {/* Typed parallel route slot */} </div> ) } // Catch-all routes with array parameters export default function DocsPage(props: PageProps<'/docs/[...path]'>) { const { path } = await props.params // path is typed as string[] return <div>Docs path: {path.join('/')}</div> } ``` ## Key Features - **Zero imports**: All types are globally available via declaration merging - **Route validation**: TypeScript ensures only valid routes can be used - **Dynamic route support**: Full typing for `[param]`, `[...param]`, and `[[...param]]` patterns - **Parameter extraction**: Automatic typing of route parameters based on file structure - **Parallel routes**: Automatic slot typing for layouts with `@slot` directories - **Custom routes**: Support for `redirects` and `rewrites` from `next.config.js` - **IDE integration**: Full auto-completion for route paths and parameters ## Route Discovery The system automatically discovers routes from: - **App Router**: `app/` directory structure with `page.tsx` and `layout.tsx` files - **Pages Router**: `pages/` directory structure (legacy support) - **Redirects**: Custom redirects defined in `next.config.js` - **Rewrites**: Custom rewrites defined in `next.config.js` - **Parallel Routes**: `@slot` directories for layout composition
-
- 01 Aug, 2025 20 commits
-
-
nextjs-bot authored
-
Vercel Release Bot authored
This auto-generated PR updates the production integration test manifest used when testing Rspack.
-
Vercel Release Bot authored
This auto-generated PR updates the development integration test manifest used when testing Rspack.
-
Wyatt Johnson authored
### What? This PR improves error debugging during prerendering by adding route context to hanging promise rejection errors and related error messages. ### Why? When developers encounter dynamic access issues during static generation, the current error messages don't provide enough context about which specific route is causing the problem. This makes debugging difficult, especially in large applications with many routes. By including route information in error messages, developers can quickly identify the problematic route and resolve the issue more efficiently. ### How? - Updates `makeHangingPromise` function signature to accept a `route` parameter - Modifies `HangingPromiseRejectionError` to include route information in error messages - Adds route context to all hanging promise calls across the codebase: - Dynamic rendering utilities - Fetch patching - Request APIs (cookies, headers, params, etc.) - Use cache wrapper - Adds new error code 773 for missing workStore scenarios - Ensures workStore validation where needed to prevent missing route context The changes are backward compatible and only enhance existing error messages with additional debugging information. ### Fixing a bug - Tests will be added in follow-up PR - Error messages now include helpful route context for debugging NAR-225
-
Štěpán Granát authored
Adding Tolgee to available i18n providers. ## Why Tolgee is listed only in the pages-router, but it actually supports app-router as well.
-
Wyatt Johnson authored
### What? Add support for generating prefetch segment data routes for pages with fallback root parameters. ### Why? When routes have fallback root parameters but no segment paths, the prefetch system wasn't generating the necessary rewrite rules. This caused client-side navigation to fail for these routes because the `/_tree` requests couldn't be properly rewritten to the prefetch RSC route. ### How? - Add `hasFallbackRootParams` flag and `prefetchSegmentDataRoutes` to `ManifestRoute` type - Generate inverse prefetch segment data routes for `/_tree` path when routes have fallback root params - Set flag to simplify route regex matching for these routes Related Pull Request: https://github.com/vercel/vercel/pull/13653
-
Luke Sandberg authored
## Improve performance of find_client_references in production builds ### What? Avoid calling `find_server_entries` in the production case where there is a single module graph. While all the turbotasks launched by `find_server_entries` are by definition already done it is still a lot of tiny tasks to get cache hits and re do work that was already done when building the graph. So instead we can just report server components and server utilities when performing the graph traversal. Unfortunately this does not work in development builds since the stacked layout graphs interfere with ordering, so in that case we will still call `find_server_entries`, however we can do this concurrently with the graph traversal to save a bit of latency. ### Why? To improve performance of course!  This represents a small latency progression. Collecting client references is on the critical path for chunking so this makes sense. We have to collect all client references for all pages
-
Luke Sandberg authored
A recent output change in #82214 invalidated a new test added in #77616 A classic write-write race
-
Luke Sandberg authored
## Optimize ESM Exports ### What For an esm module like ```js export const foo = 2; ``` turbopack will generate a factory function like ```js __turbopack_context__ => { __turbopack_context__.s({foo: ()=>foo}); const foo = 2; } ``` * we expose the exports early to enable circular imports between modules * we expose as 'getter functions' to enable live bindings These behaviors are necessary to uphold the ESM specification, however, we can optimize it by avoiding objects. ```js __turbopack_context__ => { __turbopack_context__.s(['foo', ()=>foo]); const foo = 2; } ``` Since the runtime simply walks the object literal in order to call `defineProperty` a number of times switching to an array representation will speed up both construction and iteration. In a later step i will pursue an approach to avoid generating the getter functions. ### Performance analysis courtesy of v0 I ran the `module-cost` benchmark 30 times across this branch and canary. Each measurement was in a fresh incognito window. | Scenario | Metric | HEAD (ms) | HEAD σ | HEAD CV | CHANGE (ms) | CHANGE σ | CHANGE CV | Delta (ms) | % Change | |----------|--------|-----------|---------|---------|-------------|----------|-----------|------------|----------| | **Pages API ESM** | Load Duration | 39.84 | 2.8 | 7.0% | 36.61 | 2.7 | 7.4% | -3.23 | -8.1%✅ | | | Execution Duration | 60.89 | 3.6 | 5.9% | 58.14 | 2.8 | 4.8% | -2.75 | -4.5%✅ | | **Client ESM** | Load Duration | 46.09 | 2.4 | 5.2% | 46.31 | 3.2 | 6.9% | +0.22 | +0.5%❌ | | | Execution Duration | 47.77 | 0.8 | 1.7% | 46.07 | 1.0 | 2.2% | -1.70 | -3.6%✅ | ### Key Findings **Strong improvements in Pages API ESM performance:** - Load time reduced by 8.1% with consistent variance - Execution time improved by 4.5% with reduced variance **Mixed results for Client ESM:** - Load times remain essentially unchanged (+0.5%) - Execution times show solid improvement (-3.6%) - Measurements remain highly consistent across both versions -
Niklas Mischkulnig authored
This came up during NFT where the ignore pattern `'**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js'` wasn't applied. -
Janka Uryga authored
the "wait for 500ms" thing was a leftover of me inspecting the test apps visually, we don't need it anymore and it slows the tests down unnecessarily
-
Tobias Koppers authored
### What? Improve the generation of the compression dictionary.
-
KimJunYoung authored
<img width="591" height="132" alt="image" src="https://github.com/user-attachments/assets/9c9c64fe-4095-4127-a893-1c12426d9700" /> - When I first read the explanation, it felt as if `redirect` couldn’t be used in client components. - Also, when clicking the `Server Components` link, it leads to the `Server and Client Components` page. - To indicate that `redirect` can be used in both `server and client components`, rename the hyperlink text in the `redirect.mdx` file. --------- Co-authored-by:
Joseph <joseph.chamochumbi@vercel.com>
-
Tobias Koppers authored
### What? Change the compaction behavior for "short sessions" (like next build). A longer "short session" might commit to the DB multiple times (every 60s currently), which previously resulted in compactions happening after multiple commits to the database. As compactions are expensive and memory hungry, we want to avoid them until the end of the session. At the end of the session we can run it in parallel to node.js SSG.
-
nextjs-bot authored
-
Tobias Koppers authored
### What? We try to limit the maximum number of merge jobs with the `max_merge_segment_count` option. But as we run `get_merge_segments` for every key family it only limits the merge jobs per family. This results in much more merge jobs then configured. This change applied the limits across families. Lower number families will be compacted first, which is a new behavior, so maybe we want to reorder the key families to improve the order (see enum KeySpace)
-
Jarred Sumner authored
Fixes https://github.com/vercel/next.js/issues/75220 This marks Bun's builtin modules as external, following the same pattern as for Node. - `"bun:ffi"` - `"bun:jsc"` - `"bun:sqlite"` - `"bun:test"` - `"bun:wrap"` - `"bun"` I have not manually tested this change yet, nor attempted to write tests for this. I did check for other places in the code that should be updated and _maybe_ `externals/crates/next-custom-transforms/src/transforms/warn_for_edge_runtime.rs` should as well, but I'll leave that up to you whether or not that makes sense. Opening as a draft until this can be at least manually tested. By the way, node's `sqlite` module is missing from `NODE_EXTERNALS`. That seemed out of scope but worth mentioning. Current error message:  --------- Co-authored-by:
Alistair Smith <hi@alistair.sh>
-
Tobias Koppers authored
### What? No need to manually manage a free list, since mimalloc is able to handle this now
-
Tobias Koppers authored
### What? * Upgrade to mimalloc 3 * Compute allocations size more accurately (for tracing)
-
Luke Sandberg authored
Replace construction of `RcStr` instances on constant strings with the `rcstr!` macro which can shift construction costs to compile time and eliminate reference counting. Performance impacts from all the dropped ref counts are minor but do exist  There is also a small progression in max heap which makes sense, laying out the static rcstrs should be a somewhat easier job compared to mimalloc.
-
- 31 Jul, 2025 10 commits
-
-
nextjs-bot authored
-
Andrew Clark authored
This is part of a larger effort to remove dynamic params from server responses except in cases where they are needed to render a Server Component. If a param is not rendered by a Server Component, then it can be omitted from the cache key, and cached responses can be reused across pages with different param values. In this step, I've implemented client parsing of the params from the response headers. The basic approach is to split the URL into parts, then traverse the route tree to pick off the param values, taking care to skip over things like interception routes. Notably, this is not how the server parses param values. The server gets the params from the regex that's also used for routing. Originally, I thought I'd send the regex to the client and use it there, too. However, this ended up being needlessly complicated, because the server regexes are also used for things like interception route matching. But this is already encapsulated by the structure of the route tree. So it's easier to just walk the tree and pick off the params. My main hesitation is that this introduces some risk of drift between the server and client params parsing; we'll need to keep them in sync. However, I think the solution is actually to update the server to also pick the params off the URL, rather than use the ones passed from the base router. It's conceptually cleaner, since it's less likely that extra concerns from the base server leaking into the application layer. As an example, compare the code needed to get a catchall param value in the [client](https://github.com/acdlite/next.js/blob/09b16a816ff4d595b5111cb1a6de540838caf97e/packages/next/src/client/client-params.ts#L57-L61) versus the [server](https://github.com/acdlite/next.js/blob/09b16a816ff4d595b5111cb1a6de540838caf97e/packages/next/src/shared/lib/router/utils/get-dynamic-param.ts#L37-L84) implementation. Note: Although the ultimate goal is to remove the dynamic params from the response body (e.g. FlightRouterState), I have not done so yet this PR. The rest of the work will be split up into multiple subsequent PRs.
-
Janka Uryga authored
Initial implementation of runtime prefetching. A "runtime prefetch" is a more complete version of a static prefetch (i.e. the one that a link does by default), rendered on demand, and not cached server-side. It will render the server part of the page dynamically, allowing the usage of - `params` and `searchParams` - `cookies()` - `"use cache: private"` (these are omitted from static prerenders) - `"use cache"` with a short expire time (these are omitted from static prerenders) The result may be partial (in the PPR sense). It will exclude any parts of the page that depend on - uncached IO - `connection()`, `headers()` This allows the client router to cache the result, because it has a well-defined stale time. Note that public caches with a stale time below a certain fixed treshold will also be excluded, because it wouldn't make sense to keep them around in the router cache if we need to throw them away soon after getting them. With this PR, `<Link prefetch={true}>` changes meaning if `clientSegmentCache` + `cacheComponents` are enabled. It will now initiate a runtime prefetch instead of a "full" prefetch, which included everything that a navigation request would. Full prefetches can be done via `<Link prefetch="unstable_forceStale">`. If only one of the two flags is on, the behavior of `<Link prefetch={true}>` is unchanged from how it currently works. I've split the changes up into separate commits for ease of review: 1. Introducing the new workUnitStore type 2. Server - handling the prefetch header and rendering 3. Client - Link and segment cache changes ### Implementation notes The client router sends `next-router-prefetch: 2` to signal that it wants a runtime prefetch (as opposed to the old `next-router-prefetch: 1`, which is used for static prefetches). > NOTE: this builder change is required for this to work on vercel https://github.com/vercel/vercel/pull/13547. It was released in `vercel@44.6.5` Somewhat confusingly, in order to to avoid existing static prefetch codepaths, we need the server to _not_ treat this as "a prefetch request". Instead, we want to mostly treat this like we would a navigation request, and render dynamically. This means that: - `isPrefetchRequest` (from `parseRequestHeaders` in `app-render`) will be `false` - `getRequestMeta(req, 'isPrefetchRSCRequest')` won't be set This is a bit ugly but it works for now. I'll try to clean it up in the future. We render a payload of the same shape as a navigation request (including omitting shared layouts, as instructed by the `Next-Router-State-Tree` header). But unlike a navigation request, we do a cache-components-style prerender at runtime in order to exclude uncached/sync IO. This prerender uses a new workUnitStore type, `'prerender-runtime'`. This store type changes the behavior of `cookies()`, `params`, `searchParams`, `"use cache: private"`, `next/root-params`, and others. Unlike a static prerender, if we detect a bad uncached/sync IO usage, we just log an error (instead of throwing it and erroring) and respond with whatever we managed to render up until the render was aborted, in hopes that we can still return something useful to the client. This request is happening at runtime, so we should try to handle errors gracefully. We track whether or not the prerender has any dynamic holes, and if it does, set `x-nextjs-postponed: 1` on the response. This tells the client router if we still need to fetch more data when navigating, or if we can skip it because we already have a complete page. Ideally, we'd track this information per-segment for better reuse on the client side, but that's not in scope for this PR. We also set the `x-nextjs-staletime` header on the response to tell the client router how long it should keep this prefetch in the cache. Note that this does not affect `Cache-Control`, which should still be the same as a dynamic navigation request to prevent it from being cached by anything other than the client router. This may be improved in the future if it turns out we can safely set an appropriate `Cache-Control: private, ...` that also accounts for e.g. changing cookie values, but i'm erring on the side of caution for now. -
nextjs-bot authored
-
Joshua Hannaford authored
## Fix module reference handling in app_structure.rs creating duplicated layouts ### What? Fixed a bug in the `check_and_update_module_references` function by making the code always overrides the `not-found`, `unauthorized`, etc files at the top level group route layer. ### Why? The previous implementation had a bug that when a directory was setup like the added test case where the layouts from a lower directory would render when only the layouts at the level of the not-found page should have rendered. ### How? - Added the ability to force overriding of the `module` when running `check_and_update_module_references` - Split the logic between global and layer-specific modules Fixes #PACK-5081
-
Niklas Mischkulnig authored
<!-- 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 ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### 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 # -->
-
Dario Lehmhus authored
Co-authored-by:Dario Lehmhus <dario.lehmhus@ffw.com>
-
nextjs-bot authored
-
Vercel Release Bot authored
This auto-generated PR updates the development integration test manifest used when testing Rspack. Co-authored-by:nextjs-bot <it+nextjs-bot@vercel.com>
-
Tobias Koppers authored
### What? This ensures next.js correctly waits for the turbopack shutdown to complete
-