- 04 Aug, 2025 12 commits
-
-
nextjs-bot authored
-
Luke Sandberg authored
# Add automated benchmark runner for module-cost ## What? This PR adds an automated benchmark runner for the module-cost benchmark, allowing for consistent measurement of module loading and execution times. ## Why? It is to tedious and error prone to run the benchmark. ## Usage Build `next` and turbopack however you like ``` pnpm i pnpm prepare-bench pnpm build-webpack (or build-turbopack) pnpm benchmark ``` ## How? v0 mostly
-
Benjamin Woodruff authored
I noticed we had two copies of this library. There are a few minor API changes (some things that were properties are now methods, "message" is now "kind"), and I switched our error type over to use `RcStr` since it implements `Clone`.
-
Joseph authored
Fixes: https://github.com/vercel/next.js/issues/81776
-
nextjs-bot authored
-
devin-ai-integration[bot] authored
# Improve Content Security Policy Documentation This PR comprehensively improves the Next.js Content Security Policy (CSP) documentation to address community feedback from Reddit and GitHub discussions about gaps in the current documentation. ## Changes Made ### 1. Enhanced Nonce Flow Explanation - Added detailed section explaining how Next.js automatically detects and applies nonces during server-side rendering - Clarified the 3-step process: middleware generation → Next.js extraction → automatic application - Explained that developers don't need to manually add nonces to every script tag ### 2. Static vs Dynamic Rendering Documentation - Added comprehensive section explaining performance implications of using nonces - Documented that nonces force all pages into dynamic rendering - Explained trade-offs: slower page loads, increased server load, no CDN caching - Added guidance on when to use nonces vs alternatives ### 3. Experimental SRI (Subresource Integrity) Documentation - Documented the experimental `sri.algorithm` configuration option - Explained hash-based CSP as an alternative to nonces that preserves static generation - Included configuration examples and benefits/limitations - Noted that SRI is webpack-only, App Router only, and experimental ### 4. Development vs Production Considerations - Added section addressing environment-specific CSP requirements - Documented need for `'unsafe-eval'` in development for HMR - Provided conditional CSP examples based on NODE_ENV ### 5. Comprehensive Troubleshooting Section - Added solutions for error pages that don't work with strict CSP - Documented third-party script integration with CSP - Included common CSP violation fixes - Added examples for both App Router and Pages Router ### 6. Practical Examples - Static site with hash-based CSP using SRI - Dynamic site with nonce-based CSP - Mixed approach for different page types - Environment-aware CSP configuration ### 7. Enhanced Pages Router Documentation - Added `_document.tsx` nonce access example - Improved `getServerSideProps` examples - Added third-party script integration examples ## Community Feedback Addressed This PR directly addresses the Reddit thread feedback about: -
❌ "it is not clear that the nonce is then picked up by the rest of the pages" →✅ Added detailed nonce flow explanation -❌ "it is not clear that the pages therefore are not statically generated anymore" →✅ Added static vs dynamic rendering section -❌ "The solution of being able to provide the sha256 hashes... is not supported, and it is not mentioned in the documentation" →✅ Added experimental SRI documentation -❌ Poor documentation of strict CSP implementation →✅ Added comprehensive examples and troubleshooting ## Technical Details - **File Modified**: `docs/01-app/02-guides/content-security-policy.mdx` - **Lines Added**: 642 insertions - **Maintains**: Existing documentation structure and Next.js conventions - **Supports**: Both App Router and Pages Router with appropriate switcher components ## Testing - Verified all code examples use correct Next.js APIs and patterns - Ensured documentation follows existing Next.js docs structure - Confirmed all referenced configuration options exist in the codebase - Validated that experimental features are properly marked as such --- **Link to Devin run**: https://app.devin.ai/sessions/e7e5fa95dc0146b3ab79aac72c53ed13 **Requested by**: lee@vercel.com --------- Co-authored-by:Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by:
lee@vercel.com <lee@vercel.com> Co-authored-by:
Joseph Chamochumbi <joseph.chamochumbi@vercel.com>
-
Andrew Clark authored
When performing a segment prefetch, we send a "segment path" to the server, which represents the particular segment that we're requesting. Originally, I thought these needed to fully encode all the param values, but since we already request the segments within the context of a particular target page, it's unnecessary — the base URL already contains all the param information (and is indeed the source of truth for where the param values come from). The only thing we need to put in the paths are the param names. On the client, though, these segments are cached across pages (that's the whole point of the Segment Cache). So in the prefetch cache, we do need to cache them by their concrete param values. Splitting out the param names and the param values into separate keys will allow us to implement "fallback PPR" behavior for the client, where if a segment entry does not reference a particular param, it can be reused for all possible values of that param. (We already do this for search strings.) For now, I've split the current "segment path" key into two separate keys, which I'm calling the "cache key" and the "request key". It's a bit confusing since we have so many different types of cache keys, but I think it's OK for now — this will be refactored soon anyway to support the fallback PPR behavior. Despite the line count, most of this PR is just a mechanical refactor. Most of it was done by tab completion in Cursor. The substance of the change is in the `segment-value-encoding.ts` file.
-
PuppyOne authored
## What? Added a new "React Developer Tools" section to the debugging documentation. ## Why? This PR resolves #82308 which highlighted that React DevTools - a fundamental debugging tool for React applications - was missing from Next.js debugging documentation. Since the Next.js framework is built on React, React DevTools is crucial for: - Inspecting component hierarchies - Debugging state and props - Identifying performance issues - Understanding application structure ## How? Inserted a concise section between "Client-side code" and "Server-side code" in [docs/01-app/02-guides/debugging.mdx](https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/debugging.mdx): - Introduces developers to the essential React debugging tool and its key features - Direct users to the corresponding React documentation ### Checklist: Improving Documentation - [x] Ran `pnpm prettier-fix` to ensure proper formatting - [x] Followed the Docs Contribution Guide: https://nextjs.org/docs/community/contribution-guide Closes #82308 Co-authored-by:
Joseph <joseph.chamochumbi@vercel.com>
-
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 # -->
-
Janka Uryga authored
When implementing the check that disallows using `next/root-params` in server actions, i forgot that when a page is rerendered after an action, the render is still wrapped with an `actionAsyncStorage` with `actionStore.isAction === true`. The fix is to also check that we're in the `'action'` phase, i.e. we haven't switched to rendering yet. Closes #82302
-
Sebastian "Sebbie" Silbermann authored
-
Niklas Mischkulnig authored
Part of PACK-4164 ~~Set `NODE_ENV` in tracing context~~ For that, see https://github.com/vercel/next.js/pull/75254#issuecomment-2627686346 Set `TURBOPACK` in tracing context This get rids of some constant build overhead (because we only analyze one instance of react-dom for NFT now, instead of all of the edge/server/client onces). Otherwise no measureable perf/memory impact
-
- 03 Aug, 2025 2 commits
-
-
nextjs-bot authored
-
Vercel Release Bot authored
This auto-generated PR updates font data with latest available Co-authored-by:nextjs-bot <it+nextjs-bot@vercel.com>
-
- 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 16 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)
-