Unverified Commit 7a801959 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update routes generation for build-complete (#85017)

## Summary

- Adds comprehensive route generation and normalization for
build-complete adapter hooks
- Enhances adapter output types with additional metadata fields
(`sourcePage`, `wasmAssets`, `pprChain`, `parentFallbackMode`)
- Improves middleware matcher handling and revalidation bypass logic
- Adds proper tracing for shared node dependencies across pages and app
router modules
- Includes `buildId` in adapter context for build identification

## Changes

### Route Generation
- Generates complete route manifests with processed regex patterns for
headers, redirects, rewrites, and dynamic routes
- Converts routes using `@vercel/routing-utils` for consistent
formatting
- Handles RSC routes (`.rsc` suffix) for app router pages
- Supports i18n locale-specific routes and data routes
(`/_next/data/[buildId]/...`)
- Properly handles static pages with mixed app/pages router setups

### Adapter Output Enhancements
- Added `sourcePage` field to all route outputs for tracking original
source files
- Added `wasmAssets` support for bundled WebAssembly files
- Added `pprChain` and `parentFallbackMode` to prerender outputs for PPR
support
- Enhanced middleware matchers to include processed source and regex
patterns
- Improved traced assets handling with separate tracking for pages vs
app router modules

### Middleware & Revalidation
- Standardized middleware matcher format with `source`, `sourceRegex`,
`has`, and `missing` fields
- Automatically adds `x-prerender-revalidate` header bypass to
middleware matchers
- Fixed middleware pathname to always be `/_middleware` for consistency

### Asset Tracing
- Traces shared node dependencies for bootstrapping (node-environment,
require-hook, etc.)
- Separate tracing for pages router and app router module contexts
- Improved trace ignores for unnecessary files (dev builds, webpack
internals, etc.)
- Better handling of instrumentation hook assets

### Bug Fixes
- Fixed RSC fallback handling for mixed app/pages router builds
- Improved 404/500 static page detection with locale support
- Better basePath normalization with trailing slash handling
- Fixed data route generation for getServerSideProps pages with i18n
parent 6c105133
...@@ -128,12 +128,17 @@ Called after the build process completes with detailed information about routes ...@@ -128,12 +128,17 @@ Called after the build process completes with detailed information about routes
**Parameters:** **Parameters:**
- `routes`: Object containing route manifests for headers, redirects, rewrites, and dynamic routes - `routes`: Object containing route manifests for headers, redirects, rewrites, and dynamic routes
- `routes.headers`: Array of header route objects with `source`, `sourceRegex`, `headers`, `has`, `missing`, and optional `priority` fields
- `routes.redirects`: Array of redirect route objects with `source`, `sourceRegex`, `destination`, `statusCode`, `has`, `missing`, and optional `priority` fields
- `routes.rewrites`: Object with `beforeFiles`, `afterFiles`, and `fallback` arrays, each containing rewrite route objects with `source`, `sourceRegex`, `destination`, `has`, and `missing` fields
- `routes.dynamicRoutes`: Array of dynamic route objects with `source`, `sourceRegex`, `destination`, `has`, and `missing` fields
- `outputs`: Detailed information about all build outputs organized by type - `outputs`: Detailed information about all build outputs organized by type
- `projectDir`: Absolute path to the Next.js project directory - `projectDir`: Absolute path to the Next.js project directory
- `repoRoot`: Absolute path to the detected repository root - `repoRoot`: Absolute path to the detected repository root
- `distDir`: Absolute path to the build output directory - `distDir`: Absolute path to the build output directory
- `config`: The final Next.js configuration (with `modifyConfig` applied) - `config`: The final Next.js configuration (with `modifyConfig` applied)
- `nextVersion`: Version of Next.js being used - `nextVersion`: Version of Next.js being used
- `buildId`: Unique identifier for the current build
## Output Types ## Output Types
...@@ -149,11 +154,14 @@ React pages from the `pages/` directory: ...@@ -149,11 +154,14 @@ React pages from the `pages/` directory:
id: string // Route identifier id: string // Route identifier
filePath: string // Path to the built file filePath: string // Path to the built file
pathname: string // URL pathname pathname: string // URL pathname
sourcePage: string // Original source file path in pages/ directory
runtime: 'nodejs' | 'edge' runtime: 'nodejs' | 'edge'
assets: Record<string, string> // Traced dependencies assets: Record<string, string> // Traced dependencies (key: relative path from repo root, value: absolute path)
wasmAssets?: Record<string, string> // Bundled wasm files (key: name, value: absolute path)
config: { config: {
maxDuration?: number maxDuration?: number
preferredRegion?: string | string[] preferredRegion?: string | string[]
env?: Record<string, string> // Environment variables (edge runtime only)
} }
} }
``` ```
...@@ -168,11 +176,14 @@ API routes from `pages/api/`: ...@@ -168,11 +176,14 @@ API routes from `pages/api/`:
id: string id: string
filePath: string filePath: string
pathname: string pathname: string
sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' runtime: 'nodejs' | 'edge'
assets: Record<string, string> assets: Record<string, string>
wasmAssets?: Record<string, string>
config: { config: {
maxDuration?: number maxDuration?: number
preferredRegion?: string | string[] preferredRegion?: string | string[]
env?: Record<string, string>
} }
} }
``` ```
...@@ -186,12 +197,15 @@ React pages from the `app/` directory with `page.{js,ts,jsx,tsx}`: ...@@ -186,12 +197,15 @@ React pages from the `app/` directory with `page.{js,ts,jsx,tsx}`:
type: 'APP_PAGE' type: 'APP_PAGE'
id: string id: string
filePath: string filePath: string
pathname: string pathname: string // Includes .rsc suffix for RSC routes
sourcePage: string // Original relative source file path
runtime: 'nodejs' | 'edge' runtime: 'nodejs' | 'edge'
assets: Record<string, string> assets: Record<string, string>
wasmAssets?: Record<string, string>
config: { config: {
maxDuration?: number maxDuration?: number
preferredRegion?: string | string[] preferredRegion?: string | string[]
env?: Record<string, string>
} }
} }
``` ```
...@@ -203,7 +217,18 @@ API and metadata routes from `app/` with `route.{js,ts,jsx,tsx}`: ...@@ -203,7 +217,18 @@ API and metadata routes from `app/` with `route.{js,ts,jsx,tsx}`:
```typescript ```typescript
{ {
type: 'APP_ROUTE' type: 'APP_ROUTE'
// ... same structure as APP_PAGE id: string
filePath: string
pathname: string
sourcePage: string
runtime: 'nodejs' | 'edge'
assets: Record<string, string>
wasmAssets?: Record<string, string>
config: {
maxDuration?: number
preferredRegion?: string | string[]
env?: Record<string, string>
}
} }
``` ```
...@@ -217,7 +242,11 @@ ISR-enabled routes and static prerenders: ...@@ -217,7 +242,11 @@ ISR-enabled routes and static prerenders:
id: string id: string
pathname: string pathname: string
parentOutputId: string // ID of the source page/route parentOutputId: string // ID of the source page/route
groupId: number // Revalidation group identifier groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together)
pprChain?: {
headers: Record<string, string> // PPR chain headers (e.g., 'x-nextjs-resume': '1')
}
parentFallbackMode?: 'blocking' | false | null // Fallback mode from getStaticPaths
fallback?: { fallback?: {
filePath: string filePath: string
initialStatus?: number initialStatus?: number
...@@ -258,17 +287,72 @@ Middleware function (if present): ...@@ -258,17 +287,72 @@ Middleware function (if present):
type: 'MIDDLEWARE' type: 'MIDDLEWARE'
id: string id: string
filePath: string filePath: string
pathname: string pathname: string // Always '/_middleware'
sourcePage: string // Always 'middleware'
runtime: 'nodejs' | 'edge' runtime: 'nodejs' | 'edge'
assets: Record<string, string> assets: Record<string, string>
wasmAssets?: Record<string, string>
config: { config: {
maxDuration?: number maxDuration?: number
preferredRegion?: string | string[] preferredRegion?: string | string[]
matchers?: ProxyMatcher[] env?: Record<string, string>
matchers?: Array<{
source: string
sourceRegex: string
has: RouteHas[] | undefined
missing: RouteHas[] | undefined
}>
} }
} }
``` ```
## Routes Information
The `routes` object in `onBuildComplete` provides complete routing information with processed patterns ready for deployment:
### Headers
Each header route includes:
- `source`: Original route pattern (e.g., `/about`)
- `sourceRegex`: Compiled regex for matching requests
- `headers`: Key-value pairs of headers to apply
- `has`: Optional conditions that must be met
- `missing`: Optional conditions that must not be met
- `priority`: Optional flag for internal routes
### Redirects
Each redirect route includes:
- `source`: Original route pattern
- `sourceRegex`: Compiled regex for matching
- `destination`: Target URL (can include captured groups)
- `statusCode`: HTTP status code (301, 302, 307, 308)
- `has`: Optional positive conditions
- `missing`: Optional negative conditions
- `priority`: Optional flag for internal routes
### Rewrites
Rewrites are categorized into three phases:
- `beforeFiles`: Checked before filesystem (including pages and public files)
- `afterFiles`: Checked after pages/public files but before dynamic routes
- `fallback`: Checked after all other routes
Each rewrite includes `source`, `sourceRegex`, `destination`, `has`, and `missing`.
### Dynamic Routes
Generated from dynamic route segments (e.g., `[slug]`, `[...path]`). Each includes:
- `source`: Route pattern
- `sourceRegex`: Compiled regex with named capture groups
- `destination`: Internal destination with parameter substitution
- `has`: Optional positive conditions
- `missing`: Optional negative conditions
## Use Cases ## Use Cases
Common use cases for adapters include: Common use cases for adapters include:
...@@ -278,3 +362,4 @@ Common use cases for adapters include: ...@@ -278,3 +362,4 @@ Common use cases for adapters include:
- **Monitoring Integration**: Collect build metrics and route information - **Monitoring Integration**: Collect build metrics and route information
- **Custom Bundling**: Package outputs in platform-specific formats - **Custom Bundling**: Package outputs in platform-specific formats
- **Build Validation**: Ensure outputs meet specific requirements - **Build Validation**: Ensure outputs meet specific requirements
- **Route Generation**: Use processed route information to generate platform-specific routing configs
...@@ -218,6 +218,7 @@ ...@@ -218,6 +218,7 @@
"@types/ws": "8.2.0", "@types/ws": "8.2.0",
"@vercel/ncc": "0.34.0", "@vercel/ncc": "0.34.0",
"@vercel/nft": "0.27.1", "@vercel/nft": "0.27.1",
"@vercel/routing-utils": "5.2.0",
"@vercel/turbopack-ecmascript-runtime": "*", "@vercel/turbopack-ecmascript-runtime": "*",
"acorn": "8.14.0", "acorn": "8.14.0",
"anser": "1.4.9", "anser": "1.4.9",
......
...@@ -23,6 +23,22 @@ import type { RoutesUsingEdgeRuntime } from './utils' ...@@ -23,6 +23,22 @@ import type { RoutesUsingEdgeRuntime } from './utils'
const debug = debugOriginal('next:build:build-traces') const debug = debugOriginal('next:build:build-traces')
export const makeIgnoreFn = (root: string, ignores: string[]) => {
// pre compile the ignore globs
const isMatch = picomatch(ignores, {
contains: true,
dot: true,
})
return (pathname: string) => {
if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {
return true
}
return isMatch(pathname)
}
}
function shouldIgnore( function shouldIgnore(
file: string, file: string,
serverIgnoreFn: (file: string) => boolean, serverIgnoreFn: (file: string) => boolean,
...@@ -199,22 +215,6 @@ export async function collectBuildTraces({ ...@@ -199,22 +215,6 @@ export async function collectBuildTraces({
} }
} }
const makeIgnoreFn = (ignores: string[]) => {
// pre compile the ignore globs
const isMatch = picomatch(ignores, {
contains: true,
dot: true,
})
return (pathname: string) => {
if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {
return true
}
return isMatch(pathname)
}
}
const sharedIgnores = [ const sharedIgnores = [
'**/next/dist/compiled/next-server/**/*.dev.js', '**/next/dist/compiled/next-server/**/*.dev.js',
...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']), ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']),
...@@ -235,7 +235,7 @@ export async function collectBuildTraces({ ...@@ -235,7 +235,7 @@ export async function collectBuildTraces({
...additionalIgnores, ...additionalIgnores,
] ]
const sharedIgnoresFn = makeIgnoreFn(sharedIgnores) const sharedIgnoresFn = makeIgnoreFn(root, sharedIgnores)
const serverIgnores = [ const serverIgnores = [
...sharedIgnores, ...sharedIgnores,
...@@ -247,7 +247,7 @@ export async function collectBuildTraces({ ...@@ -247,7 +247,7 @@ export async function collectBuildTraces({
? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*'] ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']
: []), : []),
].filter(nonNullable) ].filter(nonNullable)
const serverIgnoreFn = makeIgnoreFn(serverIgnores) const serverIgnoreFn = makeIgnoreFn(root, serverIgnores)
const minimalServerIgnores = [ const minimalServerIgnores = [
...serverIgnores, ...serverIgnores,
...@@ -255,7 +255,7 @@ export async function collectBuildTraces({ ...@@ -255,7 +255,7 @@ export async function collectBuildTraces({
'**/next/dist/server/web/sandbox/**/*', '**/next/dist/server/web/sandbox/**/*',
'**/next/dist/server/post-process.js', '**/next/dist/server/post-process.js',
] ]
const minimalServerIgnoreFn = makeIgnoreFn(minimalServerIgnores) const minimalServerIgnoreFn = makeIgnoreFn(root, minimalServerIgnores)
const routesIgnores = [ const routesIgnores = [
...sharedIgnores, ...sharedIgnores,
...@@ -266,7 +266,7 @@ export async function collectBuildTraces({ ...@@ -266,7 +266,7 @@ export async function collectBuildTraces({
'**/next/dist/server/post-process.js', '**/next/dist/server/post-process.js',
].filter(nonNullable) ].filter(nonNullable)
const routeIgnoreFn = makeIgnoreFn(routesIgnores) const routeIgnoreFn = makeIgnoreFn(root, routesIgnores)
const serverTracedFiles = new Set<string>() const serverTracedFiles = new Set<string>()
const minimalServerTracedFiles = new Set<string>() const minimalServerTracedFiles = new Set<string>()
......
...@@ -147,6 +147,8 @@ export function getDefineEnv({ ...@@ -147,6 +147,8 @@ export function getDefineEnv({
: process.env.NEXT_RSPACK : process.env.NEXT_RSPACK
? 'Rspack' ? 'Rspack'
: 'Webpack', : 'Webpack',
// minimal mode is enforced when an adapter is configured
'process.env.MINIMAL_MODE': Boolean(config.experimental.adapterPath),
// TODO: enforce `NODE_ENV` on `process.env`, and add a test: // TODO: enforce `NODE_ENV` on `process.env`, and add a test:
'process.env.NODE_ENV': 'process.env.NODE_ENV':
dev || config.experimental.allowDevelopmentBuild dev || config.experimental.allowDevelopmentBuild
......
...@@ -1599,7 +1599,11 @@ export default async function build( ...@@ -1599,7 +1599,11 @@ export default async function build(
undefined undefined
) )
) )
} else if (!isReservedPage(route)) { } else if (
!isReservedPage(route) ||
// don't consider /api reserved here
route.match(/^\/(api(\/|$))/)
) {
staticRoutes.push(pageToRoute(route)) staticRoutes.push(pageToRoute(route))
} }
} }
...@@ -3187,7 +3191,7 @@ export default async function build( ...@@ -3187,7 +3191,7 @@ export default async function build(
...(isRoutePPREnabled ...(isRoutePPREnabled
? [ ? [
{ {
type: 'header', type: 'header' as const,
key: 'user-agent', key: 'user-agent',
value: htmlBotsRegexString, value: htmlBotsRegexString,
}, },
...@@ -4183,8 +4187,10 @@ export default async function build( ...@@ -4183,8 +4187,10 @@ export default async function build(
dir, dir,
distDir, distDir,
config, config,
buildId,
configOutDir: path.join(dir, configOutDir), configOutDir: path.join(dir, configOutDir),
staticPages, staticPages,
serverPropsPages,
nextVersion: process.env.__NEXT_VERSION as string, nextVersion: process.env.__NEXT_VERSION as string,
tracingRoot: outputFileTracingRoot, tracingRoot: outputFileTracingRoot,
hasNodeMiddleware, hasNodeMiddleware,
...@@ -4197,6 +4203,7 @@ export default async function build( ...@@ -4197,6 +4203,7 @@ export default async function build(
middlewareManifest, middlewareManifest,
functionsConfigManifest, functionsConfigManifest,
hasStatic404: useStaticPages404, hasStatic404: useStaticPages404,
hasStatic500: useDefaultStatic500,
requiredServerFiles: requiredServerFilesManifest.files, requiredServerFiles: requiredServerFilesManifest.files,
}) })
}) })
......
...@@ -135,8 +135,9 @@ export async function handler( ...@@ -135,8 +135,9 @@ export async function handler(
const multiZoneDraftMode = process.env const multiZoneDraftMode = process.env
.__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean
// TODO: replace with more specific flags const isMinimalMode = Boolean(
const minimalMode = getRequestMeta(req, 'minimalMode') process.env.MINIMAL_MODE || getRequestMeta(req, 'minimalMode')
)
const prepareResult = await routeModule.prepare(req, res, { const prepareResult = await routeModule.prepare(req, res, {
srcPage, srcPage,
...@@ -167,6 +168,7 @@ export async function handler( ...@@ -167,6 +168,7 @@ export async function handler(
revalidateOnlyGenerated, revalidateOnlyGenerated,
routerServerContext, routerServerContext,
nextConfig, nextConfig,
parsedUrl,
interceptionRoutePatterns, interceptionRoutePatterns,
} = prepareResult } = prepareResult
...@@ -317,7 +319,7 @@ export async function handler( ...@@ -317,7 +319,7 @@ export async function handler(
// which will generate the RDC for the route. When resuming a Dynamic // which will generate the RDC for the route. When resuming a Dynamic
// RSC request, we'll pass the minimal postponed data to the render // RSC request, we'll pass the minimal postponed data to the render
// which will trigger the `supportsDynamicResponse` to be true. // which will trigger the `supportsDynamicResponse` to be true.
isDynamicRSCRequest && !minimalMode isDynamicRSCRequest && !isMinimalMode
: // Otherwise, we can support dynamic responses if it's a dynamic RSC request. : // Otherwise, we can support dynamic responses if it's a dynamic RSC request.
isDynamicRSCRequest) isDynamicRSCRequest)
...@@ -385,6 +387,16 @@ export async function handler( ...@@ -385,6 +387,16 @@ export async function handler(
const tracer = getTracer() const tracer = getTracer()
const activeSpan = tracer.getActiveScopeSpan() const activeSpan = tracer.getActiveScopeSpan()
const render404 = async () => {
// TODO: should route-module itself handle rendering the 404
if (routerServerContext?.render404) {
await routerServerContext.render404(req, res, parsedUrl, false)
} else {
res.end('This page could not be found')
}
return null
}
try { try {
const varyHeader = routeModule.getVaryHeader( const varyHeader = routeModule.getVaryHeader(
resolvedPathname, resolvedPathname,
...@@ -670,7 +682,7 @@ export async function handler( ...@@ -670,7 +682,7 @@ export async function handler(
isOnDemandRevalidate && isOnDemandRevalidate &&
revalidateOnlyGenerated && revalidateOnlyGenerated &&
!previousIncrementalCacheEntry && !previousIncrementalCacheEntry &&
!minimalMode !isMinimalMode
) { ) {
if (routerServerContext?.render404) { if (routerServerContext?.render404) {
await routerServerContext.render404(req, res) await routerServerContext.render404(req, res)
...@@ -712,7 +724,7 @@ export async function handler( ...@@ -712,7 +724,7 @@ export async function handler(
} }
if ( if (
!minimalMode && !isMinimalMode &&
fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER && fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER &&
staticPathKey && staticPathKey &&
!didRespond && !didRespond &&
...@@ -729,6 +741,9 @@ export async function handler( ...@@ -729,6 +741,9 @@ export async function handler(
// When fallback isn't present, abort this render so we 404 // When fallback isn't present, abort this render so we 404
fallbackMode === FallbackMode.NOT_FOUND fallbackMode === FallbackMode.NOT_FOUND
) { ) {
if (nextConfig.experimental.adapterPath) {
return await render404()
}
throw new NoFallbackError() throw new NoFallbackError()
} }
...@@ -779,6 +794,7 @@ export async function handler( ...@@ -779,6 +794,7 @@ export async function handler(
forceStaticRender: false, forceStaticRender: false,
}), }),
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
isMinimalMode,
}) })
// If the fallback response was set to null, then we should return null. // If the fallback response was set to null, then we should return null.
...@@ -810,7 +826,7 @@ export async function handler( ...@@ -810,7 +826,7 @@ export async function handler(
// Only enable RDC for Navigations if the feature is enabled. // Only enable RDC for Navigations if the feature is enabled.
supportsRDCForNavigations && supportsRDCForNavigations &&
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
!minimalMode && !isMinimalMode &&
incrementalCache && incrementalCache &&
isDynamicRSCRequest && isDynamicRSCRequest &&
// We don't typically trigger an on-demand revalidation for dynamic RSC // We don't typically trigger an on-demand revalidation for dynamic RSC
...@@ -943,6 +959,7 @@ export async function handler( ...@@ -943,6 +959,7 @@ export async function handler(
nextConfig, nextConfig,
prerenderManifest, prerenderManifest,
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
isMinimalMode,
}) })
if (isDraftMode) { if (isDraftMode) {
...@@ -985,7 +1002,7 @@ export async function handler( ...@@ -985,7 +1002,7 @@ export async function handler(
!isDynamicRSCRequest && !isDynamicRSCRequest &&
(!didPostpone || isPrefetchRSCRequest) (!didPostpone || isPrefetchRSCRequest)
) { ) {
if (!minimalMode) { if (!isMinimalMode) {
// set x-nextjs-cache header to match the header // set x-nextjs-cache header to match the header
// we set for the image-optimizer // we set for the image-optimizer
res.setHeader( res.setHeader(
...@@ -1076,7 +1093,7 @@ export async function handler( ...@@ -1076,7 +1093,7 @@ export async function handler(
// Add the cache tags header to the response if it exists and we're in // Add the cache tags header to the response if it exists and we're in
// minimal mode while rendering a static page. // minimal mode while rendering a static page.
const tags = cachedData.headers?.[NEXT_CACHE_TAGS_HEADER] const tags = cachedData.headers?.[NEXT_CACHE_TAGS_HEADER]
if (minimalMode && isSSG && tags && typeof tags === 'string') { if (isMinimalMode && isSSG && tags && typeof tags === 'string') {
res.setHeader(NEXT_CACHE_TAGS_HEADER, tags) res.setHeader(NEXT_CACHE_TAGS_HEADER, tags)
} }
...@@ -1132,7 +1149,7 @@ export async function handler( ...@@ -1132,7 +1149,7 @@ export async function handler(
if (cachedData.headers) { if (cachedData.headers) {
const headers = { ...cachedData.headers } const headers = { ...cachedData.headers }
if (!minimalMode || !isSSG) { if (!isMinimalMode || !isSSG) {
delete headers[NEXT_CACHE_TAGS_HEADER] delete headers[NEXT_CACHE_TAGS_HEADER]
} }
...@@ -1155,7 +1172,7 @@ export async function handler( ...@@ -1155,7 +1172,7 @@ export async function handler(
// Add the cache tags header to the response if it exists and we're in // Add the cache tags header to the response if it exists and we're in
// minimal mode while rendering a static page. // minimal mode while rendering a static page.
const tags = cachedData.headers?.[NEXT_CACHE_TAGS_HEADER] const tags = cachedData.headers?.[NEXT_CACHE_TAGS_HEADER]
if (minimalMode && isSSG && tags && typeof tags === 'string') { if (isMinimalMode && isSSG && tags && typeof tags === 'string') {
res.setHeader(NEXT_CACHE_TAGS_HEADER, tags) res.setHeader(NEXT_CACHE_TAGS_HEADER, tags)
} }
...@@ -1168,7 +1185,7 @@ export async function handler( ...@@ -1168,7 +1185,7 @@ export async function handler(
// Redirect information is encoded in RSC payload, so we don't need to use redirect status codes // Redirect information is encoded in RSC payload, so we don't need to use redirect status codes
if ( if (
!minimalMode && !isMinimalMode &&
cachedData.status && cachedData.status &&
RedirectStatusCode[cachedData.status] && RedirectStatusCode[cachedData.status] &&
isRSCRequest isRSCRequest
...@@ -1239,13 +1256,13 @@ export async function handler( ...@@ -1239,13 +1256,13 @@ export async function handler(
// If there's no postponed state, we should just serve the HTML. This // If there's no postponed state, we should just serve the HTML. This
// should also be the case for a resume request because it's completed // should also be the case for a resume request because it's completed
// as a server render (rather than a static render). // as a server render (rather than a static render).
if (!didPostpone || minimalMode || isRSCRequest) { if (!didPostpone || isMinimalMode || isRSCRequest) {
// If we're in test mode, we should add a sentinel chunk to the response // If we're in test mode, we should add a sentinel chunk to the response
// that's between the static and dynamic parts so we can compare the // that's between the static and dynamic parts so we can compare the
// chunks and add assertions. // chunks and add assertions.
if ( if (
process.env.__NEXT_TEST_MODE && process.env.__NEXT_TEST_MODE &&
minimalMode && isMinimalMode &&
isRoutePPREnabled && isRoutePPREnabled &&
body.contentType === HTML_CONTENT_TYPE_HEADER body.contentType === HTML_CONTENT_TYPE_HEADER
) { ) {
......
...@@ -118,6 +118,7 @@ export async function handler( ...@@ -118,6 +118,7 @@ export async function handler(
buildId, buildId,
params, params,
nextConfig, nextConfig,
parsedUrl,
isDraftMode, isDraftMode,
prerenderManifest, prerenderManifest,
routerServerContext, routerServerContext,
...@@ -135,12 +136,25 @@ export async function handler( ...@@ -135,12 +136,25 @@ export async function handler(
prerenderManifest.routes[resolvedPathname] prerenderManifest.routes[resolvedPathname]
) )
const render404 = async () => {
// TODO: should route-module itself handle rendering the 404
if (routerServerContext?.render404) {
await routerServerContext.render404(req, res, parsedUrl, false)
} else {
res.end('This page could not be found')
}
return null
}
if (isIsr && !isDraftMode) { if (isIsr && !isDraftMode) {
const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]) const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname])
const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage] const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]
if (prerenderInfo) { if (prerenderInfo) {
if (prerenderInfo.fallback === false && !isPrerendered) { if (prerenderInfo.fallback === false && !isPrerendered) {
if (nextConfig.experimental.adapterPath) {
return await render404()
}
throw new NoFallbackError() throw new NoFallbackError()
} }
} }
...@@ -264,6 +278,9 @@ export async function handler( ...@@ -264,6 +278,9 @@ export async function handler(
} }
}) })
} }
const isMinimalMode = Boolean(
process.env.MINIMAL_MODE || getRequestMeta(req, 'minimalMode')
)
const handleResponse = async (currentSpan?: Span) => { const handleResponse = async (currentSpan?: Span) => {
const responseGenerator: ResponseGenerator = async ({ const responseGenerator: ResponseGenerator = async ({
...@@ -271,7 +288,7 @@ export async function handler( ...@@ -271,7 +288,7 @@ export async function handler(
}) => { }) => {
try { try {
if ( if (
!getRequestMeta(req, 'minimalMode') && !isMinimalMode &&
isOnDemandRevalidate && isOnDemandRevalidate &&
revalidateOnlyGenerated && revalidateOnlyGenerated &&
!previousCacheEntry !previousCacheEntry
...@@ -383,6 +400,7 @@ export async function handler( ...@@ -383,6 +400,7 @@ export async function handler(
revalidateOnlyGenerated, revalidateOnlyGenerated,
responseGenerator, responseGenerator,
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
isMinimalMode,
}) })
// we don't create a cacheEntry for ISR // we don't create a cacheEntry for ISR
...@@ -396,7 +414,7 @@ export async function handler( ...@@ -396,7 +414,7 @@ export async function handler(
) )
} }
if (!getRequestMeta(req, 'minimalMode')) { if (!isMinimalMode) {
res.setHeader( res.setHeader(
'x-nextjs-cache', 'x-nextjs-cache',
isOnDemandRevalidate isOnDemandRevalidate
...@@ -419,7 +437,7 @@ export async function handler( ...@@ -419,7 +437,7 @@ export async function handler(
const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers) const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers)
if (!(getRequestMeta(req, 'minimalMode') && isIsr)) { if (!(isMinimalMode && isIsr)) {
headers.delete(NEXT_CACHE_TAGS_HEADER) headers.delete(NEXT_CACHE_TAGS_HEADER)
} }
......
...@@ -171,7 +171,8 @@ async function requestHandler( ...@@ -171,7 +171,8 @@ async function requestHandler(
incrementalCache: await pageRouteModule.getIncrementalCache( incrementalCache: await pageRouteModule.getIncrementalCache(
baseReq, baseReq,
nextConfig, nextConfig,
prerenderManifest prerenderManifest,
true
), ),
waitUntil: event.waitUntil.bind(event), waitUntil: event.waitUntil.bind(event),
......
This diff is collapsed.
{"name":"@vercel/routing-utils","main":"superstatic.js","license":"Apache-2.0"}
...@@ -9,7 +9,7 @@ import { isFullStringUrl } from './url' ...@@ -9,7 +9,7 @@ import { isFullStringUrl } from './url'
export type RouteHas = export type RouteHas =
| { | {
type: string type: 'header' | 'cookie' | 'query'
key: string key: string
value?: string value?: string
} }
......
...@@ -144,6 +144,9 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -144,6 +144,9 @@ export class IncrementalCache implements IncrementalCacheType {
if (globalCacheHandler?.FetchCache) { if (globalCacheHandler?.FetchCache) {
CurCacheHandler = globalCacheHandler.FetchCache CurCacheHandler = globalCacheHandler.FetchCache
if (IncrementalCache.debug) {
console.log('IncrementalCache: using global FetchCache cache handler')
}
} else { } else {
if (fs && serverDistDir) { if (fs && serverDistDir) {
if (IncrementalCache.debug) { if (IncrementalCache.debug) {
......
...@@ -101,6 +101,19 @@ export const getHandler = ({ ...@@ -101,6 +101,19 @@ export const getHandler = ({
return return
} }
const isMinimalMode = Boolean(
process.env.MINIMAL_MODE || getRequestMeta(req, 'minimalMode')
)
const render404 = async () => {
// TODO: should route-module itself handle rendering the 404
if (routerServerContext?.render404) {
await routerServerContext.render404(req, res, parsedUrl, false)
} else {
res.end('This page could not be found')
}
}
const { const {
buildId, buildId,
query, query,
...@@ -173,6 +186,9 @@ export const getHandler = ({ ...@@ -173,6 +186,9 @@ export const getHandler = ({
if (prerenderInfo) { if (prerenderInfo) {
if (prerenderInfo.fallback === false && !isPrerendered) { if (prerenderInfo.fallback === false && !isPrerendered) {
if (nextConfig.experimental.adapterPath) {
return await render404()
}
throw new NoFallbackError() throw new NoFallbackError()
} }
...@@ -191,7 +207,7 @@ export const getHandler = ({ ...@@ -191,7 +207,7 @@ export const getHandler = ({
// to the bot in the head. // to the bot in the head.
if ( if (
(isIsrFallback && isBot(req.headers['user-agent'] || '')) || (isIsrFallback && isBot(req.headers['user-agent'] || '')) ||
getRequestMeta(req, 'minimalMode') isMinimalMode
) { ) {
isIsrFallback = false isIsrFallback = false
} }
...@@ -454,7 +470,8 @@ export const getHandler = ({ ...@@ -454,7 +470,8 @@ export const getHandler = ({
incrementalCache: await routeModule.getIncrementalCache( incrementalCache: await routeModule.getIncrementalCache(
req, req,
nextConfig, nextConfig,
prerenderManifest prerenderManifest,
isMinimalMode
), ),
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
} }
...@@ -469,7 +486,7 @@ export const getHandler = ({ ...@@ -469,7 +486,7 @@ export const getHandler = ({
} }
if ( if (
!getRequestMeta(req, 'minimalMode') && !isMinimalMode &&
isOnDemandRevalidate && isOnDemandRevalidate &&
revalidateOnlyGenerated && revalidateOnlyGenerated &&
!previousCacheEntry !previousCacheEntry
...@@ -518,6 +535,7 @@ export const getHandler = ({ ...@@ -518,6 +535,7 @@ export const getHandler = ({
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
responseGenerator: responseGenerator, responseGenerator: responseGenerator,
prerenderManifest, prerenderManifest,
isMinimalMode,
}) })
// if we got a cache hit this wasn't an ISR fallback // if we got a cache hit this wasn't an ISR fallback
...@@ -532,7 +550,7 @@ export const getHandler = ({ ...@@ -532,7 +550,7 @@ export const getHandler = ({
return return
} }
if (hasStaticProps && !getRequestMeta(req, 'minimalMode')) { if (hasStaticProps && !isMinimalMode) {
res.setHeader( res.setHeader(
'x-nextjs-cache', 'x-nextjs-cache',
isOnDemandRevalidate isOnDemandRevalidate
...@@ -609,13 +627,7 @@ export const getHandler = ({ ...@@ -609,13 +627,7 @@ export const getHandler = ({
res.end('{"notFound":true}') res.end('{"notFound":true}')
return return
} }
// TODO: should route-module itself handle rendering the 404 return await render404()
if (routerServerContext?.render404) {
await routerServerContext.render404(req, res, parsedUrl, false)
} else {
res.end('This page could not be found')
}
return
} }
if (result.value.kind === CachedRouteKind.REDIRECT) { if (result.value.kind === CachedRouteKind.REDIRECT) {
...@@ -682,9 +694,7 @@ export const getHandler = ({ ...@@ -682,9 +694,7 @@ export const getHandler = ({
// send the _error response // send the _error response
if ( if (
getRequestMeta(req, 'customErrorRender') || getRequestMeta(req, 'customErrorRender') ||
(isErrorPage && (isErrorPage && isMinimalMode && res.statusCode === 500)
getRequestMeta(req, 'minimalMode') &&
res.statusCode === 500)
) { ) {
return null return null
} }
......
...@@ -422,7 +422,8 @@ export abstract class RouteModule< ...@@ -422,7 +422,8 @@ export abstract class RouteModule<
public async getIncrementalCache( public async getIncrementalCache(
req: IncomingMessage | BaseNextRequest, req: IncomingMessage | BaseNextRequest,
nextConfig: NextConfigComplete, nextConfig: NextConfigComplete,
prerenderManifest: DeepReadonly<PrerenderManifest> prerenderManifest: DeepReadonly<PrerenderManifest>,
isMinimalMode: boolean
): Promise<IncrementalCache> { ): Promise<IncrementalCache> {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
return (globalThis as any).__incrementalCache return (globalThis as any).__incrementalCache
...@@ -452,7 +453,7 @@ export abstract class RouteModule< ...@@ -452,7 +453,7 @@ export abstract class RouteModule<
// incremental-cache is request specific // incremental-cache is request specific
// although can have shared caches in module scope // although can have shared caches in module scope
// per-cache handler // per-cache handler
return new IncrementalCache({ const incrementalCache = new IncrementalCache({
fs: ( fs: (
require('../lib/node-fs-methods') as typeof import('../lib/node-fs-methods') require('../lib/node-fs-methods') as typeof import('../lib/node-fs-methods')
).nodeFs, ).nodeFs,
...@@ -460,14 +461,19 @@ export abstract class RouteModule< ...@@ -460,14 +461,19 @@ export abstract class RouteModule<
requestHeaders: req.headers, requestHeaders: req.headers,
allowedRevalidateHeaderKeys: allowedRevalidateHeaderKeys:
nextConfig.experimental.allowedRevalidateHeaderKeys, nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: getRequestMeta(req, 'minimalMode'), minimalMode: isMinimalMode,
serverDistDir: `${projectDir}/${this.distDir}/server`, serverDistDir: `${projectDir}/${this.distDir}/server`,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix, fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
maxMemoryCacheSize: nextConfig.cacheMaxMemorySize, maxMemoryCacheSize: nextConfig.cacheMaxMemorySize,
flushToDisk: nextConfig.experimental.isrFlushToDisk, flushToDisk: !isMinimalMode && nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => prerenderManifest, getPrerenderManifest: () => prerenderManifest,
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
}) })
// we need to expose this on globalThis as the app-render
// workStore grabs the incrementalCache from there
;(globalThis as any).__incrementalCache = incrementalCache
return incrementalCache
} }
} }
...@@ -744,12 +750,29 @@ export abstract class RouteModule< ...@@ -744,12 +750,29 @@ export abstract class RouteModule<
params || {}, params || {},
true true
) )
const paramsToInterpolate: ParsedUrlQuery =
paramsResult.hasValidParams && params let paramsToInterpolate: ParsedUrlQuery
? params
: queryResult.hasValidParams if (
? query // if both query and params are valid but one
: {} // provided more information rely on that one
query &&
params &&
paramsResult.hasValidParams &&
queryResult.hasValidParams &&
Object.keys(paramsResult.params).length <
Object.keys(queryResult.params).length
) {
paramsToInterpolate = queryResult.params
params = Object.assign(queryResult.params)
} else {
paramsToInterpolate =
paramsResult.hasValidParams && params
? params
: queryResult.hasValidParams
? query
: {}
}
req.url = serverUtils.interpolateDynamicPath( req.url = serverUtils.interpolateDynamicPath(
req.url || '/', req.url || '/',
...@@ -876,7 +899,10 @@ export abstract class RouteModule< ...@@ -876,7 +899,10 @@ export abstract class RouteModule<
public getResponseCache(req: IncomingMessage | BaseNextRequest) { public getResponseCache(req: IncomingMessage | BaseNextRequest) {
if (!this.responseCache) { if (!this.responseCache) {
const minimalMode = getRequestMeta(req, 'minimalMode') ?? false const minimalMode =
(Boolean(process.env.MINIMAL_MODE) ||
getRequestMeta(req, 'minimalMode')) ??
false
this.responseCache = new ResponseCache(minimalMode) this.responseCache = new ResponseCache(minimalMode)
} }
return this.responseCache return this.responseCache
...@@ -894,6 +920,7 @@ export abstract class RouteModule< ...@@ -894,6 +920,7 @@ export abstract class RouteModule<
revalidateOnlyGenerated, revalidateOnlyGenerated,
responseGenerator, responseGenerator,
waitUntil, waitUntil,
isMinimalMode,
}: { }: {
req: IncomingMessage | BaseNextRequest req: IncomingMessage | BaseNextRequest
nextConfig: NextConfigComplete nextConfig: NextConfigComplete
...@@ -906,6 +933,7 @@ export abstract class RouteModule< ...@@ -906,6 +933,7 @@ export abstract class RouteModule<
revalidateOnlyGenerated?: boolean revalidateOnlyGenerated?: boolean
responseGenerator: ResponseGenerator responseGenerator: ResponseGenerator
waitUntil?: (prom: Promise<any>) => void waitUntil?: (prom: Promise<any>) => void
isMinimalMode: boolean
}) { }) {
const responseCache = this.getResponseCache(req) const responseCache = this.getResponseCache(req)
const cacheEntry = await responseCache.get(cacheKey, responseGenerator, { const cacheEntry = await responseCache.get(cacheKey, responseGenerator, {
...@@ -917,7 +945,8 @@ export abstract class RouteModule< ...@@ -917,7 +945,8 @@ export abstract class RouteModule<
incrementalCache: await this.getIncrementalCache( incrementalCache: await this.getIncrementalCache(
req, req,
nextConfig, nextConfig,
prerenderManifest prerenderManifest,
isMinimalMode
), ),
waitUntil, waitUntil,
}) })
......
...@@ -154,7 +154,9 @@ export function normalizeDynamicRouteParams( ...@@ -154,7 +154,9 @@ export function normalizeDynamicRouteParams(
value.length === 1 && value.length === 1 &&
// fallback optional catch-all SSG pages have // fallback optional catch-all SSG pages have
// [[...paramName]] for the root path on Vercel // [[...paramName]] for the root path on Vercel
(value[0] === 'index' || value[0] === `[[...${key}]]`))) (value[0] === 'index' || value[0] === `[[...${key}]]`)) ||
value === 'index' ||
value === `[[...${key}]]`)
) { ) {
value = undefined value = undefined
delete query[key] delete query[key]
......
...@@ -86,6 +86,23 @@ export async function ncc_node_html_parser(task, opts) { ...@@ -86,6 +86,23 @@ export async function ncc_node_html_parser(task, opts) {
.target('src/compiled/node-html-parser') .target('src/compiled/node-html-parser')
} }
externals['@vercel/routing-utils'] = 'next/dist/compiled/@vercel/routing-utils'
export async function ncc_vercel_routing_utils(task, opts) {
await task
.source(
relative(
__dirname,
require.resolve('@vercel/routing-utils/dist/superstatic')
)
)
.ncc({
packageName: '@vercel/routing-utils',
externals,
target: 'es5',
})
.target('src/compiled/@vercel/routing-utils')
}
externals['busboy'] = 'next/dist/compiled/busboy' externals['busboy'] = 'next/dist/compiled/busboy'
export async function ncc_busboy(task, opts) { export async function ncc_busboy(task, opts) {
await task await task
...@@ -2309,6 +2326,7 @@ export async function ncc(task, opts) { ...@@ -2309,6 +2326,7 @@ export async function ncc(task, opts) {
'ncc_mswjs_interceptors', 'ncc_mswjs_interceptors',
'ncc_rsc_poison_packages', 'ncc_rsc_poison_packages',
'ncc_modelcontextprotocol_sdk', 'ncc_modelcontextprotocol_sdk',
'ncc_vercel_routing_utils',
], ],
opts opts
) )
......
...@@ -740,6 +740,10 @@ declare module 'next/dist/compiled/ws' { ...@@ -740,6 +740,10 @@ declare module 'next/dist/compiled/ws' {
import m from 'ws' import m from 'ws'
export = m export = m
} }
declare module 'next/dist/compiled/@vercel/routing-utils' {
import m from '@vercel/routing-utils/dist/superstatic'
export = m
}
declare module 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' { declare module 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' {
export * from '@modelcontextprotocol/sdk/server/mcp' export * from '@modelcontextprotocol/sdk/server/mcp'
......
This diff is collapsed.
...@@ -2443,6 +2443,12 @@ const runTests = (isDev = false) => { ...@@ -2443,6 +2443,12 @@ const runTests = (isDev = false) => {
"varyHeader": "rsc, next-router-state-tree, next-router-prefetch, next-router-segment-prefetch", "varyHeader": "rsc, next-router-state-tree, next-router-prefetch, next-router-segment-prefetch",
}, },
"staticRoutes": [ "staticRoutes": [
{
"namedRegex": "^/api/hello(?:/)?$",
"page": "/api/hello",
"regex": "^/api/hello(?:/)?$",
"routeKeys": {},
},
{ {
"namedRegex": "^/auto\\-export/another(?:/)?$", "namedRegex": "^/auto\\-export/another(?:/)?$",
"page": "/auto-export/another", "page": "/auto-export/another",
......
...@@ -94,6 +94,8 @@ describe('adapter-config', () => { ...@@ -94,6 +94,8 @@ describe('adapter-config', () => {
if (output.filePath.endsWith('.html')) { if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false) expect(output.pathname.endsWith('.html')).toBe(false)
} else if (output.pathname.endsWith('.rsc')) {
expect(output.filePath.endsWith('rsc-fallback.json')).toBe(true)
} else { } else {
expect(output.pathname).toStartWith('/docs/_next/static') expect(output.pathname).toStartWith('/docs/_next/static')
} }
......
...@@ -3,8 +3,35 @@ const require = Module.createRequire(import.meta.url) ...@@ -3,8 +3,35 @@ const require = Module.createRequire(import.meta.url)
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
cacheComponents: process.env.TEST_CACHE_COMPONENTS === '1', experimental: {
experimental: { adapterPath: require.resolve('./my-adapter.mjs') }, adapterPath: require.resolve('./my-adapter.mjs'),
cacheComponents: process.env.TEST_CACHE_COMPONENTS === '1',
},
rewrites() {
return [
{
source: '/rewrite-me',
destination: '/isr-pages',
},
]
},
redirects() {
return [
{
source: '/redirect-me',
destination: '/isr-pages',
permanent: false,
},
]
},
headers() {
return [
{
source: '/isr-pages',
headers: [{ key: 'x-custom-header', value: 'hello' }],
},
]
},
output: process.env.TEST_EXPORT ? 'export' : undefined, output: process.env.TEST_EXPORT ? 'export' : undefined,
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment