Unverified Commit 52c94abd authored by Josh Story's avatar Josh Story Committed by GitHub

[lts-maintenance] Scope response cache keys to their source route (#219)

parent 785f4c23
......@@ -25,6 +25,16 @@ The cache handler can implement the following methods: `get`, `set`, `revalidate
| --------- | -------- | ---------------------------- |
| `key` | `string` | The key to the cached value. |
Cache keys are opaque identifiers. Preserve the entire key when reading and writing entries; a key is not a request pathname.
Response keys include the response kind and a SHA-256 hash of the source route to keep different routes from sharing entries. Pages Router sources use the route definition's canonical `pathname`, so an index module has the same identity in both bundlers. App Router sources use the full `page` module name, including route groups and parallel slots. For example, a Pages Router response for `/blog/post` generated by `/blog/[slug]` uses `/route-cache/PAGES/<route-hash>/$/blog/post`, where `<route-hash>` is the 64-character hexadecimal SHA-256 digest of the UTF-8 source string `/blog/[slug]`. This bounds the added directory depth and avoids expanding Unicode source names on disk. The request pathname remains readable; the source route cannot be recovered from its hash. Handlers that previously interpreted keys as pathnames must account for this namespace. Fetch cache keys are unchanged.
Without a build adapter, prerendered responses remain at their historical `server/pages` and `server/app` paths. Their metadata identifies the exact scoped key, source owner, and fallback status that produced each immutable build seed. The built-in filesystem cache verifies that metadata before reading a historical seed, then promotes the complete response to `server/route-cache` while retaining the original artifact and its age. When an adapter is configured, build-time response artifacts are written directly to their scoped `server/route-cache` keys so colliding routes cannot overwrite one another before the adapter packages them. Static `output: 'export'` continues to emit normal public export files. Runtime reads and writes use only scoped keys. Custom cache handlers receive the opaque scoped key and are never queried with a historical pathname; an external response cache must preserve that key unchanged.
Runtime packaging must preserve the existing source-route metadata in the prerender manifest. Next.js also uses it to verify the allowed parameters and rendering mode of the selected route.
Integrations that read cached responses before invoking Next.js must also preserve source-route ownership when selecting entries. Removing the route namespace or falling back to pathname-only cache entries defeats that isolation.
Returns the cached value or `null` if not found.
### `set()`
......
......@@ -266,6 +266,7 @@
"find-up": "4.1.0",
"fresh": "0.5.2",
"glob": "7.1.7",
"hash.js": "1.1.7",
"gzip-size": "5.1.1",
"http-proxy": "1.18.1",
"http-proxy-agent": "5.0.0",
......
import { getRouteCacheKey } from '../../server/lib/route-cache-key'
import { RouteKind } from '../../server/route-kind'
import path from 'path'
import fs from 'fs/promises'
import { promisify } from 'util'
......@@ -17,7 +19,10 @@ import type {
} from '../webpack/plugins/middleware-plugin'
import { isMiddlewareFilename } from '../utils'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import {
normalizeAppPath,
selectAppPageEntry,
} from '../../shared/lib/router/utils/app-paths'
import { AdapterOutputType } from '../../shared/lib/constants'
import { RenderingMode } from '../rendering-mode'
import { isDynamicRoute } from '../../shared/lib/router/utils'
......@@ -262,7 +267,7 @@ export async function handleBuildComplete({
const appDistDir = path.join(distDir, 'server', 'app')
if (appPageKeys) {
for (const page of appPageKeys) {
for (const page of [...appPageKeys].sort().reverse()) {
if (middlewareManifest.functions.hasOwnProperty(page)) {
continue
}
......@@ -273,6 +278,15 @@ export async function handleBuildComplete({
Log.warn(`Failed to copy traced files for ${pageFile}`, err)
return {} as Record<string, string>
})
// Parallel entries share one runtime owner but retain every traced asset.
const existingOutput = appOutputMap[normalizedPage]
if (existingOutput) {
existingOutput.assets ??= {}
Object.assign(existingOutput.assets, assets)
existingOutput.assets[path.relative(tracingRoot, pageFile)] =
pageFile
continue
}
const functionConfig =
functionsConfigManifest.functions[normalizedPage] || {}
......@@ -322,6 +336,34 @@ export async function handleBuildComplete({
contentTypeHeader,
} = routesManifest.rsc
const getPrerenderFilePath = (
route: string,
isAppPage: boolean,
extension: string
) => {
const normalizedRoute = route.startsWith('/') ? route : `/${route}`
const prerender = prerenderManifest.routes[normalizedRoute]
const dynamic = prerenderManifest.dynamicRoutes[normalizedRoute]
const source =
prerender?.srcRoute ?? dynamic?.fallbackSourceRoute ?? normalizedRoute
const dataRoute = prerender?.dataRoute ?? dynamic?.dataRoute
const sourceRoute = isAppPage
? selectAppPageEntry(source, appPageKeys ?? [])
: source
return path.join(
distDir,
'server',
`${getRouteCacheKey(normalizedRoute, {
kind: isAppPage
? dataRoute
? RouteKind.APP_PAGE
: RouteKind.APP_ROUTE
: RouteKind.PAGES,
sourceRoute,
})}${extension}`
)
}
const handleAppMeta = async (
route: string,
initialOutput: AdapterOutputs[0]
......@@ -331,7 +373,7 @@ export async function handleBuildComplete({
postponed?: string
} = JSON.parse(
await fs
.readFile(path.join(appDistDir, `${route}.meta`), 'utf8')
.readFile(getPrerenderFilePath(route, true, '.meta'), 'utf8')
.catch(() => '{}')
)
......@@ -340,9 +382,10 @@ export async function handleBuildComplete({
}
if (meta?.segmentPaths) {
const segmentsDir = path.join(
appDistDir,
`${route}${prefetchSegmentDirSuffix}`
const segmentsDir = getPrerenderFilePath(
route,
true,
prefetchSegmentDirSuffix
)
for (const segmentPath of meta.segmentPaths) {
......@@ -422,9 +465,10 @@ export async function handleBuildComplete({
allowQuery = Object.values(routeKeys)
}
let filePath = path.join(
isAppPage ? appDistDir : pagesDistDir,
`${route}.${isAppPage && !dataRoute ? 'body' : 'html'}`
let filePath = getPrerenderFilePath(
route,
isAppPage,
isAppPage && !dataRoute ? '.body' : '.html'
)
// we use the static 404 for notFound: true if available
......@@ -466,7 +510,7 @@ export async function handleBuildComplete({
outputs.push(initialOutput)
if (dataRoute) {
let dataFilePath = path.join(pagesDistDir, `${route}.json`)
let dataFilePath = getPrerenderFilePath(route, false, '.json')
if (isAppPage) {
// When experimental PPR is enabled, we expect that the data
......@@ -474,12 +518,13 @@ export async function handleBuildComplete({
// be from the prefetch data route. If this isn't enabled
// for ppr, the only way to get the data is from the data
// route.
dataFilePath = path.join(
appDistDir,
dataFilePath = getPrerenderFilePath(
route,
true,
prefetchDataRoute &&
renderingMode === RenderingMode.PARTIALLY_STATIC
? prefetchDataRoute
: dataRoute
? '.prefetch.rsc'
: '.rsc'
)
}
......@@ -537,9 +582,10 @@ export async function handleBuildComplete({
fallback:
typeof fallback === 'string'
? {
filePath: path.join(
isAppPage ? appDistDir : pagesDistDir,
fallback
filePath: getPrerenderFilePath(
fallback.replace(/\.html$/, ''),
isAppPage,
'.html'
),
initialStatus: fallbackStatus,
initialHeaders: fallbackHeaders,
......
......@@ -16,7 +16,10 @@ import picomatch from 'next/dist/compiled/picomatch'
import { defaultOverrides } from '../server/require-hook'
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import isError from '../lib/is-error'
import type { NodeFileTraceReasons } from '@vercel/nft'
import type { RoutesUsingEdgeRuntime } from './utils'
......@@ -479,6 +482,73 @@ export async function collectBuildTraces({
)
})
)
// A platform may package any one of the entries for a pathname into
// its route function. The runtime selects the canonical page, so a
// parallel slot trace must also include that page and its dependencies.
const appEntriesByRoute = new Map<string, string[]>()
for (const entryName of Object.keys(entryNameFilesMap || {})) {
if (!entryName.startsWith('app/') || !entryName.endsWith('/page')) {
continue
}
const route = normalizeAppPath(entryName.slice('app'.length))
if (staticPages.includes(route)) continue
const entries = appEntriesByRoute.get(route) || []
entries.push(entryName)
appEntriesByRoute.set(route, entries)
}
await Promise.all(
[...appEntriesByRoute].map(async ([route, entries]) => {
if (entries.length < 2) return
const selectedEntry = `app${selectAppPageEntry(
route,
entries.map((entry) => entry.slice('app'.length)),
normalizeAppPath
)}`
const selectedOutputPath = path.join(
distDir,
'server',
`${selectedEntry}.js`
)
const selectedTracePath = `${selectedOutputPath}.nft.json`
const selectedTrace = JSON.parse(
await fs.readFile(selectedTracePath, 'utf8')
) as { files: string[] }
const selectedTraceDir = path.dirname(selectedTracePath)
const selectedFiles = [
selectedOutputPath,
...selectedTrace.files.map((file) =>
path.resolve(selectedTraceDir, file)
),
]
await Promise.all(
entries
.filter((entry) => entry !== selectedEntry)
.map(async (entry) => {
const tracePath = path.join(
distDir,
'server',
`${entry}.js.nft.json`
)
const traceDir = path.dirname(tracePath)
const trace = JSON.parse(
await fs.readFile(tracePath, 'utf8')
) as { files: string[] }
const files = new Set(trace.files)
for (const file of selectedFiles) {
files.add(path.relative(traceDir, file).replace(/\\/g, '/'))
}
await fs.writeFile(
tracePath,
JSON.stringify({ ...trace, files: [...files].sort() })
)
})
)
})
)
}
const moduleTypes = ['app-page', 'pages']
......
import {
getRouteCacheKey,
ROUTE_CACHE_DIRECTORY,
} from '../server/lib/route-cache-key'
import { RouteKind } from '../server/route-kind'
import type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
......@@ -152,7 +157,10 @@ import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import {
ACTION_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
......@@ -754,6 +762,24 @@ async function writeStandaloneDirectory(
),
{ overwrite: true }
)
const responseCacheDir = path.join(
distDir,
SERVER_DIRECTORY,
ROUTE_CACHE_DIRECTORY
)
if (existsSync(responseCacheDir)) {
await recursiveCopy(
responseCacheDir,
path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
ROUTE_CACHE_DIRECTORY
),
{ overwrite: true }
)
}
if (appDir) {
const originalServerApp = path.join(distDir, SERVER_DIRECTORY, 'app')
if (existsSync(originalServerApp)) {
......@@ -2012,18 +2038,17 @@ export default async function build(
let originalAppPath: string | undefined
if (pageType === 'app' && mappedAppPages) {
for (const [originalPath, normalizedPath] of Object.entries(
appPathRoutes
)) {
if (normalizedPath === page) {
pagePath = mappedAppPages[originalPath].replace(
/^private-next-app-dir/,
''
)
originalAppPath = originalPath
break
}
}
originalAppPath = selectAppPageEntry(
page,
Object.keys(appPathRoutes).filter(
(entry) => mappedAppPages[entry]
),
(entry) => appPathRoutes[entry]
)
pagePath = mappedAppPages[originalAppPath].replace(
/^private-next-app-dir/,
''
)
}
const pageFilePath = isAppBuiltinNotFoundPage(pagePath)
......@@ -3421,14 +3446,36 @@ export default async function build(
page: string,
file: string,
isSsg: boolean,
ext: 'html' | 'json',
ext: 'html' | 'json' | 'meta',
additionalSsgFile = false
) => {
if (
isSsg &&
config.experimental.adapterPath &&
config.output !== 'export'
)
return
if (isSsg && ext === 'html') {
await moveExportedPage(
originPage,
page,
file,
isSsg,
'meta',
additionalSsgFile
)
}
return staticGenerationSpan
.traceChild('move-exported-page')
.traceAsyncFn(async () => {
file = `${file}.${ext}`
const orig = path.join(outdir, file)
if (
ext === 'meta' &&
(!i18n || additionalSsgFile) &&
!existsSync(orig)
)
return
const pagePath = getPagePath(
originPage,
distDir,
......@@ -3543,8 +3590,12 @@ export default async function build(
const orig = path.join(
distDir,
'server',
'app',
'_not-found.html'
config.experimental.adapterPath && config.output !== 'export'
? `${getRouteCacheKey(UNDERSCORE_NOT_FOUND_ROUTE, {
kind: RouteKind.APP_PAGE,
sourceRoute: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
})}.html`
: 'app/_not-found.html'
)
const updatedRelativeDest = path
.join('pages', '404.html')
......
import { isRouteCacheOwner } from '../../server/lib/route-cache-key'
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { IncomingMessage, ServerResponse } from 'node:http'
......@@ -175,7 +176,14 @@ export async function handler(
let { isOnDemandRevalidate } = prepareResult
const prerenderInfo = routeModule.match(pathname, prerenderManifest)
const isPrerendered = !!prerenderManifest.routes[resolvedPathname]
const isPrerendered =
!!prerenderManifest.routes[resolvedPathname] &&
(routeModule.isDev ||
isRouteCacheOwner(
resolvedPathname,
routeModule.cacheOwner,
prerenderManifest.routes[resolvedPathname]
))
let isSSG = Boolean(
prerenderInfo ||
......
......@@ -24,6 +24,7 @@ import {
import { getCacheControlHeader } from '../../server/lib/cache-control'
import { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external'
import { isRouteCacheOwner } from '../../server/lib/route-cache-key'
import {
CachedRouteKind,
type ResponseCacheEntry,
......@@ -123,13 +124,21 @@ export async function handler(
const normalizedSrcPage = normalizeAppPath(srcPage)
// Only this route's prerenders can establish ISR or admit generated params.
const isPrerendered =
Boolean(prerenderManifest.routes[resolvedPathname]) &&
(routeModule.isDev ||
isRouteCacheOwner(
resolvedPathname,
routeModule.cacheOwner,
prerenderManifest.routes[resolvedPathname]
))
let isIsr = Boolean(
prerenderManifest.dynamicRoutes[normalizedSrcPage] ||
prerenderManifest.routes[resolvedPathname]
prerenderManifest.dynamicRoutes[normalizedSrcPage] || isPrerendered
)
if (isIsr && !isDraftMode) {
const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname])
const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]
if (prerenderInfo) {
......
(()=>{var t={330:(t,r,e)=>{"use strict";var n=e(263);var i=e(523);function BlockHash(){this.pending=null;this.pendingTotal=0;this.blockSize=this.constructor.blockSize;this.outSize=this.constructor.outSize;this.hmacStrength=this.constructor.hmacStrength;this.padLength=this.constructor.padLength/8;this.endian="big";this._delta8=this.blockSize/8;this._delta32=this.blockSize/32}r.BlockHash=BlockHash;BlockHash.prototype.update=function update(t,r){t=n.toArray(t,r);if(!this.pending)this.pending=t;else this.pending=this.pending.concat(t);this.pendingTotal+=t.length;if(this.pending.length>=this._delta8){t=this.pending;var e=t.length%this._delta8;this.pending=t.slice(t.length-e,t.length);if(this.pending.length===0)this.pending=null;t=n.join32(t,0,t.length-e,this.endian);for(var i=0;i<t.length;i+=this._delta32)this._update(t,i,i+this._delta32)}return this};BlockHash.prototype.digest=function digest(t){this.update(this._pad());i(this.pending===null);return this._digest(t)};BlockHash.prototype._pad=function pad(){var t=this.pendingTotal;var r=this._delta8;var e=r-(t+this.padLength)%r;var n=new Array(e+this.padLength);n[0]=128;for(var i=1;i<e;i++)n[i]=0;t<<=3;if(this.endian==="big"){for(var s=8;s<this.padLength;s++)n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=t>>>24&255;n[i++]=t>>>16&255;n[i++]=t>>>8&255;n[i++]=t&255}else{n[i++]=t&255;n[i++]=t>>>8&255;n[i++]=t>>>16&255;n[i++]=t>>>24&255;n[i++]=0;n[i++]=0;n[i++]=0;n[i++]=0;for(s=8;s<this.padLength;s++)n[i++]=0}return n}},525:(t,r,e)=>{"use strict";var n=e(263);var i=e(330);var s=e(975);var o=e(523);var h=n.sum32;var u=n.sum32_4;var a=n.sum32_5;var l=s.ch32;var f=s.maj32;var _=s.s0_256;var c=s.s1_256;var v=s.g0_256;var p=s.g1_256;var g=i.BlockHash;var d=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function SHA256(){if(!(this instanceof SHA256))return new SHA256;g.call(this);this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];this.k=d;this.W=new Array(64)}n.inherits(SHA256,g);t.exports=SHA256;SHA256.blockSize=512;SHA256.outSize=256;SHA256.hmacStrength=192;SHA256.padLength=64;SHA256.prototype._update=function _update(t,r){var e=this.W;for(var n=0;n<16;n++)e[n]=t[r+n];for(;n<e.length;n++)e[n]=u(p(e[n-2]),e[n-7],v(e[n-15]),e[n-16]);var i=this.h[0];var s=this.h[1];var g=this.h[2];var d=this.h[3];var m=this.h[4];var A=this.h[5];var y=this.h[6];var S=this.h[7];o(this.k.length===e.length);for(n=0;n<e.length;n++){var H=a(S,c(m),l(m,A,y),this.k[n],e[n]);var b=h(_(i),f(i,s,g));S=y;y=A;A=m;m=h(d,H);d=g;g=s;s=i;i=h(H,b)}this.h[0]=h(this.h[0],i);this.h[1]=h(this.h[1],s);this.h[2]=h(this.h[2],g);this.h[3]=h(this.h[3],d);this.h[4]=h(this.h[4],m);this.h[5]=h(this.h[5],A);this.h[6]=h(this.h[6],y);this.h[7]=h(this.h[7],S)};SHA256.prototype._digest=function digest(t){if(t==="hex")return n.toHex32(this.h,"big");else return n.split32(this.h,"big")}},975:(t,r,e)=>{"use strict";var n=e(263);var i=n.rotr32;function ft_1(t,r,e,n){if(t===0)return ch32(r,e,n);if(t===1||t===3)return p32(r,e,n);if(t===2)return maj32(r,e,n)}r.ft_1=ft_1;function ch32(t,r,e){return t&r^~t&e}r.ch32=ch32;function maj32(t,r,e){return t&r^t&e^r&e}r.maj32=maj32;function p32(t,r,e){return t^r^e}r.p32=p32;function s0_256(t){return i(t,2)^i(t,13)^i(t,22)}r.s0_256=s0_256;function s1_256(t){return i(t,6)^i(t,11)^i(t,25)}r.s1_256=s1_256;function g0_256(t){return i(t,7)^i(t,18)^t>>>3}r.g0_256=g0_256;function g1_256(t){return i(t,17)^i(t,19)^t>>>10}r.g1_256=g1_256},263:(t,r,e)=>{"use strict";var n=e(523);var i=e(782);r.inherits=i;function isSurrogatePair(t,r){if((t.charCodeAt(r)&64512)!==55296){return false}if(r<0||r+1>=t.length){return false}return(t.charCodeAt(r+1)&64512)===56320}function toArray(t,r){if(Array.isArray(t))return t.slice();if(!t)return[];var e=[];if(typeof t==="string"){if(!r){var n=0;for(var i=0;i<t.length;i++){var s=t.charCodeAt(i);if(s<128){e[n++]=s}else if(s<2048){e[n++]=s>>6|192;e[n++]=s&63|128}else if(isSurrogatePair(t,i)){s=65536+((s&1023)<<10)+(t.charCodeAt(++i)&1023);e[n++]=s>>18|240;e[n++]=s>>12&63|128;e[n++]=s>>6&63|128;e[n++]=s&63|128}else{e[n++]=s>>12|224;e[n++]=s>>6&63|128;e[n++]=s&63|128}}}else if(r==="hex"){t=t.replace(/[^a-z0-9]+/gi,"");if(t.length%2!==0)t="0"+t;for(i=0;i<t.length;i+=2)e.push(parseInt(t[i]+t[i+1],16))}}else{for(i=0;i<t.length;i++)e[i]=t[i]|0}return e}r.toArray=toArray;function toHex(t){var r="";for(var e=0;e<t.length;e++)r+=zero2(t[e].toString(16));return r}r.toHex=toHex;function htonl(t){var r=t>>>24|t>>>8&65280|t<<8&16711680|(t&255)<<24;return r>>>0}r.htonl=htonl;function toHex32(t,r){var e="";for(var n=0;n<t.length;n++){var i=t[n];if(r==="little")i=htonl(i);e+=zero8(i.toString(16))}return e}r.toHex32=toHex32;function zero2(t){if(t.length===1)return"0"+t;else return t}r.zero2=zero2;function zero8(t){if(t.length===7)return"0"+t;else if(t.length===6)return"00"+t;else if(t.length===5)return"000"+t;else if(t.length===4)return"0000"+t;else if(t.length===3)return"00000"+t;else if(t.length===2)return"000000"+t;else if(t.length===1)return"0000000"+t;else return t}r.zero8=zero8;function join32(t,r,e,i){var s=e-r;n(s%4===0);var o=new Array(s/4);for(var h=0,u=r;h<o.length;h++,u+=4){var a;if(i==="big")a=t[u]<<24|t[u+1]<<16|t[u+2]<<8|t[u+3];else a=t[u+3]<<24|t[u+2]<<16|t[u+1]<<8|t[u];o[h]=a>>>0}return o}r.join32=join32;function split32(t,r){var e=new Array(t.length*4);for(var n=0,i=0;n<t.length;n++,i+=4){var s=t[n];if(r==="big"){e[i]=s>>>24;e[i+1]=s>>>16&255;e[i+2]=s>>>8&255;e[i+3]=s&255}else{e[i+3]=s>>>24;e[i+2]=s>>>16&255;e[i+1]=s>>>8&255;e[i]=s&255}}return e}r.split32=split32;function rotr32(t,r){return t>>>r|t<<32-r}r.rotr32=rotr32;function rotl32(t,r){return t<<r|t>>>32-r}r.rotl32=rotl32;function sum32(t,r){return t+r>>>0}r.sum32=sum32;function sum32_3(t,r,e){return t+r+e>>>0}r.sum32_3=sum32_3;function sum32_4(t,r,e,n){return t+r+e+n>>>0}r.sum32_4=sum32_4;function sum32_5(t,r,e,n,i){return t+r+e+n+i>>>0}r.sum32_5=sum32_5;function sum64(t,r,e,n){var i=t[r];var s=t[r+1];var o=n+s>>>0;var h=(o<n?1:0)+e+i;t[r]=h>>>0;t[r+1]=o}r.sum64=sum64;function sum64_hi(t,r,e,n){var i=r+n>>>0;var s=(i<r?1:0)+t+e;return s>>>0}r.sum64_hi=sum64_hi;function sum64_lo(t,r,e,n){var i=r+n;return i>>>0}r.sum64_lo=sum64_lo;function sum64_4_hi(t,r,e,n,i,s,o,h){var u=0;var a=r;a=a+n>>>0;u+=a<r?1:0;a=a+s>>>0;u+=a<s?1:0;a=a+h>>>0;u+=a<h?1:0;var l=t+e+i+o+u;return l>>>0}r.sum64_4_hi=sum64_4_hi;function sum64_4_lo(t,r,e,n,i,s,o,h){var u=r+n+s+h;return u>>>0}r.sum64_4_lo=sum64_4_lo;function sum64_5_hi(t,r,e,n,i,s,o,h,u,a){var l=0;var f=r;f=f+n>>>0;l+=f<r?1:0;f=f+s>>>0;l+=f<s?1:0;f=f+h>>>0;l+=f<h?1:0;f=f+a>>>0;l+=f<a?1:0;var _=t+e+i+o+u+l;return _>>>0}r.sum64_5_hi=sum64_5_hi;function sum64_5_lo(t,r,e,n,i,s,o,h,u,a){var l=r+n+s+h+a;return l>>>0}r.sum64_5_lo=sum64_5_lo;function rotr64_hi(t,r,e){var n=r<<32-e|t>>>e;return n>>>0}r.rotr64_hi=rotr64_hi;function rotr64_lo(t,r,e){var n=t<<32-e|r>>>e;return n>>>0}r.rotr64_lo=rotr64_lo;function shr64_hi(t,r,e){return t>>>e}r.shr64_hi=shr64_hi;function shr64_lo(t,r,e){var n=t<<32-e|r>>>e;return n>>>0}r.shr64_lo=shr64_lo},782:t=>{if(typeof Object.create==="function"){t.exports=function inherits(t,r){if(r){t.super_=r;t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:false,writable:true,configurable:true}})}}}else{t.exports=function inherits(t,r){if(r){t.super_=r;var TempCtor=function(){};TempCtor.prototype=r.prototype;t.prototype=new TempCtor;t.prototype.constructor=t}}}},523:t=>{t.exports=assert;function assert(t,r){if(!t)throw new Error(r||"Assertion failed")}assert.equal=function assertEqual(t,r,e){if(t!=r)throw new Error(e||"Assertion failed: "+t+" != "+r)}}};var r={};function __nccwpck_require__(e){var n=r[e];if(n!==undefined){return n.exports}var i=r[e]={exports:{}};var s=true;try{t[e](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete r[e]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var e=__nccwpck_require__(525);module.exports=e})();
\ No newline at end of file
This software is licensed under the MIT License.
Copyright Fedor Indutny, 2014.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
{"name":"hash.js","main":"256.js","author":"Fedor Indutny <fedor@indutny.com>","license":"MIT"}
......@@ -2,7 +2,7 @@ import type { OutgoingHttpHeaders } from 'node:http'
import type { ExportRouteResult } from '../types'
import type { RenderOpts } from '../../server/app-render/types'
import type { NextParsedUrlQuery } from '../../server/request-meta'
import type { RouteMetadata } from './types'
import type { RouteCacheMetadata, RouteMetadata } from './types'
import type {
MockedRequest,
......@@ -47,7 +47,8 @@ export async function exportAppPage(
debugOutput: boolean,
isDynamicError: boolean,
fileWriter: MultiFileWriter,
sharedContext: AppSharedContext
sharedContext: AppSharedContext,
routeCache?: RouteCacheMetadata
): Promise<ExportRouteResult> {
const afterRunner = new AfterRunner()
......@@ -208,6 +209,7 @@ export async function exportAppPage(
headers,
postponed,
segmentPaths,
routeCache,
}
fileWriter.append(
......
import type { ExportRouteResult } from '../types'
import type { RouteCacheMetadata } from './types'
import type AppRouteRouteModule from '../../server/route-modules/app-route/module'
import type { AppRouteRouteHandlerContext } from '../../server/route-modules/app-route/module'
import type { IncrementalCache } from '../../server/lib/incremental-cache'
......@@ -51,7 +52,8 @@ export async function exportAppRoute(
experimental: Required<
Pick<ExperimentalConfig, 'cacheComponents' | 'authInterrupts'>
>,
buildId: string
buildId: string,
routeCache?: RouteCacheMetadata
): Promise<ExportRouteResult> {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`
......@@ -158,7 +160,7 @@ export async function exportAppRoute(
fileWriter.append(htmlFilepath.replace(/\.html$/, NEXT_BODY_SUFFIX), body)
// Write the request metadata to a file.
const meta = { status: response.status, headers }
const meta = { status: response.status, headers, routeCache }
fileWriter.append(
htmlFilepath.replace(/\.html$/, NEXT_META_SUFFIX),
JSON.stringify(meta)
......
import type { ExportRouteResult } from '../types'
import type { RouteCacheMetadata } from './types'
import type {
PagesRenderContext,
PagesSharedContext,
......@@ -54,7 +55,8 @@ export async function exportPagesPage(
hasOrigQueryValues: boolean,
renderOpts: RenderOpts,
components: LoadComponentsReturnType,
fileWriter: MultiFileWriter
fileWriter: MultiFileWriter,
routeCache?: RouteCacheMetadata
): Promise<ExportRouteResult | undefined> {
const ampState = {
ampFirst: components.pageConfig?.amp === true,
......@@ -255,6 +257,12 @@ export async function exportPagesPage(
if (!ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found
fileWriter.append(htmlFilepath, html)
if (routeCache) {
fileWriter.append(
htmlFilepath.replace(/\.html$/, '.meta'),
JSON.stringify({ routeCache })
)
}
}
return {
......
import type { OutgoingHttpHeaders } from 'node:http'
import type { ResponseCacheOwner } from '../../server/lib/route-cache-key'
export type RouteCacheMetadata = {
key: string
owner: ResponseCacheOwner
isFallback: boolean
}
export type RouteMetadata = {
status: number | undefined
headers: OutgoingHttpHeaders | undefined
postponed: string | undefined
segmentPaths: Array<string> | undefined
/** Identifies the response-cache entry represented by this build artifact. */
routeCache?: RouteCacheMetadata
/** Original payload mtime retained when a build seed is promoted. */
routeCacheLastModified?: number
}
......@@ -62,6 +62,8 @@ export interface ExportPageInput {
httpAgentOptions: NextConfigComplete['httpAgentOptions']
debugOutput?: boolean
nextConfigOutput?: NextConfigComplete['output']
/** Write build-time response artifacts to their route-scoped cache keys. */
useScopedBuildArtifacts: boolean
enableExperimentalReact?: boolean
sriEnabled: boolean
renderResumeDataCache: RenderResumeDataCache | undefined
......
import { getRouteCacheKey } from '../server/lib/route-cache-key'
import type { RouteCacheMetadata } from './routes/types'
import type {
ExportPagesInput,
ExportPageInput,
......@@ -88,6 +90,7 @@ async function exportPageImpl(
outDir: commonOutDir,
buildId,
renderResumeDataCache,
useScopedBuildArtifacts,
} = input
if (enableExperimentalReact) {
......@@ -229,11 +232,6 @@ async function exportPageImpl(
htmlFilename = 'index.html'
}
const baseDir = join(outDir, dirname(htmlFilename))
let htmlFilepath = join(outDir, htmlFilename)
await fs.mkdir(baseDir, { recursive: true })
const components = await loadComponents({
distDir,
page,
......@@ -242,6 +240,30 @@ async function exportPageImpl(
sriEnabled,
})
const routeCache: RouteCacheMetadata | undefined =
buildExport &&
commonRenderOpts.nextConfigOutput !== 'export' &&
(isAppDir || components.getStaticProps)
? {
key: getRouteCacheKey(path, components.routeModule.cacheOwner),
owner: components.routeModule.cacheOwner,
isFallback: isAppDir
? fallbackRouteParams != null && fallbackRouteParams.size > 0
: exportPath._pagesFallback ?? false,
}
: undefined
const htmlFilepath =
useScopedBuildArtifacts && routeCache
? join(distDir, 'server', `${routeCache.key}.html`)
: join(outDir, htmlFilename)
const routePagesDataDir =
useScopedBuildArtifacts && routeCache
? join(distDir, 'server')
: pagesDataDir
if (useScopedBuildArtifacts && routeCache)
htmlFilename = `${routeCache.key}.html`
await fs.mkdir(dirname(htmlFilepath), { recursive: true })
// Handle App Routes.
if (isAppDir && isAppRouteRoute(page)) {
return exportAppRoute(
......@@ -255,7 +277,8 @@ async function exportPageImpl(
htmlFilepath,
fileWriter,
commonRenderOpts.experimental,
buildId
buildId,
routeCache
)
}
......@@ -302,7 +325,8 @@ async function exportPageImpl(
debugOutput,
isDynamicError,
fileWriter,
sharedContext
sharedContext,
routeCache
)
}
......@@ -331,7 +355,7 @@ async function exportPageImpl(
subFolders,
outDir,
ampValidatorPath,
pagesDataDir,
routePagesDataDir,
buildExport,
isDynamic,
sharedContext,
......@@ -339,7 +363,8 @@ async function exportPageImpl(
hasOrigQueryValues,
renderOpts,
components,
fileWriter
fileWriter,
routeCache
)
}
......@@ -432,6 +457,10 @@ export async function exportPages(
sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),
buildId: input.buildId,
renderResumeDataCache,
useScopedBuildArtifacts:
Boolean(nextConfig.experimental.adapterPath) &&
nextConfig.output !== 'export' &&
options.buildExport,
}),
hasDebuggerAttached
? // With a debugger attached, exporting can take infinitely if we paused script execution.
......
......@@ -14,10 +14,7 @@ import type {
RenderOptsPartial as AppRenderOptsPartial,
ServerOnInstrumentationRequestError,
} from './app-render/types'
import type {
ServerComponentsHmrCache,
ResponseCacheBase,
} from './response-cache'
import type { ServerComponentsHmrCache } from './response-cache'
import type { UrlWithParsedQuery } from 'url'
import {
NormalizeError,
......@@ -74,7 +71,10 @@ import {
setRequestMeta,
} from './request-meta'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
......@@ -327,7 +327,6 @@ export default abstract class Server<
protected interceptionRoutePatterns: RegExp[]
protected nextFontManifest?: DeepReadonly<NextFontManifest>
protected instrumentation: InstrumentationModule | undefined
private readonly responseCache: ResponseCacheBase
protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean
......@@ -394,10 +393,6 @@ export default abstract class Server<
requestHeaders: Record<string, undefined | string | string[]>
}): Promise<import('./lib/incremental-cache').IncrementalCache>
protected abstract getResponseCache(options: {
dev: boolean
}): ResponseCacheBase
protected getServerComponentsHmrCache():
| ServerComponentsHmrCache
| undefined {
......@@ -605,7 +600,6 @@ export default abstract class Server<
void this.matchers.reload()
this.setAssetPrefix(assetPrefix)
this.responseCache = this.getResponseCache({ dev })
}
private handleRSCRequest: RouteHandler<ServerRequest, ServerResponse> = (
......@@ -2474,8 +2468,8 @@ export default abstract class Server<
let page = pathname
if (isAppPath) {
// the last item in the array is the root page, if there are parallel routes
page = appPaths[appPaths.length - 1]
// Use the same direct entry as the build, independent of manifest order.
page = selectAppPageEntry(pathname, appPaths)
}
const result = await this.findPageComponents({
......
import { getRouteCacheKey, ROUTE_CACHE_DIRECTORY } from '../route-cache-key'
import type { RouteMetadata } from '../../../export/routes/types'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from '.'
import type { CacheFs } from '../../../shared/lib/utils'
......@@ -6,8 +7,9 @@ import {
IncrementalCacheKind,
type CachedFetchValue,
type IncrementalCacheValue,
type GetIncrementalResponseCacheHandlerContext,
type SetIncrementalFetchCacheContext,
type SetIncrementalResponseCacheContext,
type SetIncrementalResponseCacheHandlerContext,
} from '../../response-cache'
import type { LRUCache } from '../lru-cache'
......@@ -40,6 +42,10 @@ export default class FileSystemCache implements CacheHandler {
private revalidatedTags: string[]
private static debug: boolean = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
private static memoryCache: LRUCache<CacheHandlerValue> | undefined
private static readonly seedReads = new Map<
string,
{ readers: number; version: number; promotion?: Promise<void> }
>()
constructor(ctx: FileSystemCacheContext) {
this.fs = ctx.fs
......@@ -64,6 +70,31 @@ export default class FileSystemCache implements CacheHandler {
public resetRequestCache(): void {}
private getSeedReadState(key: string) {
return FileSystemCache.seedReads.get(`${this.serverDistDir}:${key}`)
}
private beginSeedRead(key: string) {
const stateKey = `${this.serverDistDir}:${key}`
let state = FileSystemCache.seedReads.get(stateKey)
if (!state) {
state = { readers: 0, version: 0 }
FileSystemCache.seedReads.set(stateKey, state)
}
state.readers++
return { stateKey, state, version: state.version }
}
private finishSeedRead(
stateKey: string,
state: { readers: number; version: number; promotion?: Promise<void> }
) {
state.readers--
if (state.readers === 0 && !state.promotion) {
FileSystemCache.seedReads.delete(stateKey)
}
}
public async revalidateTag(
...args: Parameters<CacheHandler['revalidateTag']>
) {
......@@ -88,9 +119,17 @@ export default class FileSystemCache implements CacheHandler {
public async get(...args: Parameters<CacheHandler['get']>) {
const [key, ctx] = args
const { kind } = ctx
let readKey = key
let seedRead: ReturnType<FileSystemCache['beginSeedRead']> | undefined
let data = FileSystemCache.memoryCache?.get(key)
const activePromotion = this.getSeedReadState(key)?.promotion
if (!data && activePromotion) {
await activePromotion
data = FileSystemCache.memoryCache?.get(key)
}
if (FileSystemCache.debug) {
if (kind === IncrementalCacheKind.FETCH) {
console.log('get', key, ctx.tags, kind, !!data)
......@@ -99,12 +138,63 @@ export default class FileSystemCache implements CacheHandler {
}
}
// let's check the disk for seed data
const isResponse =
kind === IncrementalCacheKind.PAGES ||
kind === IncrementalCacheKind.APP_PAGE ||
kind === IncrementalCacheKind.APP_ROUTE
if (
!data &&
isResponse &&
key.startsWith(`/${ROUTE_CACHE_DIRECTORY}/`) &&
process.env.NEXT_RUNTIME !== 'edge'
) {
const primaryPath = this.getFilePath(
kind === IncrementalCacheKind.APP_ROUTE ? `${key}.body` : `${key}.html`,
kind
)
if (!this.fs.existsSync(primaryPath)) {
const marker = key.indexOf('/$/')
if (marker !== -1) {
const legacyKey = key.slice(marker + 2)
const legacyMetaPath = this.getFilePath(
`${legacyKey}${NEXT_META_SUFFIX}`,
kind
)
try {
const meta = JSON.parse(
this.fs.readFileSync(legacyMetaPath, 'utf8')
) as RouteMetadata
const namespaceEnd = key.indexOf('/$/')
const ownerKey = meta.routeCache
? getRouteCacheKey('/', meta.routeCache.owner)
: undefined
if (
meta.routeCache?.key === key &&
(meta.routeCache.isFallback === Boolean(ctx.isFallback) ||
// PPR also reads fallback shells through ordinary response and
// navigation resume-data lookups, which set isFallback: false.
(kind === IncrementalCacheKind.APP_PAGE &&
ctx.isRoutePPREnabled &&
meta.postponed != null)) &&
ownerKey?.slice(0, ownerKey.indexOf('/$/')) ===
key.slice(0, namespaceEnd)
) {
readKey = legacyKey
seedRead = this.beginSeedRead(key)
}
} catch {}
}
}
}
// Check the scoped disk entry first, or a verified immutable build seed
// only when its scoped primary payload is genuinely absent.
if (!data && process.env.NEXT_RUNTIME !== 'edge') {
try {
if (kind === IncrementalCacheKind.APP_ROUTE) {
const filePath = this.getFilePath(
`${key}.body`,
`${readKey}.body`,
IncrementalCacheKind.APP_ROUTE
)
const fileData = await this.fs.readFile(filePath)
......@@ -118,7 +208,7 @@ export default class FileSystemCache implements CacheHandler {
)
data = {
lastModified: mtime.getTime(),
lastModified: meta.routeCacheLastModified ?? mtime.getTime(),
value: {
kind: CachedRouteKind.APP_ROUTE,
body: fileData,
......@@ -128,7 +218,7 @@ export default class FileSystemCache implements CacheHandler {
}
} else {
const filePath = this.getFilePath(
kind === IncrementalCacheKind.FETCH ? key : `${key}.html`,
kind === IncrementalCacheKind.FETCH ? readKey : `${readKey}.html`,
kind
)
......@@ -166,17 +256,15 @@ export default class FileSystemCache implements CacheHandler {
}
}
} else if (kind === IncrementalCacheKind.APP_PAGE) {
// We try to load the metadata file, but if it fails, we don't
// error. We also don't load it if this is a fallback.
let meta: RouteMetadata | undefined
try {
meta = JSON.parse(
await this.fs.readFile(
filePath.replace(/\.html$/, NEXT_META_SUFFIX),
'utf8'
)
// Metadata is required for both normal entries and fallback shells.
// Promoted entries publish their primary payload last, so a missing
// sidecar means the scoped entry is incomplete.
const meta: RouteMetadata = JSON.parse(
await this.fs.readFile(
filePath.replace(/\.html$/, NEXT_META_SUFFIX),
'utf8'
)
} catch {}
)
let maybeSegmentData: Map<string, Buffer> | undefined
if (meta?.segmentPaths) {
......@@ -187,7 +275,7 @@ export default class FileSystemCache implements CacheHandler {
// identical regardless.
const segmentData: Map<string, Buffer> = new Map()
maybeSegmentData = segmentData
const segmentsDir = key + RSC_SEGMENTS_DIR_SUFFIX
const segmentsDir = readKey + RSC_SEGMENTS_DIR_SUFFIX
await Promise.all(
meta.segmentPaths.map(async (segmentPath: string) => {
const segmentDataFilePath = this.getFilePath(
......@@ -212,14 +300,14 @@ export default class FileSystemCache implements CacheHandler {
if (!ctx.isFallback) {
rscData = await this.fs.readFile(
this.getFilePath(
`${key}${ctx.isRoutePPREnabled ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX}`,
`${readKey}${ctx.isRoutePPREnabled ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX}`,
IncrementalCacheKind.APP_PAGE
)
)
}
data = {
lastModified: mtime.getTime(),
lastModified: meta.routeCacheLastModified ?? mtime.getTime(),
value: {
kind: CachedRouteKind.APP_PAGE,
html: fileData,
......@@ -231,14 +319,19 @@ export default class FileSystemCache implements CacheHandler {
},
}
} else if (kind === IncrementalCacheKind.PAGES) {
let meta: RouteMetadata | undefined
const meta: RouteMetadata = JSON.parse(
await this.fs.readFile(
filePath.replace(/\.html$/, NEXT_META_SUFFIX),
'utf8'
)
)
let pageData: string | object = {}
if (!ctx.isFallback) {
pageData = JSON.parse(
await this.fs.readFile(
this.getFilePath(
`${key}${NEXT_DATA_SUFFIX}`,
`${readKey}${NEXT_DATA_SUFFIX}`,
IncrementalCacheKind.PAGES
),
'utf8'
......@@ -247,7 +340,7 @@ export default class FileSystemCache implements CacheHandler {
}
data = {
lastModified: mtime.getTime(),
lastModified: meta.routeCacheLastModified ?? mtime.getTime(),
value: {
kind: CachedRouteKind.PAGES,
html: fileData,
......@@ -264,9 +357,14 @@ export default class FileSystemCache implements CacheHandler {
}
if (data) {
FileSystemCache.memoryCache?.set(key, data)
if (!seedRead) {
FileSystemCache.memoryCache?.set(key, data)
}
}
} catch {
if (seedRead) {
this.finishSeedRead(seedRead.stateKey, seedRead.state)
}
return null
}
}
......@@ -288,6 +386,9 @@ export default class FileSystemCache implements CacheHandler {
// had a tag revalidated, if we want to be a background
// revalidation instead we return data.lastModified = -1
if (isStale(cacheTags, data?.lastModified || Date.now())) {
if (seedRead) {
this.finishSeedRead(seedRead.stateKey, seedRead.state)
}
return null
}
}
......@@ -311,14 +412,180 @@ export default class FileSystemCache implements CacheHandler {
}
}
if (seedRead && data) {
const { stateKey, state, version } = seedRead
try {
if (state.version === version) {
await this.promoteSeed(
key,
readKey,
data,
ctx as GetIncrementalResponseCacheHandlerContext,
stateKey,
state,
version
)
if (
state.version === version &&
!FileSystemCache.memoryCache?.get(key)
) {
FileSystemCache.memoryCache?.set(key, data)
}
}
} finally {
this.finishSeedRead(stateKey, state)
}
}
return data ?? null
}
private async promoteSeed(
key: string,
seedKey: string,
data: CacheHandlerValue,
ctx: GetIncrementalResponseCacheHandlerContext,
stateKey: string,
state: { readers: number; version: number; promotion?: Promise<void> },
version: number
) {
const writeFileAtomic = this.fs.writeFileAtomic
if (!this.flushToDisk || !writeFileAtomic || !data.value) return
if (state.promotion) {
await state.promotion
return
}
const promotion = (async () => {
const value = data.value
if (
!value ||
state.version !== version ||
(value.kind !== CachedRouteKind.PAGES &&
value.kind !== CachedRouteKind.APP_PAGE &&
value.kind !== CachedRouteKind.APP_ROUTE)
) {
return
}
const kind = ctx.kind
const primaryPath = this.getFilePath(
value.kind === CachedRouteKind.APP_ROUTE
? `${key}.body`
: `${key}.html`,
kind
)
if (this.fs.existsSync(primaryPath)) return
const seedPrimaryPath = this.getFilePath(
value.kind === CachedRouteKind.APP_ROUTE
? `${seedKey}.body`
: `${seedKey}.html`,
kind
)
const seedMetaPath = seedPrimaryPath.replace(
value.kind === CachedRouteKind.APP_ROUTE ? /\.body$/ : /\.html$/,
NEXT_META_SUFFIX
)
const meta = JSON.parse(
await this.fs.readFile(seedMetaPath, 'utf8')
) as RouteMetadata
meta.routeCacheLastModified = data.lastModified
// Copy every ancillary seed file first. The scoped primary payload is
// the publication marker and is written only after metadata is complete.
const ancillaryFiles: Array<{ path: string; data: Buffer | string }> = []
if (value.kind === CachedRouteKind.PAGES && !ctx.isFallback) {
ancillaryFiles.push({
path: this.getFilePath(`${key}${NEXT_DATA_SUFFIX}`, kind),
data: await this.fs.readFile(
this.getFilePath(`${seedKey}${NEXT_DATA_SUFFIX}`, kind)
),
})
} else if (value.kind === CachedRouteKind.APP_PAGE) {
const rscSuffix = ctx.isRoutePPREnabled
? RSC_PREFETCH_SUFFIX
: RSC_SUFFIX
const seedRscPath = this.getFilePath(`${seedKey}${rscSuffix}`, kind)
// Next 15 PPR shells can include a full prefetch payload even when
// first read as a fallback. Preserve it for subsequent ordinary reads.
if (
!ctx.isFallback ||
(ctx.isRoutePPREnabled && this.fs.existsSync(seedRscPath))
) {
ancillaryFiles.push({
path: this.getFilePath(`${key}${rscSuffix}`, kind),
data: await this.fs.readFile(seedRscPath),
})
}
ancillaryFiles.push(
...(await Promise.all(
(meta.segmentPaths ?? []).map(async (segmentPath) => ({
path: this.getFilePath(
key +
RSC_SEGMENTS_DIR_SUFFIX +
segmentPath +
RSC_SEGMENT_SUFFIX,
kind
),
data: await this.fs.readFile(
this.getFilePath(
seedKey +
RSC_SEGMENTS_DIR_SUFFIX +
segmentPath +
RSC_SEGMENT_SUFFIX,
kind
)
),
}))
))
)
}
const writer = new MultiFileWriter(this.fs)
for (const file of ancillaryFiles) writer.append(file.path, file.data)
await writer.wait()
if (state.version !== version) return
const metaPath = primaryPath.replace(
value.kind === CachedRouteKind.APP_ROUTE ? /\.body$/ : /\.html$/,
NEXT_META_SUFFIX
)
await this.fs.mkdir(path.dirname(metaPath))
await this.fs.writeFile(metaPath, JSON.stringify(meta))
if (state.version !== version || this.fs.existsSync(primaryPath)) return
await writeFileAtomic.call(
this.fs,
primaryPath,
await this.fs.readFile(seedPrimaryPath)
)
})()
state.promotion = promotion.catch((error) => {
if (FileSystemCache.debug) {
console.log('FileSystemCache: failed to promote build seed', error)
}
})
try {
await state.promotion
} finally {
if (state.promotion) state.promotion = undefined
if (state.readers === 0) FileSystemCache.seedReads.delete(stateKey)
}
}
public async set(
key: string,
data: IncrementalCacheValue | null,
ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext
ctx:
| SetIncrementalFetchCacheContext
| SetIncrementalResponseCacheHandlerContext
) {
const seedState = this.getSeedReadState(key)
if (seedState) seedState.version++
FileSystemCache.memoryCache?.set(key, {
value: data,
lastModified: Date.now(),
......@@ -330,6 +597,8 @@ export default class FileSystemCache implements CacheHandler {
if (!this.flushToDisk || !data) return
await seedState?.promotion
// Create a new writer that will prepare to write all the files to disk
// after their containing directory is created.
const writer = new MultiFileWriter(this.fs)
......@@ -408,6 +677,17 @@ export default class FileSystemCache implements CacheHandler {
segmentPaths,
}
writer.append(
htmlPath.replace(/\.html$/, NEXT_META_SUFFIX),
JSON.stringify(meta)
)
} else {
const meta: RouteMetadata = {
headers: data.headers,
status: data.status,
postponed: undefined,
segmentPaths: undefined,
}
writer.append(
htmlPath.replace(/\.html$/, NEXT_META_SUFFIX),
JSON.stringify(meta)
......@@ -448,6 +728,16 @@ export default class FileSystemCache implements CacheHandler {
throw new Error(`Unexpected file path kind: ${kind}`)
}
// Scoped response artifacts live outside the compiled route and ASO files.
if (
(kind === IncrementalCacheKind.PAGES ||
kind === IncrementalCacheKind.APP_PAGE ||
kind === IncrementalCacheKind.APP_ROUTE) &&
key.startsWith(`/${ROUTE_CACHE_DIRECTORY}/`)
) {
rootDir = path.join(this.serverDistDir, '.')
}
const filePath = path.join(rootDir, key)
if (!(filePath.startsWith(rootDir + path.sep) || filePath === rootDir)) {
throw new Error(`Invalid file path: ${filePath}`)
......
import { getRouteCacheKey, isRouteCacheOwner } from '../route-cache-key'
import type { CacheFs } from '../../../shared/lib/utils'
import type { PrerenderManifest } from '../../../build'
import {
......@@ -10,20 +11,22 @@ import {
type IncrementalFetchCacheEntry,
type GetIncrementalFetchCacheContext,
type GetIncrementalResponseCacheContext,
type GetIncrementalResponseCacheHandlerContext,
type GetIncrementalImageCacheContext,
type CachedFetchValue,
type SetIncrementalFetchCacheContext,
type SetIncrementalResponseCacheContext,
type SetIncrementalResponseCacheHandlerContext,
type SetIncrementalImageCacheContext,
} from '../../response-cache'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import FileSystemCache from './file-system-cache'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import {
CACHE_ONE_YEAR,
PRERENDER_REVALIDATE_HEADER,
} from '../../../lib/constants'
import { toRoute } from '../to-route'
import { SharedCacheControls } from './shared-cache-controls.external'
import {
getPrerenderResumeDataCache,
......@@ -31,7 +34,7 @@ import {
workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../../shared/lib/invariant-error'
import type { Revalidate } from '../cache-control'
import type { CacheControl, Revalidate } from '../cache-control'
import { getPreviouslyRevalidatedTags } from '../../server-utils'
import { workAsyncStorage } from '../../app-render/work-async-storage.external'
import { DetachedPromise } from '../../../lib/detached-promise'
......@@ -105,7 +108,10 @@ export class CacheHandler {
public async get(
_cacheKey: string,
_ctx: GetIncrementalFetchCacheContext | GetIncrementalResponseCacheContext
_ctx:
| GetIncrementalFetchCacheContext
| GetIncrementalResponseCacheHandlerContext
| GetIncrementalImageCacheContext
): Promise<CacheHandlerValue | null> {
return {} as any
}
......@@ -113,7 +119,10 @@ export class CacheHandler {
public async set(
_cacheKey: string,
_data: IncrementalCacheValue | null,
_ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext
_ctx:
| SetIncrementalFetchCacheContext
| SetIncrementalResponseCacheHandlerContext
| SetIncrementalImageCacheContext
): Promise<void> {}
public async revalidateTag(
......@@ -160,6 +169,7 @@ export class IncrementalCache implements IncrementalCacheType {
* prerender manifest until the in-memory cache is updated with new values.
*/
private readonly cacheControls: SharedCacheControls
private readonly locales?: readonly string[]
constructor({
fs,
......@@ -173,6 +183,7 @@ export class IncrementalCache implements IncrementalCacheType {
fetchCacheKeyPrefix,
CurCacheHandler,
allowedRevalidateHeaderKeys,
locales,
}: {
fs?: CacheFs
dev: boolean
......@@ -180,6 +191,7 @@ export class IncrementalCache implements IncrementalCacheType {
serverDistDir?: string
flushToDisk?: boolean
allowedRevalidateHeaderKeys?: string[]
locales?: readonly string[]
requestHeaders: IncrementalCache['requestHeaders']
maxMemoryCacheSize?: number
getPrerenderManifest: () => DeepReadonly<PrerenderManifest>
......@@ -226,7 +238,11 @@ export class IncrementalCache implements IncrementalCacheType {
this.requestHeaders = requestHeaders
this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys
this.prerenderManifest = getPrerenderManifest()
this.cacheControls = new SharedCacheControls(this.prerenderManifest)
this.locales = locales
this.cacheControls = new SharedCacheControls(
this.prerenderManifest,
locales
)
this.fetchCacheKeyPrefix = fetchCacheKeyPrefix
let revalidatedTags: string[] = []
......@@ -259,7 +275,7 @@ export class IncrementalCache implements IncrementalCacheType {
}
private calculateRevalidate(
pathname: string,
cacheControl: CacheControl | undefined,
fromTime: number,
dev: boolean,
isFallback: boolean | undefined
......@@ -269,8 +285,6 @@ export class IncrementalCache implements IncrementalCacheType {
if (dev)
return Math.floor(performance.timeOrigin + performance.now() - 1000)
const cacheControl = this.cacheControls.get(toRoute(pathname))
// if an entry isn't present in routes we fallback to a default
// of revalidating after 1 second unless it's a fallback request.
const initialRevalidateSeconds = cacheControl
......@@ -287,10 +301,6 @@ export class IncrementalCache implements IncrementalCacheType {
return revalidateAfter
}
_getPathname(pathname: string, fetchCache?: boolean) {
return fetchCache ? pathname : normalizePagePath(pathname)
}
resetRequestCache() {
this.cacheHandler?.resetRequestCache?.()
}
......@@ -472,12 +482,18 @@ export class IncrementalCache implements IncrementalCacheType {
): Promise<IncrementalFetchCacheEntry | null>
async get(
cacheKey: string,
ctx: GetIncrementalResponseCacheContext
ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext
): Promise<IncrementalResponseCacheEntry | null>
async get(
cacheKey: string,
ctx: GetIncrementalFetchCacheContext | GetIncrementalResponseCacheContext
ctx:
| GetIncrementalFetchCacheContext
| GetIncrementalResponseCacheContext
| GetIncrementalImageCacheContext
): Promise<IncrementalCacheEntry | null> {
if (ctx.kind === IncrementalCacheKind.IMAGE) {
throw new InvariantError('Images must use the image optimizer cache')
}
// Unlike other caches if we have a resume data cache, we use it even if
// testmode would normally disable it or if requestHeaders say 'no-cache'.
if (ctx.kind === IncrementalCacheKind.FETCH) {
......@@ -504,12 +520,16 @@ export class IncrementalCache implements IncrementalCacheType {
return null
}
cacheKey = this._getPathname(
cacheKey,
ctx.kind === IncrementalCacheKind.FETCH
)
const cacheData = await this.cacheHandler?.get(cacheKey, ctx)
let storageKey = cacheKey
let handlerContext: Parameters<CacheHandler['get']>[1] = ctx
if (ctx.kind !== IncrementalCacheKind.FETCH) {
// Ownership scopes the key and metadata inside Next.js. Storage handlers
// only need the resulting key and the existing cache options.
const { route, ...responseContext } = ctx
storageKey = getRouteCacheKey(cacheKey, route)
handlerContext = responseContext
}
const cacheData = await this.cacheHandler?.get(storageKey, handlerContext)
if (ctx.kind === IncrementalCacheKind.FETCH) {
if (!cacheData) {
......@@ -556,7 +576,7 @@ export class IncrementalCache implements IncrementalCacheType {
}
let entry: IncrementalResponseCacheEntry | null = null
const cacheControl = this.cacheControls.get(toRoute(cacheKey))
const cacheControl = this.cacheControls.get(cacheKey, ctx.route)
let isStale: boolean | -1 | undefined
let revalidateAfter: Revalidate
......@@ -566,7 +586,7 @@ export class IncrementalCache implements IncrementalCacheType {
revalidateAfter = -1 * CACHE_ONE_YEAR
} else {
revalidateAfter = this.calculateRevalidate(
cacheKey,
cacheControl,
cacheData?.lastModified || performance.timeOrigin + performance.now(),
this.dev ?? false,
ctx.isFallback
......@@ -589,7 +609,13 @@ export class IncrementalCache implements IncrementalCacheType {
if (
!cacheData &&
this.prerenderManifest.notFoundRoutes.includes(cacheKey)
this.prerenderManifest.notFoundRoutes.includes(cacheKey) &&
isRouteCacheOwner(
cacheKey,
ctx.route,
this.prerenderManifest.routes[cacheKey],
this.locales
)
) {
// for the first hit after starting the server the cache
// may not have a way to save notFound: true so if
......@@ -615,13 +641,19 @@ export class IncrementalCache implements IncrementalCacheType {
async set(
pathname: string,
data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,
ctx: SetIncrementalResponseCacheContext
ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext
): Promise<void>
async set(
pathname: string,
data: IncrementalCacheValue | null,
ctx: SetIncrementalFetchCacheContext | SetIncrementalResponseCacheContext
ctx:
| SetIncrementalFetchCacheContext
| SetIncrementalResponseCacheContext
| SetIncrementalImageCacheContext
): Promise<void> {
if ('kind' in ctx && ctx.kind === IncrementalCacheKind.IMAGE) {
throw new InvariantError('Images must use the image optimizer cache')
}
// Even if we otherwise disable caching for testMode or if no fetchCache is
// configured we still always stash results in the resume data cache if one
// exists. This is because this is a transient in memory cache that
......@@ -639,7 +671,16 @@ export class IncrementalCache implements IncrementalCacheType {
if (this.disableForTestmode || (this.dev && !ctx.fetchCache)) return
pathname = this._getPathname(pathname, ctx.fetchCache)
let storageKey = pathname
let handlerContext: Parameters<CacheHandler['set']>[2] = ctx
if (!ctx.fetchCache) {
const { route, ...responseContext } = ctx
if (!route) {
throw new InvariantError('Response cache requires a source route')
}
storageKey = getRouteCacheKey(pathname, route)
handlerContext = responseContext
}
// FetchCache has upper limit of 2MB per-entry currently
const itemSize = JSON.stringify(data).length
......@@ -664,10 +705,10 @@ export class IncrementalCache implements IncrementalCacheType {
try {
if (!ctx.fetchCache && ctx.cacheControl) {
this.cacheControls.set(toRoute(pathname), ctx.cacheControl)
this.cacheControls.set(storageKey, ctx.cacheControl)
}
await this.cacheHandler?.set(pathname, data, ctx)
await this.cacheHandler?.set(storageKey, data, handlerContext)
} catch (error) {
console.warn('Failed to update prerender cache for', pathname, error)
}
......
......@@ -16,16 +16,20 @@ export function getMemoryCache(maxMemoryCacheSize: number) {
} else if (value.kind === CachedRouteKind.FETCH) {
return JSON.stringify(value.data || '').length
} else if (value.kind === CachedRouteKind.APP_ROUTE) {
return value.body.length
return Math.max(1, value.body.length)
}
// rough estimate of size of cache value
return (
value.html.length +
(JSON.stringify(
value.kind === CachedRouteKind.APP_PAGE
? value.rscData
: value.pageData
)?.length || 0)
return Math.max(
1,
(value.kind === CachedRouteKind.APP_PAGE
? value.postponed?.length || 0
: 0) +
value.html.length +
(JSON.stringify(
value.kind === CachedRouteKind.APP_PAGE
? value.rscData
: value.pageData
)?.length || 0)
)
})
}
......
import type {
DynamicPrerenderManifestRoute,
PrerenderManifestRoute,
PrerenderManifest,
} from '../../../build'
import { RenderingMode } from '../../../build/rendering-mode'
import { SharedCacheControls } from './shared-cache-controls.external'
import { getRouteCacheKey } from '../route-cache-key'
import { RouteKind } from '../../route-kind'
const owner = { kind: RouteKind.PAGES, sourceRoute: '/[id]' }
const other = { kind: RouteKind.PAGES, sourceRoute: '/[...slug]' }
const appRoute = (sourceRoute: string) => ({
kind: RouteKind.APP_ROUTE,
sourceRoute,
})
describe('SharedCacheControls', () => {
let sharedCacheControls: SharedCacheControls
let prerenderManifest
let prerenderManifest: Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>
beforeEach(() => {
prerenderManifest = {
......@@ -58,37 +68,141 @@ describe('SharedCacheControls', () => {
sharedCacheControls.clear()
})
it('rejects cache-control reads without a source route', () => {
expect(() => {
// @ts-expect-error cache-control lookups require a source route
sharedCacheControls.get('/route2')
}).toThrow('Response cache requires a source route')
})
it('should get cache control from in-memory cache', () => {
sharedCacheControls.set('/route1', { revalidate: 15, expire: undefined })
const cacheControl = sharedCacheControls.get('/route1')
sharedCacheControls.set(getRouteCacheKey('/route1', appRoute('/route1')), {
revalidate: 15,
expire: undefined,
})
const cacheControl = sharedCacheControls.get('/route1', appRoute('/route1'))
expect(cacheControl).toEqual({ revalidate: 15 })
})
it('should get cache control from prerender manifest if not in cache', () => {
const cacheControl = sharedCacheControls.get('/route2')
const cacheControl = sharedCacheControls.get('/route2', appRoute('/route2'))
expect(cacheControl).toEqual({ revalidate: 20, expire: 40 })
})
it('should return undefined if cache control not found', () => {
const cacheControl = sharedCacheControls.get('/route3')
const cacheControl = sharedCacheControls.get('/route3', appRoute('/route3'))
expect(cacheControl).toBeUndefined()
})
it('should set cache control in cache', () => {
sharedCacheControls.set('/route3', { revalidate: 30, expire: undefined })
const cacheControl = sharedCacheControls.get('/route3')
sharedCacheControls.set(getRouteCacheKey('/route3', appRoute('/route3')), {
revalidate: 30,
expire: undefined,
})
const cacheControl = sharedCacheControls.get('/route3', appRoute('/route3'))
expect(cacheControl).toEqual({ revalidate: 30 })
})
it('should clear the in-memory cache', () => {
sharedCacheControls.set('/route3', { revalidate: 30, expire: undefined })
sharedCacheControls.set(getRouteCacheKey('/route3', appRoute('/route3')), {
revalidate: 30,
expire: undefined,
})
sharedCacheControls.clear()
const cacheControl = sharedCacheControls.get('/route3')
const cacheControl = sharedCacheControls.get('/route3', appRoute('/route3'))
expect(cacheControl).toBeUndefined()
})
it('should get cache control from prerender manifest for dynamic route with fallback', () => {
const cacheControl = sharedCacheControls.get('/route4')
const cacheControl = sharedCacheControls.get('/route4', appRoute('/route4'))
expect(cacheControl).toEqual({ revalidate: 30, expire: 50 })
})
it('uses build-time metadata only for its recorded owner', () => {
prerenderManifest.routes['/route2'].srcRoute = owner.sourceRoute
prerenderManifest.routes['/route2'].dataRoute =
'/_next/data/build/route2.json'
expect(sharedCacheControls.get('/route2', owner)).toEqual({
revalidate: 20,
expire: 40,
})
expect(sharedCacheControls.get('/route2', other)).toBeUndefined()
})
it("does not borrow a static route's metadata for a dynamic response", () => {
prerenderManifest.routes['/route2'].dataRoute =
'/_next/data/build/route2.json'
expect(sharedCacheControls.get('/route2', owner)).toBeUndefined()
})
it('keeps runtime lifetime overrides separate from other owners and seeds', () => {
prerenderManifest.routes['/route2'].srcRoute = owner.sourceRoute
prerenderManifest.routes['/route2'].dataRoute =
'/_next/data/build/route2.json'
sharedCacheControls.set(getRouteCacheKey('/route2', other), {
revalidate: 1,
expire: 2,
})
expect(sharedCacheControls.get('/route2', owner)).toEqual({
revalidate: 20,
expire: 40,
})
expect(sharedCacheControls.get('/route2', other)).toEqual({
revalidate: 1,
expire: 2,
})
})
it('uses locale-prefixed static metadata only for its source page', () => {
prerenderManifest.routes['/fr/route2'] = {
...prerenderManifest.routes['/route2'],
dataRoute: '/_next/data/build/fr/route2.json',
}
sharedCacheControls = new SharedCacheControls(prerenderManifest, [
'en',
'fr',
])
expect(
sharedCacheControls.get('/fr/route2', {
kind: RouteKind.PAGES,
sourceRoute: '/route2',
})
).toEqual({ revalidate: 20, expire: 40 })
expect(sharedCacheControls.get('/fr/route2', other)).toBeUndefined()
})
it('uses the source pattern for locale-prefixed fallback metadata', () => {
prerenderManifest.dynamicRoutes['/route4'].dataRoute =
'/_next/data/build/route4.json'
sharedCacheControls = new SharedCacheControls(prerenderManifest, [
'en',
'fr',
])
expect(
sharedCacheControls.get('/fr/route4', {
kind: RouteKind.PAGES,
sourceRoute: '/route4',
})
).toEqual({ revalidate: 30, expire: 50 })
expect(sharedCacheControls.get('/fr/route4', other)).toBeUndefined()
})
it('keeps a partial fallback shell lifetime with its original source', () => {
prerenderManifest.dynamicRoutes['/catalog/a/[item]'] = {
...prerenderManifest.dynamicRoutes['/route4'],
dataRoute: '/catalog/a/[item].rsc',
fallbackSourceRoute: '/catalog/[category]/[item]',
}
expect(
sharedCacheControls.get('/catalog/a/[item]', {
kind: RouteKind.APP_PAGE,
sourceRoute: '/(group)/catalog/[category]/[item]/page',
})
).toEqual({ revalidate: 30, expire: 50 })
expect(
sharedCacheControls.get('/catalog/a/[item]', {
kind: RouteKind.APP_PAGE,
sourceRoute: '/catalog/a/[item]/page',
})
).toBeUndefined()
})
})
import type { PrerenderManifest } from '../../../build'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import type { CacheControl } from '../cache-control'
import {
getRouteCacheKey,
isRouteCacheOwner,
type ResponseCacheOwner,
} from '../route-cache-key'
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { RouteKind } from '../../route-kind'
/**
* A shared cache of cache controls for routes. This cache is used so we don't
......@@ -21,7 +28,8 @@ export class SharedCacheControls {
*/
private readonly prerenderManifest: DeepReadonly<
Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>
>
>,
private readonly locales?: readonly string[]
) {}
/**
......@@ -30,19 +38,28 @@ export class SharedCacheControls {
* in-memory cache, it will be sourced from the prerender manifest.
*
* @param route the route to get the cache control for
* @param owner the source route that owns the response
* @returns the cache control for the route, or undefined if the values
* are not present in the in-memory cache or the prerender manifest
*/
public get(route: string): CacheControl | undefined {
public get(
route: string,
owner: ResponseCacheOwner
): CacheControl | undefined {
// This is a copy on write cache that is updated when the cache is updated.
// If the cache is never written to, then the values will be sourced from
// the prerender manifest.
let cacheControl = SharedCacheControls.cacheControls.get(route)
let cacheControl = SharedCacheControls.cacheControls.get(
getRouteCacheKey(route, owner)
)
if (cacheControl) return cacheControl
let prerenderData = this.prerenderManifest.routes[route]
if (prerenderData) {
if (
prerenderData &&
isRouteCacheOwner(route, owner, prerenderData, this.locales)
) {
const { initialRevalidateSeconds, initialExpireSeconds } = prerenderData
if (typeof initialRevalidateSeconds !== 'undefined') {
......@@ -53,9 +70,17 @@ export class SharedCacheControls {
}
}
const dynamicPrerenderData = this.prerenderManifest.dynamicRoutes[route]
const dynamicPathname =
owner.kind === RouteKind.PAGES
? normalizeLocalePath(route, this.locales).pathname
: route
const dynamicPrerenderData =
this.prerenderManifest.dynamicRoutes[dynamicPathname]
if (dynamicPrerenderData) {
if (
dynamicPrerenderData &&
isRouteCacheOwner(route, owner, dynamicPrerenderData, this.locales)
) {
const { fallbackRevalidate, fallbackExpire } = dynamicPrerenderData
if (typeof fallbackRevalidate !== 'undefined') {
......@@ -63,6 +88,8 @@ export class SharedCacheControls {
}
}
// A new runtime pathname has no initial lifetime. Its own render supplies
// one instead of borrowing a sibling route's build-time metadata.
return undefined
}
......
import type { CacheFs } from '../../shared/lib/utils'
import fs from 'fs'
import { randomUUID } from 'node:crypto'
export const nodeFs: CacheFs = {
existsSync: fs.existsSync,
readFile: fs.promises.readFile,
readFileSync: fs.readFileSync,
writeFile: (f, d) => fs.promises.writeFile(f, d),
writeFileAtomic: async (f, d) => {
const temporary = `${f}.${randomUUID()}.tmp`
try {
await fs.promises.writeFile(temporary, d)
await fs.promises.link(temporary, f)
return true
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
throw error
} finally {
await fs.promises.unlink(temporary).catch(() => {})
}
},
mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }),
stat: (f) => fs.promises.stat(f),
}
import type { RouteDefinition } from '../route-definitions/route-definition'
import type {
DynamicPrerenderManifestRoute,
PrerenderManifestRoute,
} from '../../build'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { InvariantError } from '../../shared/lib/invariant-error'
import { AppPathnameNormalizer } from '../normalizers/built/app/app-pathname-normalizer'
import { RouteKind } from '../route-kind'
export const ROUTE_CACHE_DIRECTORY = 'route-cache'
export type ResponseCacheOwner = {
readonly kind: RouteKind
/** Canonical Pages pathname or full App module name, including groups and slots. */
readonly sourceRoute: string
}
const appPathnameNormalizer = new AppPathnameNormalizer()
/** Convert a runtime route definition to the identity used by response caches. */
export function getResponseCacheOwner(
definition: Pick<RouteDefinition, 'kind' | 'page' | 'pathname'>
): ResponseCacheOwner {
return {
kind: definition.kind,
// Pages module names can include a trailing /index in Turbopack. Their
// pathname matches the manifest's source in both bundlers. App modules
// retain groups and parallel slots in their cache identity.
sourceRoute:
definition.kind === RouteKind.PAGES
? definition.pathname
: definition.page,
}
}
/**
* Prerender metadata already identifies its source route. Compare that source
* with the selected module before using its metadata, including negative
* entries and partially specialized fallback shells. Cache storage continues
* to use the full module identity, including groups and parallel slots.
*/
export function isRouteCacheOwner(
pathname: string,
owner: ResponseCacheOwner,
prerender:
| Pick<PrerenderManifestRoute, 'srcRoute' | 'dataRoute'>
| Pick<DynamicPrerenderManifestRoute, 'fallbackSourceRoute' | 'dataRoute'>
| undefined,
locales?: readonly string[]
): boolean {
if (!prerender) {
return false
}
// Pages have JSON data routes, App Pages have RSC data routes, and App
// Route Handlers have no separate data route.
const kind =
prerender.dataRoute === null
? RouteKind.APP_ROUTE
: prerender.dataRoute.endsWith('.json')
? RouteKind.PAGES
: prerender.dataRoute.endsWith('.rsc')
? RouteKind.APP_PAGE
: undefined
if (kind !== owner.kind) {
return false
}
const source =
'srcRoute' in prerender ? prerender.srcRoute : prerender.fallbackSourceRoute
const prerenderOwner =
source ??
(kind === RouteKind.PAGES
? normalizeLocalePath(pathname, locales).pathname
: pathname)
return (
prerenderOwner ===
(kind === RouteKind.PAGES
? owner.sourceRoute
: appPathnameNormalizer.normalize(owner.sourceRoute))
)
}
/**
* Response keys are opaque to cache handlers. Hash the source route into one
* fixed-length directory, preserving App groups and slots without expanding
* Unicode names or repeating the source directory hierarchy on disk. The
* pathname stays readable and is normalized exactly once before namespacing.
*/
export function getRouteCacheKey(
pathname: string,
owner: ResponseCacheOwner
): string {
if (!owner) {
throw new InvariantError('Response cache requires a source route')
}
const { sourceRoute } = owner
let source: string
if (process.env.NEXT_RUNTIME === 'edge') {
const sha256 =
require('next/dist/compiled/hash.js/sha256') as typeof import('next/dist/compiled/hash.js/sha256')
source = sha256()
.update(new TextEncoder().encode(sourceRoute))
.digest('hex')
} else {
const { createHash } = require('crypto') as typeof import('crypto')
source = createHash('sha256').update(sourceRoute).digest('hex')
}
return `/${ROUTE_CACHE_DIRECTORY}/${owner.kind}/${source}/$${normalizePagePath(pathname)}`
}
......@@ -78,7 +78,10 @@ import ResponseCache, {
type IncrementalResponseCacheEntry,
} from './response-cache'
import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import {
normalizeAppPath,
selectAppPageEntry,
} from '../shared/lib/router/utils/app-paths'
import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
......@@ -289,7 +292,10 @@ export default class NextNodeServer extends BaseServer<
: this.nextConfig.deploymentId || ''
if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode)
this.imageResponseCache = new ResponseCache({
minimalMode: this.minimalMode,
route: 'image',
})
}
const { appDocumentPreloading } = this.nextConfig.experimental
......@@ -528,14 +534,11 @@ export default class NextNodeServer extends BaseServer<
flushToDisk:
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(),
locales: this.nextConfig.i18n?.locales,
CurCacheHandler: CacheHandler,
})
}
protected getResponseCache() {
return new ResponseCache(this.minimalMode)
}
protected getPublicDir(): string {
return join(this.dir, CLIENT_PUBLIC_FILES_PATH)
}
......@@ -825,8 +828,8 @@ export default class NextNodeServer extends BaseServer<
let page = ctx.pathname
if (isAppPath) {
// When it's an array, we need to pass all parallel routes to the loader.
page = appPaths[0]
// Match the build owner while passing all parallel paths to the loader.
page = selectAppPageEntry(ctx.pathname, appPaths)
}
for (const edgeFunctionsPage of edgeFunctionsPages) {
......
import ResponseCache from './index'
import {
CachedRouteKind,
IncrementalCacheKind,
type ResponseCacheEntry,
} from './types'
import { RouteKind } from '../route-kind'
import RenderResult from '../render-result'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
import { fromResponseCacheEntry } from './utils'
function mockIncrementalCache() {
return {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
}
}
function makeCacheEntry(html: string): ResponseCacheEntry {
return {
value: {
kind: CachedRouteKind.APP_PAGE,
html: RenderResult.fromStatic(html, HTML_CONTENT_TYPE_HEADER),
rscData: Buffer.from('rsc-payload'),
postponed: undefined,
status: 200,
headers: undefined,
segmentData: undefined,
},
cacheControl: { revalidate: 60, expire: undefined },
}
}
describe('ResponseCache', () => {
const route = { kind: RouteKind.APP_PAGE, sourceRoute: '/test/page' }
it('rejects missing ownership even in minimal mode', () => {
expect(() => {
// @ts-expect-error response caches must explicitly select their owner
new ResponseCache({ minimalMode: true })
}).toThrow('Response cache requires a source route')
})
it('passes the source route to both reads and regeneration writes', async () => {
const cache = new ResponseCache({ minimalMode: false, route })
const incrementalCache = mockIncrementalCache()
await cache.get('/test', async () => makeCacheEntry('generated'), {
routeKind: RouteKind.APP_PAGE,
incrementalCache,
})
expect(incrementalCache.get).toHaveBeenCalledWith('/test', {
kind: IncrementalCacheKind.APP_PAGE,
route,
isFallback: false,
isRoutePPREnabled: false,
})
expect(incrementalCache.set).toHaveBeenCalledWith(
'/test',
expect.any(Object),
expect.objectContaining({ route })
)
})
it('uses an explicit image context without a source route', async () => {
const cache = new ResponseCache({ minimalMode: false, route: 'image' })
const incrementalCache = mockIncrementalCache()
await cache.get(
'image-key',
async () => ({
value: {
kind: CachedRouteKind.IMAGE,
buffer: Buffer.from('image'),
etag: 'etag',
upstreamEtag: 'upstream-etag',
extension: 'png',
},
cacheControl: { revalidate: 60, expire: undefined },
}),
{
routeKind: RouteKind.IMAGE,
incrementalCache,
}
)
expect(incrementalCache.get).toHaveBeenCalledWith('image-key', {
kind: IncrementalCacheKind.IMAGE,
isFallback: false,
})
expect(incrementalCache.set).toHaveBeenCalledWith(
'image-key',
expect.objectContaining({ kind: CachedRouteKind.IMAGE }),
{
kind: IncrementalCacheKind.IMAGE,
isFallback: false,
cacheControl: { revalidate: 60, expire: undefined },
}
)
})
it('keeps ownership when extending a previous entry after regeneration fails', async () => {
const cache = new ResponseCache({ minimalMode: false, route })
const incrementalCache = mockIncrementalCache()
const previous = await fromResponseCacheEntry(makeCacheEntry('cached'))
incrementalCache.get.mockResolvedValue(previous)
await expect(
cache.get(
'/test',
async () => {
throw new Error('regeneration failed')
},
{
routeKind: RouteKind.APP_PAGE,
incrementalCache,
isOnDemandRevalidate: true,
}
)
).rejects.toThrow('regeneration failed')
expect(incrementalCache.set).toHaveBeenCalledWith(
'/test',
previous.value,
expect.objectContaining({
route,
cacheControl: { revalidate: 30, expire: undefined },
})
)
})
})
import type { RouteKind } from '../route-kind'
import type { ResponseCacheOwner } from '../lib/route-cache-key'
import type {
ResponseCacheEntry,
ResponseGenerator,
ResponseCacheBase,
IncrementalResponseCacheEntry,
IncrementalResponseCache,
GetIncrementalResponseCacheContext,
GetIncrementalImageCacheContext,
} from './types'
import { IncrementalCacheKind } from './types'
import { InvariantError } from '../../shared/lib/invariant-error'
import { Batcher } from '../../lib/batcher'
import { LRUCache } from '../lib/lru-cache'
......@@ -15,7 +21,6 @@ import {
routeKindToIncrementalCacheKind,
toResponseCacheEntry,
} from './utils'
import type { RouteKind } from '../route-kind'
/**
* Parses an environment variable as a positive integer, returning the fallback
......@@ -159,12 +164,24 @@ export default class ResponseCache implements ResponseCacheBase {
// be dynamic here
private minimal_mode?: boolean
constructor(
minimal_mode: boolean,
maxSize: number = DEFAULT_MAX_SIZE,
ttl: number = DEFAULT_TTL_MS
) {
this.minimal_mode = minimal_mode
private readonly route: ResponseCacheOwner | 'image'
constructor({
minimalMode,
route,
maxSize = DEFAULT_MAX_SIZE,
ttl = DEFAULT_TTL_MS,
}: {
minimalMode: boolean
route: ResponseCacheOwner | 'image'
maxSize?: number
ttl?: number
}) {
if (!route) {
throw new InvariantError('Response cache requires a source route')
}
this.route = route
this.minimal_mode = minimalMode
this.maxSize = maxSize
this.ttl = ttl
......@@ -258,7 +275,6 @@ export default class ResponseCache implements ResponseCacheBase {
isRoutePPREnabled = false,
isPrefetch = false,
waitUntil,
routeKind,
invocationID,
} = context
......@@ -274,7 +290,6 @@ export default class ResponseCache implements ResponseCacheBase {
isFallback,
isRoutePPREnabled,
isPrefetch,
routeKind,
invocationID,
},
resolve
......@@ -310,7 +325,6 @@ export default class ResponseCache implements ResponseCacheBase {
isFallback: boolean
isRoutePPREnabled: boolean
isPrefetch: boolean
routeKind: RouteKind
invocationID: string | undefined
},
resolve: (value: IncrementalResponseCacheEntry | null) => void
......@@ -322,11 +336,10 @@ export default class ResponseCache implements ResponseCacheBase {
try {
// Get the previous cache entry if not in minimal mode
previousIncrementalCacheEntry = !this.minimal_mode
? await context.incrementalCache.get(key, {
kind: routeKindToIncrementalCacheKind(context.routeKind),
isRoutePPREnabled: context.isRoutePPREnabled,
isFallback: context.isFallback,
})
? await context.incrementalCache.get(
key,
this.getCacheContext(context.isRoutePPREnabled, context.isFallback)
)
: null
if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate) {
......@@ -466,8 +479,7 @@ export default class ResponseCache implements ResponseCacheBase {
} else {
await incrementalCache.set(key, incrementalResponseCacheEntry.value, {
cacheControl: incrementalResponseCacheEntry.cacheControl,
isRoutePPREnabled,
isFallback,
...this.getCacheContext(isRoutePPREnabled, isFallback),
})
}
}
......@@ -493,9 +505,8 @@ export default class ResponseCache implements ResponseCacheBase {
)
await incrementalCache.set(key, previousIncrementalCacheEntry.value, {
...this.getCacheContext(isRoutePPREnabled, isFallback),
cacheControl: { revalidate: revalidate, expire: expire },
isRoutePPREnabled,
isFallback,
})
}
......@@ -503,4 +514,18 @@ export default class ResponseCache implements ResponseCacheBase {
throw err
}
}
private getCacheContext(
isRoutePPREnabled: boolean,
isFallback: boolean
): GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext {
if (this.route === 'image') {
return { kind: IncrementalCacheKind.IMAGE, isFallback: false }
}
const kind = routeKindToIncrementalCacheKind(this.route.kind)
if (kind === IncrementalCacheKind.IMAGE) {
throw new InvariantError('Images must use the image response cache')
}
return { route: this.route, kind, isRoutePPREnabled, isFallback }
}
}
import type { ResponseCacheOwner } from '../lib/route-cache-key'
import type { OutgoingHttpHeaders } from 'http'
import type RenderResult from '../render-result'
import type { CacheControl, Revalidate } from '../lib/cache-control'
......@@ -207,8 +208,11 @@ export interface GetIncrementalFetchCacheContext {
softTags?: string[]
}
export interface GetIncrementalResponseCacheContext {
kind: Exclude<IncrementalCacheKind, IncrementalCacheKind.FETCH>
export interface GetIncrementalResponseCacheHandlerContext {
kind: Exclude<
IncrementalCacheKind,
IncrementalCacheKind.FETCH | IncrementalCacheKind.IMAGE
>
/**
* True if the route is enabled for PPR.
......@@ -221,6 +225,12 @@ export interface GetIncrementalResponseCacheContext {
isFallback: boolean
}
export interface GetIncrementalResponseCacheContext
extends GetIncrementalResponseCacheHandlerContext {
/** Internal ownership used before invoking the storage handler. */
route: ResponseCacheOwner
}
export interface SetIncrementalFetchCacheContext {
fetchCache: true
fetchUrl?: string
......@@ -229,7 +239,7 @@ export interface SetIncrementalFetchCacheContext {
isImplicitBuildTimeCache?: boolean
}
export interface SetIncrementalResponseCacheContext {
export interface SetIncrementalResponseCacheHandlerContext {
fetchCache?: false
cacheControl?: CacheControl
......@@ -244,15 +254,35 @@ export interface SetIncrementalResponseCacheContext {
isFallback?: boolean
}
export interface SetIncrementalResponseCacheContext
extends SetIncrementalResponseCacheHandlerContext {
/** Internal ownership used before invoking the storage handler. */
route: ResponseCacheOwner
}
export interface GetIncrementalImageCacheContext {
kind: IncrementalCacheKind.IMAGE
route?: never
isFallback: false
isRoutePPREnabled?: false
}
export interface SetIncrementalImageCacheContext {
kind: IncrementalCacheKind.IMAGE
route?: never
fetchCache?: false
cacheControl?: CacheControl
}
export interface IncrementalResponseCache {
get(
cacheKey: string,
ctx: GetIncrementalResponseCacheContext
ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext
): Promise<IncrementalResponseCacheEntry | null>
set(
key: string,
data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,
ctx: SetIncrementalResponseCacheContext
ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext
): Promise<void>
}
......@@ -263,7 +293,7 @@ export interface IncrementalCache extends IncrementalResponseCache {
): Promise<IncrementalFetchCacheEntry | null>
get(
cacheKey: string,
ctx: GetIncrementalResponseCacheContext
ctx: GetIncrementalResponseCacheContext | GetIncrementalImageCacheContext
): Promise<IncrementalResponseCacheEntry | null>
set(
key: string,
......@@ -273,6 +303,6 @@ export interface IncrementalCache extends IncrementalResponseCache {
set(
key: string,
data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,
ctx: SetIncrementalResponseCacheContext
ctx: SetIncrementalResponseCacheContext | SetIncrementalImageCacheContext
): Promise<void>
}
......@@ -11,6 +11,28 @@ describe('AppPageRouteMatcherProvider', () => {
await expect(matcher.matchers()).resolves.toEqual([])
})
it.each([false, true])(
'selects the build owner regardless of manifest insertion order (%s)',
async (reverse) => {
const entries = [
['/stories/@slot/[slug]/page', 'app/stories/@slot/[slug]/page.js'],
['/stories/[slug]/page', 'app/stories/[slug]/page.js'],
]
if (reverse) entries.reverse()
const loader: ManifestLoader = {
load: jest.fn(() => Object.fromEntries(entries)),
}
const provider = new AppPageRouteMatcherProvider('<root>', loader)
const matchers = await provider.matchers()
expect(matchers).toHaveLength(1)
expect(matchers[0].definition).toMatchObject({
page: '/stories/[slug]/page',
filename: `<root>/${SERVER_DIRECTORY}/app/stories/[slug]/page.js`,
appPaths: entries.map(([page]) => page),
})
}
)
describe('manifest matching', () => {
it.each<{
manifest: Record<string, string>
......
import { selectAppPageEntry } from '../../shared/lib/router/utils/app-paths'
import { isAppPageRoute } from '../../lib/is-app-page-route'
import { APP_PATHS_MANIFEST } from '../../shared/lib/constants'
......@@ -37,8 +38,7 @@ export class AppPageRouteMatcherProvider extends ManifestRouteMatcherProvider<Ap
// Format the routes.
const matchers: Array<AppPageRouteMatcher> = []
for (const [pathname, appPaths] of Object.entries(allAppPaths)) {
// TODO-APP: (wyattjoh) this is a hack right now, should be more deterministic
const page = appPaths[0]
const page = selectAppPageEntry(pathname, appPaths)
const filename = this.normalizers.filename.normalize(manifest[page])
const bundlePath = this.normalizers.bundlePath.normalize(page)
......
......@@ -36,6 +36,7 @@ import { RedirectStatusCode } from '../../../client/components/redirect-status-c
import { isBot } from '../../../shared/lib/router/utils/is-bot'
import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix'
import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'
import { isRouteCacheOwner } from '../../lib/route-cache-key'
import type { PagesRouteModule } from './module.compiled'
import type {
GetServerSideProps,
......@@ -159,8 +160,18 @@ export const getHandler = ({
: resolvedPathname
)
const isPrerendered =
Boolean(prerenderManifest.routes[decodedPathname]) ||
prerenderManifest.notFoundRoutes.includes(decodedPathname)
(Boolean(prerenderManifest.routes[decodedPathname]) ||
prerenderManifest.notFoundRoutes.includes(decodedPathname)) &&
// A sibling's positive or negative prerender cannot admit parameters
// that this route excluded. Development computes static paths on demand
// instead of reading build-time prerender metadata.
(routeModule.isDev ||
isRouteCacheOwner(
decodedPathname,
routeModule.cacheOwner,
prerenderManifest.routes[decodedPathname],
nextConfig.i18n?.locales
))
const prerenderInfo = prerenderManifest.dynamicRoutes[srcPage]
......
......@@ -49,6 +49,10 @@ import { IncrementalCache } from '../lib/incremental-cache'
import { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'
import { interopDefault } from '../app-render/interop-default'
import type { RouteKind } from '../route-kind'
import {
getResponseCacheOwner,
type ResponseCacheOwner,
} from '../lib/route-cache-key'
import type { BaseNextRequest } from '../base-http'
import type { I18NConfig, NextConfigComplete } from '../config-shared'
import ResponseCache, { type ResponseGenerator } from '../response-cache'
......@@ -113,6 +117,9 @@ export abstract class RouteModule<
*/
public readonly definition: Readonly<D>
/** The canonical source identity shared by cache reads, writes, and metadata. */
public readonly cacheOwner: ResponseCacheOwner
/**
* The shared modules that are exposed and required for the route module.
*/
......@@ -133,6 +140,7 @@ export abstract class RouteModule<
}: RouteModuleOptions<D, U>) {
this.userland = userland
this.definition = definition
this.cacheOwner = getResponseCacheOwner(definition)
this.isDev = process.env.NODE_ENV === 'development'
this.distDir = distDir
this.relativeProjectDir = relativeProjectDir
......@@ -456,6 +464,7 @@ export abstract class RouteModule<
flushToDisk: nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => prerenderManifest,
CurCacheHandler: CacheHandler,
locales: nextConfig.i18n?.locales,
})
}
}
......@@ -848,7 +857,10 @@ export abstract class RouteModule<
public getResponseCache(req: IncomingMessage | BaseNextRequest) {
if (!this.responseCache) {
const minimalMode = getRequestMeta(req, 'minimalMode') ?? false
this.responseCache = new ResponseCache(minimalMode)
this.responseCache = new ResponseCache({
minimalMode,
route: this.cacheOwner,
})
}
return this.responseCache
}
......
......@@ -51,6 +51,24 @@ export function normalizeAppPath(route: string) {
)
}
/** Select the last direct entry, matching Next 15's sorted appPaths at runtime. */
export function selectAppPageEntry(
pathname: string,
appPaths: readonly string[],
normalizePathname: (appPath: string) => string = (appPath) =>
normalizeAppPath(appPath).replace(/%5F/g, '_')
): string {
let entry: string | undefined
for (const appPath of appPaths) {
if (normalizePathname(appPath) !== pathname) continue
if (entry === undefined || entry < appPath) entry = appPath
}
if (entry === undefined) {
throw new Error(`Invariant: no direct app page entry found for ${pathname}`)
}
return entry
}
/**
* Strips the `.rsc` extension if it's in the pathname.
* Since this function is used on full urls it checks `?` for searchParams handling.
......
......@@ -452,6 +452,8 @@ export interface CacheFs {
readFile: typeof fs.promises.readFile
readFileSync: typeof fs.readFileSync
writeFile(f: string, d: any): Promise<void>
/** Publish a complete file without replacing an existing destination. */
writeFileAtomic?(f: string, d: any): Promise<boolean>
mkdir(dir: string): Promise<void | string>
stat(f: string): Promise<{ mtime: Date }>
}
......
......@@ -1997,7 +1997,29 @@ export async function ncc_string_hash(task, opts) {
.ncc({ packageName: 'string-hash', externals })
.target('src/compiled/string-hash')
}
// eslint-disable-next-line camelcase
// Bundle only SHA-256, using browser entrypoints so this is safe in Edge.
export async function ncc_hash_sha256(task, opts) {
await task
.source(relative(__dirname, require.resolve('hash.js/lib/hash/sha/256')))
.ncc({
packageName: 'hash.js',
bundleName: 'hash.js/sha256',
externals,
mainFields: ['browser', 'main'],
})
.target('src/compiled/hash.js/sha256')
// hash.js publishes its license in the README rather than a LICENSE file.
const readme = await fs.readFile(require.resolve('hash.js/README.md'), 'utf8')
const license = readme.split('#### LICENSE\n')[1]
if (!license) {
throw new Error('Missing hash.js license')
}
await fs.writeFile(
join(__dirname, 'src/compiled/hash.js/sha256/LICENSE'),
`${license.trim()}\n`
)
}
externals['strip-ansi'] = 'next/dist/compiled/strip-ansi'
externals['next/dist/compiled/strip-ansi'] = 'next/dist/compiled/strip-ansi'
export async function ncc_strip_ansi(task, opts) {
......@@ -2404,6 +2426,7 @@ export async function ncc(task, opts) {
'ncc_source_map',
'ncc_source_map08',
'ncc_string_hash',
'ncc_hash_sha256',
'ncc_strip_ansi',
'ncc_superstruct',
'ncc_zod',
......
......@@ -684,6 +684,10 @@ declare module 'next/dist/compiled/string-hash' {
import m from 'string-hash'
export = m
}
declare module 'next/dist/compiled/hash.js/sha256' {
import { sha256 } from 'hash.js'
export = sha256
}
declare module 'next/dist/compiled/ua-parser-js' {
import m from 'ua-parser-js'
export = m
......
......@@ -1360,6 +1360,9 @@ importers:
gzip-size:
specifier: 5.1.1
version: 5.1.1
hash.js:
specifier: 1.1.7
version: 1.1.7
http-proxy:
specifier: 1.18.1
version: 1.18.1(patch_hash=kzqzmw2zuo23hy3avffm6aqice)
......@@ -176,6 +176,7 @@ async function main() {
env: {
...process.env,
NEXT_TEST_MODE: testMode,
NEXT_TEST_PREVIEW_BUILDS_BASE_URL: previewBuildsBaseUrl,
NEXT_TEST_VERSION: nextTestVersion,
NEXT_EXTERNAL_TESTS_FILTERS:
testMode === 'deploy' ? 'test/deploy-tests-manifest.json' : undefined,
......
import { RouteKind } from 'next/dist/server/route-kind'
import { nextTestSetup } from 'e2e-utils'
import { check, waitFor, retry } from 'next-test-utils'
import { Readable } from 'stream'
......@@ -69,10 +70,26 @@ describe('app-custom-routes', () => {
if (isNextStart) {
await check(async () => {
expect(
await next.readFile(`.next/server/app/${path}.body`)
await next.readFile(
next.getPrerenderFilePath(path, '.body', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy()
expect(
await next.readFile(`.next/server/app/${path}.meta`)
await next.readFile(
next.getPrerenderFilePath(path, '.meta', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy()
return 'success'
}, 'success')
......@@ -98,10 +115,26 @@ describe('app-custom-routes', () => {
if (isNextStart) {
await check(async () => {
expect(
await next.readFile(`.next/server/app/${path}.body`)
await next.readFile(
next.getPrerenderFilePath(path, '.body', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy()
expect(
await next.readFile(`.next/server/app/${path}.meta`)
await next.readFile(
next.getPrerenderFilePath(path, '.meta', {
router: 'app',
route: {
kind: RouteKind.APP_ROUTE,
sourceRoute: `/${path.split('/')[1]}/[slug]/data.json/route`,
},
})
)
).toBeTruthy()
return 'success'
}, 'success')
......
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('catchall-parallel-routes-group', () => {
const { next } = nextTestSetup({
const { next, isNextStart, isTurbopack } = nextTestSetup({
files: __dirname,
})
if (isNextStart && !isTurbopack) {
it('traces the canonical page and its dependencies from the slot entry', async () => {
const routeDir = path.join(next.testDir, '.next/server/app/[...catchAll]')
const slotDir = path.join(routeDir, '@slot/(group)')
const rootTrace = await next.readJSON(
'.next/server/app/[...catchAll]/page.js.nft.json'
)
const slotTrace = await next.readJSON(
'.next/server/app/[...catchAll]/@slot/(group)/page.js.nft.json'
)
const slotFiles = new Set<string>(
slotTrace.files.map((file: string) => path.resolve(slotDir, file))
)
const requiredFiles = [
path.join(routeDir, 'page.js'),
...rootTrace.files.map((file: string) => path.resolve(routeDir, file)),
]
expect(requiredFiles.filter((file) => !slotFiles.has(file))).toEqual([])
})
}
it('should work without throwing any errors about invalid pages', async () => {
const browser = await next.browser('/')
......
......@@ -22,10 +22,21 @@ describe('ppr-navigations incremental', () => {
})
it('can navigate between all the links and back without writing to disk', async () => {
const before =
!isNextDev && !isTurbopack && !isNextDeploy
? await getDotNextFiles(next)
: []
const checkDisk = !isNextDev && !isTurbopack && !isNextDeploy
if (checkDisk) {
// Promote every route's existing build seed before measuring navigation.
for (const { href } of links) {
if (href === '/') continue
expect((await next.fetch(href)).status).toBe(200)
expect(
(
await next.fetch(href, {
headers: { RSC: '1', 'Next-Router-Prefetch': '1' },
})
).status
).toBe(200)
}
}
const browser = await next.browser('/')
......@@ -33,6 +44,8 @@ describe('ppr-navigations incremental', () => {
await waitForHydration(browser)
await setTimeout(500)
const before = checkDisk ? await getDotNextFiles(next) : []
// Add a variable to the window so we can tell if it MPA navigated. If this
// value is still true at the end of the test, then we know that the page
// didn't MPA navigate.
......@@ -65,7 +78,7 @@ describe('ppr-navigations incremental', () => {
await browser.close()
}
if (!isNextDev && !isTurbopack && !isNextDeploy) {
if (checkDisk) {
const after = await getDotNextFiles(next)
// Ensure that no new files were written to disk. If this test fails, it's
......
......@@ -18,6 +18,7 @@ import {
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import stripAnsi from 'strip-ansi'
import { RouteKind } from 'next/dist/server/route-kind'
const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
......@@ -57,28 +58,28 @@ describe('Prerender', () => {
afterAll(() => next.destroy())
async function waitForCacheWrite(
prerenderPath = '',
prerenderPath: string,
sourceRoute: string,
timeBeforeRevalidateMilliseconds,
retries = 30
) {
for (let i = 0; i < retries; i++) {
const lastRetry = i === retries - 1
const jsonPath = join(
const htmlPath = join(
next.testDir,
'.next',
'server',
'pages',
`${prerenderPath}.html`
next.getPrerenderFilePath(prerenderPath, '.html', {
route: { kind: RouteKind.PAGES, sourceRoute },
})
)
try {
const jsonStats = await fs.stat(jsonPath)
const jsonLastModified = jsonStats.mtime.getTime()
const htmlStats = await fs.stat(htmlPath)
const htmlLastModified = htmlStats.mtime.getTime()
if (timeBeforeRevalidateMilliseconds <= jsonLastModified) {
if (timeBeforeRevalidateMilliseconds <= htmlLastModified) {
break
}
throw new Error(
`revalidate cache not past ${timeBeforeRevalidateMilliseconds} received time ${jsonLastModified}`
`revalidate cache not past ${timeBeforeRevalidateMilliseconds} received time ${htmlLastModified}`
)
} catch (err) {
if (lastRetry) {
......@@ -383,7 +384,14 @@ describe('Prerender', () => {
await waitFor(2500)
await Promise.all(toBuild.map((pg) => renderViaHTTP(next.url, pg)))
if (isDev) {
// Dev requests can concurrently update the prerender manifest.
for (const pg of toBuild) {
await renderViaHTTP(next.url, pg)
}
} else {
await Promise.all(toBuild.map((pg) => renderViaHTTP(next.url, pg)))
}
const browser = await webdriver(next.url, '/')
let text = await browser.elementByCss('p').text()
......@@ -2445,6 +2453,7 @@ describe('Prerender', () => {
)
await waitForCacheWrite(
'/blocking-fallback/test-if-generated-2',
'/blocking-fallback/[slug]',
beforeRevalidate
)
const html = await res.text()
......
/* eslint-env jest */
import fs from 'fs-extra'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
......@@ -114,14 +116,26 @@ function runTests(isDev) {
await check(
() =>
fs
.exists(join(pagesDir, mode, path + '.html'))
.exists(
join(
appDir,
'.next/server',
`${getRouteCacheKey(`/${mode}/${path}`, { kind: RouteKind.PAGES, sourceRoute: `/${mode}/[slug]` })}.html`
)
)
.then((res) => (res ? 'yes' : 'no')),
'yes'
)
await check(
() =>
fs
.exists(join(pagesDir, mode, path + '.json'))
.exists(
join(
appDir,
'.next/server',
`${getRouteCacheKey(`/${mode}/${path}`, { kind: RouteKind.PAGES, sourceRoute: `/${mode}/[slug]` })}.json`
)
)
.then((res) => (res ? 'yes' : 'no')),
'yes'
)
......
/* eslint-env jest */
import fs from 'fs-extra'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import {
findPort,
killApp,
nextBuild,
nextStart,
renderViaHTTP,
retry,
waitFor,
getPageFileFromPagesManifest,
fetchViaHTTP,
} from 'next-test-utils'
import { join } from 'path'
......@@ -18,15 +20,43 @@ let app
let appPort
let buildId
function getScopedFile(routePath, extension) {
const cacheKey = getRouteCacheKey(routePath, {
kind: RouteKind.PAGES,
sourceRoute: routePath,
})
return join(appDir, '.next', 'server', `${cacheKey}${extension}`)
}
async function settleScopedResponse(fileName, requestPath, isJson = false) {
const warmStartedAt = Date.now()
await renderViaHTTP(appPort, requestPath)
return retry(
async () => {
const response = await renderViaHTTP(appPort, requestPath)
const file = await fs.readFile(fileName, 'utf8')
const { mtimeMs } = await fs.stat(fileName)
// A promoted build seed keeps its original age. Wait for any stale seed
// regeneration to finish before using the scoped file as the baseline.
expect(mtimeMs).toBeGreaterThanOrEqual(warmStartedAt)
expect(file).not.toBe('')
if (isJson) {
expect(JSON.parse(response)).toEqual(JSON.parse(file))
} else {
expect(response).toBe(file)
}
return file
},
15000,
500
)
}
function runTests(route, routePath) {
it(`[${route}] should regenerate page when revalidate time exceeded`, async () => {
const fileName = join(
appDir,
'.next',
'server',
getPageFileFromPagesManifest(appDir, routePath).replace('.js', '.html')
)
const initialHtmlFile = await fs.readFile(fileName, 'utf8')
const fileName = getScopedFile(routePath, '.html')
const initialHtmlFile = await settleScopedResponse(fileName, route)
await waitFor(1000) // Wait revalidate duration
......@@ -40,14 +70,9 @@ function runTests(route, routePath) {
})
it(`[${route}] should regenerate /_next/data when revalidate time exceeded`, async () => {
const fileName = join(
appDir,
'.next',
'server',
getPageFileFromPagesManifest(appDir, routePath).replace('.js', '.json')
)
const fileName = getScopedFile(routePath, '.json')
const route = join(`/_next/data/${buildId}`, `${routePath}.json`)
const initialFileJson = await fs.readFile(fileName, 'utf8')
const initialFileJson = await settleScopedResponse(fileName, route, true)
await waitFor(1000) // Wait revalidate duration
......
/* eslint-env jest */
import cheerio from 'cheerio'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import cookie from 'cookie'
import fs from 'fs-extra'
import { join } from 'path'
......@@ -239,7 +241,13 @@ function runTests(isDev) {
})
if (!isDev) {
const fsHtml = await fs.readFile(getCacheFile('fallback/second.html'))
const fsHtml = await fs.readFile(
join(
appDir,
'.next/server',
`${getRouteCacheKey('/fallback/second', { kind: RouteKind.PAGES, sourceRoute: '/fallback/[post]' })}.html`
)
)
const fsProps = JSON.parse(cheerio.load(fsHtml)('#props').text())
expect(fsProps).toEqual({
......
......@@ -7,6 +7,11 @@ import { FileRef, isNextDeploy } from '../e2e-utils'
import { ChildProcess } from 'child_process'
import { createNextInstall } from '../create-next-install'
import { Span } from 'next/dist/trace'
import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path'
import {
getRouteCacheKey,
type ResponseCacheOwner,
} from 'next/dist/server/lib/route-cache-key'
import webdriver from '../next-webdriver'
import { renderViaHTTP, fetchViaHTTP, findPort } from 'next-test-utils'
import cheerio from 'cheerio'
......@@ -559,6 +564,31 @@ export class NextInstance {
return existsSync(path.join(this.testDir, filename))
}
/** Resolve a response artifact without assuming the cache key is its URL. */
public getPrerenderFilePath(
pathname: string,
extension: string,
{
router = 'app',
distDir = '.next',
route,
}: {
router?: 'app' | 'pages'
distDir?: string
/** Supply the source for an entry generated only at runtime. */
route?: ResponseCacheOwner
} = {}
): string {
pathname = `/${pathname.replace(/^\/+/, '')}`
const cacheKey = route ? getRouteCacheKey(pathname, route) : undefined
const filename = normalizePagePath(pathname)
return path.join(
distDir,
'server',
`${cacheKey ?? `/${router}${filename}`}${extension}`
)
}
public async readFile(filename: string) {
return fs.readFile(path.join(this.testDir, filename), 'utf8')
}
......
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
import { RouteKind } from 'next/dist/server/route-kind'
describe('adapter config with i18n response artifacts', () => {
const { next } = nextTestSetup({ files: __dirname })
it.each(['en', 'fr'])(
'resolves %s prerenders and fallback shells to scoped files',
async (locale) => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
for (const [suffix, sourceRoute] of [
['fallback/first', '/fallback/[slug]'],
['fallback/[slug]', '/fallback/[slug]'],
]) {
const pathname = `/${locale}/${suffix}`
const output = outputs.find((item) => item.pathname === pathname)
const artifact = next.getPrerenderFilePath(pathname, '.html', {
router: 'pages',
route: { kind: RouteKind.PAGES, sourceRoute },
})
// Next 15 has no localized fallback outputs in its flat adapter schema.
// Assert the emitted positive route and both localized build shell files.
if (!suffix.includes('[slug]')) {
expect(output?.fallback?.filePath).toBe(
path.join(next.testDir, artifact)
)
}
expect(await next.hasFile(artifact)).toBe(true)
expect(await next.hasFile(artifact.replace(/\.html$/, '.meta'))).toBe(
true
)
if (!suffix.includes('[slug]'))
expect(await next.hasFile(artifact.replace(/\.html$/, '.json'))).toBe(
true
)
for (const extension of ['.html', '.json', '.meta']) {
expect(
await next.hasFile(`.next/server/pages${pathname}${extension}`)
).toBe(false)
}
}
}
)
})
import fs from 'fs/promises'
// @ts-check
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'i18n-test-adapter',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
export default adapter
import Module from 'module'
const require = Module.createRequire(import.meta.url)
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: { cpus: 2, adapterPath: require.resolve('./my-adapter.mjs') },
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
}
export default nextConfig
export function getStaticPaths() {
return {
paths: ['en', 'fr'].map((locale) => ({
params: { slug: 'first' },
locale,
})),
fallback: true,
}
}
export function getStaticProps({ params, locale }) {
return { props: { slug: params.slug, locale } }
}
export default function Page({ slug, locale }) {
return (
<p>
{locale}: {slug}
</p>
)
}
import fs from 'fs'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
import { AdapterOutputType } from 'next/constants'
import { RouteKind } from 'next/dist/server/route-kind'
describe('adapter-config', () => {
const { next } = nextTestSetup({
......@@ -113,4 +115,78 @@ describe('adapter-config', () => {
headers: expect.toBeArray(),
})
})
it('uses scoped build files for response artifacts', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
for (const [pathname, router, extension, route, sidecar] of [
[
'/grouped',
'app',
'.html',
{ kind: RouteKind.APP_PAGE, sourceRoute: '/(group)/grouped/page' },
'.rsc',
],
[
'/isr-app/first',
'app',
'.html',
{ kind: RouteKind.APP_PAGE, sourceRoute: '/isr-app/[slug]/page' },
'.rsc',
],
[
'/isr-route/first',
'app',
'.body',
{ kind: RouteKind.APP_ROUTE, sourceRoute: '/isr-route/[slug]/route' },
undefined,
],
[
'/isr-pages/first',
'pages',
'.html',
{ kind: RouteKind.PAGES, sourceRoute: '/isr-pages/[slug]' },
'.json',
],
[
'/isr-pages-fallback-true/[slug]',
'pages',
'.html',
{
kind: RouteKind.PAGES,
sourceRoute: '/isr-pages-fallback-true/[slug]',
},
undefined,
],
] as const) {
const output = outputs.find(
(item) =>
item.type === AdapterOutputType.PRERENDER &&
item.pathname === pathname
)
const artifact = next.getPrerenderFilePath(pathname, extension, {
router,
route,
})
expect(output?.fallback?.filePath).toBe(path.join(next.testDir, artifact))
expect(await next.hasFile(artifact)).toBe(true)
expect(
await next.hasFile(`.next/server/${router}${pathname}${extension}`)
).toBe(false)
expect(await next.hasFile(`.next/server/${router}${pathname}.meta`)).toBe(
false
)
expect(
await next.hasFile(artifact.replace(/\.(?:html|body)$/, '.meta'))
).toBe(true)
if (sidecar) {
expect(
await next.hasFile(artifact.replace(/\.(?:html|body)$/, sidecar))
).toBe(true)
expect(
await next.hasFile(`.next/server/${router}${pathname}${sidecar}`)
).toBe(false)
}
}
})
})
export default function Page() {
return <p>grouped prerender</p>
}
import { RouteKind } from 'next/dist/server/route-kind'
import { nextTestSetup } from 'e2e-utils'
describe.each([false, true])(
'route-scoped-cache parallel closed route (adapter %s)',
(adapter) => {
const { next, skipped } = nextTestSetup({
// Inspects local artifacts and the experimental adapter output.
skipDeployment: true,
files: {
'next.config.js': `module.exports = { cacheMaxMemorySize: 0, experimental: { cpus: 2, cacheComponents: false, ppr: false, ${adapter ? "adapterPath: require.resolve('./adapter.mjs')" : ''} } }`,
'adapter.mjs': `import fs from 'fs'; export default { name: 'test', async onBuildComplete(ctx) { await fs.promises.writeFile('outputs.json', JSON.stringify(ctx.outputs)) } }`,
'app/layout.js':
'export default function Layout({children}) { return <html><body>{children}</body></html> }',
'app/stories/layout.js':
'export default function Layout({children, slot}) { return <>{slot}{children}</> }',
'app/stories/[slug]/page.js': `
export const dynamicParams = false
export function generateStaticParams() { return [{slug: 'known'}] }
export default async function Page({params}) { return <main>story:{(await params).slug}</main> }
`,
'app/stories/@slot/[slug]/page.js': `
export const dynamicParams = false
export function generateStaticParams() { return [{slug: 'known'}] }
export default function Page() { return <aside>slot</aside> }
`,
'app/stories/@slot/default.js':
'export default function Page() { return null }',
},
})
if (skipped) return
it('admits the listed closed route with the runtime root owner', async () => {
const meta = await next.readJSON(
next.getPrerenderFilePath('/stories/known', '.meta', {
route: adapter
? { kind: RouteKind.APP_PAGE, sourceRoute: '/stories/[slug]/page' }
: undefined,
})
)
expect(meta.routeCache.owner).toEqual({
kind: 'APP_PAGE',
sourceRoute: '/stories/[slug]/page',
})
if (adapter) {
const outputs = await next.readJSON('outputs.json')
const entries = outputs.filter(
(output) =>
output.pathname === '/stories/[slug]' && output.type === 'APP_PAGE'
)
expect(entries).toHaveLength(1)
expect(entries[0].filePath).toEndWith('/app/stories/[slug]/page.js')
expect(Object.values(entries[0].assets)).toContainEqual(
expect.stringContaining('/app/stories/@slot/[slug]/page.js')
)
}
for (let i = 0; i < 2; i++) {
const response = await next.fetch('/stories/known')
expect(response.status).toBe(200)
expect(await response.text()).toContain('story:')
}
expect((await next.fetch('/stories/unknown')).status).toBe(404)
})
}
)
import { Suspense } from 'react'
import { Content, Dynamic } from '../../lib/state'
export function generateStaticParams() {
return [{ slug: ['warmup'] }]
}
export default function Page({ params }) {
return (
<>
<h1 id="shell">catchall-shell</h1>
<Suspense fallback="loading">
<Content route="ppr-catchall" params={params} />
</Suspense>
<Suspense fallback="dynamic">
<Dynamic />
</Suspense>
</>
)
}
import { revalidatePath, revalidateTag } from 'next/cache'
export async function POST(request) {
const { item } = await request.json()
if (typeof item !== 'string' || !/^[a-z-]+$/.test(item))
return new Response(null, { status: 400 })
revalidateTag(`state:ppr-catalog:${item}`)
revalidatePath(`/catalog/a/${item}`)
return Response.json({ revalidated: true })
}
import { Suspense } from 'react'
import { Content, Dynamic } from '../../../../lib/state'
export function generateStaticParams() {
return [{ item: 'known' }, { item: 'seed-cold' }, { item: 'seed-warm' }]
}
export default function Page({ params }) {
return (
<>
<h1 id="shell">catalog-shell</h1>
<Suspense fallback="loading">
<Content route="ppr-catalog" params={params} />
</Suspense>
<Suspense fallback="dynamic">
<Dynamic />
</Suspense>
</>
)
}
export function generateStaticParams() {
return [{ category: 'a' }, { category: 'b' }]
}
export default function Layout({ children }) {
return children
}
import { sharedData } from '../../lib/state'
export default async function Page() {
return <p id="shared-data">{await sharedData()}</p>
}
import { sharedData } from '../../lib/state'
export default async function Page() {
return <p id="shared-data">{await sharedData()}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>ppr-home</p>
}
import { Suspense } from 'react'
import { Content, Dynamic } from '../../../../lib/state'
export default function Page({ params }) {
return (
<>
<h1 id="shell">shared-shell</h1>
<Suspense fallback="loading">
<Content route="ppr-shared" params={params} />
</Suspense>
<Suspense fallback="dynamic">
<Dynamic />
</Suspense>
</>
)
}
export function generateStaticParams() {
return [{ category: 'a' }, { category: 'b' }]
}
export default function Layout({ children }) {
return children
}
import { randomUUID } from 'node:crypto'
import {
unstable_cacheLife as cacheLife,
unstable_cacheTag as cacheTag,
} from 'next/cache'
import { connection } from 'next/server'
export async function cachedState(route, params) {
'use cache'
cacheLife({
stale: 30,
revalidate: params.item?.startsWith('fast-') ? 1 : 3600,
expire: 7200,
})
cacheTag(`state:${route}:${params.item || 'shell'}`)
return { route, params, generation: randomUUID() }
}
export async function Content({ route, params }) {
return (
<pre id="route-state">
{JSON.stringify(await cachedState(route, await params))}
</pre>
)
}
export async function Dynamic() {
await connection()
return <pre id="dynamic-state">{randomUUID()}</pre>
}
export async function sharedData() {
'use cache'
cacheLife('max')
return randomUUID()
}
module.exports = {
experimental: { cpus: 2, cacheComponents: true, ppr: true },
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { load } from 'cheerio'
import { RouteKind } from 'next/dist/server/route-kind'
describe('route-scoped-cache with PPR', () => {
const { next, isNextDeploy } = nextTestSetup({ files: __dirname })
async function read(pathname: string) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
const $ = load(await response.text())
return {
state: JSON.parse($('#route-state').text()),
shell: $('#shell').text(),
dynamic: $('#dynamic-state').text(),
}
}
async function prefetch(pathname: string) {
const response = await next.fetch(pathname, {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
},
})
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/x-component')
return response.text()
}
it('normal: emits PPR shells and prefetch payloads as historical build seeds', async () => {
const pathname = '/catalog/a/known'
if (isNextDeploy) {
expect((await read(pathname)).shell).toBe('catalog-shell')
expect(await prefetch(pathname)).toContain('catalog-shell')
return
}
expect(
await next.readJSON('.next/prerender-manifest.json')
).not.toHaveProperty('cacheKeys')
const legacyPath = `.next/server/app${pathname}`
const metadata = await next.readJSON(
next.getPrerenderFilePath(pathname, '.meta')
)
// Next 15 stores a full PPR prefetch payload beside the shell.
const extensions = ['.html', '.meta', '.prefetch.rsc']
expect(metadata.postponed).toBeDefined()
for (const filename of [`${legacyPath}.rsc`]) {
await expect(next.readFile(filename)).rejects.toMatchObject({
code: 'ENOENT',
})
}
for (const extension of extensions) {
expect(
await next.hasFile(next.getPrerenderFilePath(pathname, extension))
).toBe(true)
}
expect(metadata.routeCache).toEqual(
expect.objectContaining({
key: expect.stringMatching(/^\/route-cache\//),
owner: expect.objectContaining({ sourceRoute: expect.any(String) }),
isFallback: false,
})
)
expect((await read(pathname)).shell).toBe('catalog-shell')
for (const extension of extensions) {
expect(
await next.hasFile(
next.getPrerenderFilePath(pathname, extension, {
route: {
kind: RouteKind.APP_PAGE,
sourceRoute: '/catalog/[category]/[item]/page',
},
})
)
).toBe(true)
}
})
it.each(['known', 'normal-runtime'])(
'normal: reuses the %s shell and resumes fresh dynamic content',
async (item) => {
const path = `/catalog/a/${item}`
const first = await read(path)
const hit = await read(path)
expect(first.state.route).toBe('ppr-catalog')
expect(first.state.params).toEqual({ category: 'a', item })
expect(hit.state).toEqual(first.state)
expect(first.shell).toBe('catalog-shell')
expect(hit.shell).toBe('catalog-shell')
expect(first.dynamic).not.toBe('')
expect(hit.dynamic).not.toBe(first.dynamic)
}
)
it('normal: keeps parameter variants distinct', async () => {
const a = await read('/catalog/a/params')
const b = await read('/catalog/b/params')
expect(a.state.params).toEqual({ category: 'a', item: 'params' })
expect(b.state.params).toEqual({ category: 'b', item: 'params' })
expect(a.state.generation).not.toBe(b.state.generation)
})
it('normal: serves a partial shell without mixing its dynamic parameters', async () => {
for (const item of ['one', 'two']) {
const result = await read(`/shared/a/${item}`)
expect(result.shell).toBe('shared-shell')
expect(result.state.route).toBe('ppr-shared')
expect(result.state.params).toEqual({ category: 'a', item })
// Next 15's full prefetch payload embeds the selected parameters. It
// cannot be byte-identical across parameter variants like canary's shell.
const payload = await prefetch(`/shared/a/${item}`)
expect(payload).toContain('shared-shell')
expect(payload).toContain(result.state.generation)
expect(payload).toContain(
JSON.stringify(JSON.stringify({ category: 'a', item })).slice(1, -1)
)
}
})
it('normal: preserves HTML, RSC navigation and PPR prefetch', async () => {
const pathname = '/catalog/a/known'
const html = await read(pathname)
const rsc = await next.fetch(pathname, { headers: { RSC: '1' } })
expect(rsc.status).toBe(200)
expect(rsc.headers.get('content-type')).toContain('text/x-component')
// A dynamic navigation can regenerate use-cache data in this process;
// its UUID need not equal the data embedded during the build.
const navigation = await rsc.text()
expect(navigation).toContain('ppr-catalog')
expect(navigation).toContain('known')
expect(navigation).not.toContain('ppr-catchall')
const shell = await prefetch(pathname)
expect(shell).toContain('catalog-shell')
expect(shell).toContain(html.state.generation)
expect(await prefetch(pathname)).toBe(shell)
})
it('normal: refreshes a runtime-created shell after its cache lifetime', async () => {
const first = await read('/catalog/a/fast-runtime')
await retry(async () => {
const current = await read('/catalog/a/fast-runtime')
expect(current.state.route).toBe('ppr-catalog')
expect(current.state.generation).not.toBe(first.state.generation)
}, 45000)
})
it('normal: revalidates cached data and its route shell through public APIs', async () => {
const path = '/catalog/a/on-demand'
const before = await read(path)
await retry(async () => {
expect(await prefetch(path)).toContain(before.state.generation)
})
const result = await next.fetch('/api/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ item: 'on-demand' }),
})
expect(result.status).toBe(200)
await retry(async () => {
const after = await read(path)
expect(after.state.route).toBe('ppr-catalog')
expect(after.state.generation).not.toBe(before.state.generation)
expect(await prefetch(path)).toContain(after.state.generation)
})
})
it('normal: keeps intentionally shared use-cache data shared across routes', async () => {
const a = await next.render$('/data-a')
const b = await next.render$('/data-b')
expect(a('#shared-data').text()).not.toBe('')
expect(b('#shared-data').text()).toBe(a('#shared-data').text())
})
it.each(['cold', 'warm', 'seed-cold', 'seed-warm'])(
'security: isolates a catalog shell from the catch-all (%s)',
async (order) => {
const item = order.startsWith('seed-') ? order : `collision-${order}`
const canonical = `/catalog/a/${item}`
const alias = `/%63atalog/a/${item}`
if (order.endsWith('warm')) {
expect((await read(canonical)).state.route).toBe('ppr-catalog')
}
const encoded = await read(alias)
expect(
isNextDeploy ? ['ppr-catchall', 'ppr-catalog'] : ['ppr-catchall']
).toContain(encoded.state.route)
const ordinary = await read(canonical)
expect(ordinary.state.route).toBe('ppr-catalog')
expect(ordinary.state.params).toEqual({ category: 'a', item })
expect(ordinary.shell).toBe('catalog-shell')
expect((await read(alias)).state.route).toBe(encoded.state.route)
expect((await read(canonical)).state).toEqual(ordinary.state)
// The RSC lookup can bypass the normal response-cache entry point.
expect(await prefetch(canonical)).toContain('catalog-shell')
expect(await prefetch(canonical)).not.toContain('catchall-shell')
expect(await prefetch(alias)).toContain(encoded.shell)
const navigation = await next.fetch(alias, { headers: { RSC: '1' } })
expect(navigation.status).toBe(200)
expect(navigation.headers.get('content-type')).toContain(
'text/x-component'
)
expect(await navigation.text()).toContain(encoded.state.route)
}
)
it('security: keeps a shared partial shell with its source route', async () => {
const alias = await read('/%73hared/a/alias')
expect(
isNextDeploy ? ['ppr-catchall', 'ppr-shared'] : ['ppr-catchall']
).toContain(alias.state.route)
for (const item of ['alias', 'sibling']) {
const result = await read(`/shared/a/${item}`)
expect(result.shell).toBe('shared-shell')
expect(result.state.route).toBe('ppr-shared')
expect(result.state.params).toEqual({ category: 'a', item })
expect(await prefetch(`/shared/a/${item}`)).toContain('shared-shell')
}
})
})
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import { nextTestSetup } from 'e2e-utils'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
retry,
} from 'next-test-utils'
import { load } from 'cheerio'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import type { ChildProcess } from 'node:child_process'
describe('route-scoped-cache standalone', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, '../route-scoped-cache'),
skipStart: true,
// Tests the self-hosted standalone distribution after moving it outside
// the original build tree; a hosted deployment has no such launcher.
skipDeployment: true,
env: { STANDALONE: '1', CACHE_STORAGE: 'disk' },
})
if (skipped) return
let directory: string
let server: ChildProcess
let port: number
function serverAddress() {
return `http://127.0.0.1:${port}`
}
async function start() {
port = await findPort()
server = await initNextServerScript(
path.join(directory, 'server.js'),
/- Local:/,
{
...process.env,
PORT: String(port),
HOSTNAME: '127.0.0.1',
},
undefined,
{ cwd: directory }
)
}
async function read(pathname: string) {
const response = await fetchViaHTTP(serverAddress(), pathname)
expect(response.status).toBe(200)
const body = await response.text()
return response.headers.get('content-type')?.includes('application/json')
? JSON.parse(body)
: JSON.parse(load(body)('#route-state').text())
}
beforeAll(async () => {
const { exitCode } = await next.build()
if (exitCode !== 0) throw new Error(`Fixture build failed: ${exitCode}`)
directory = await fs.mkdtemp(
path.join(os.tmpdir(), 'route-scoped-standalone-')
)
await fs.copy(path.join(next.testDir, '.next/standalone'), directory)
await fs.copy(
path.join(next.testDir, '.next/static'),
path.join(directory, '.next/static')
)
await fs.copy(
path.join(next.testDir, 'public'),
path.join(directory, 'public')
)
await start()
})
afterAll(async () => {
if (server) await killApp(server)
if (directory) await fs.remove(directory)
})
it.each([
['/pages-victim/known', 'pages-victim'],
['/fr/pages-victim/known', 'pages-victim'],
['/app-victim/known', 'app-victim'],
['/api/victim/known', 'route-victim'],
['/source-hash/known', 'app-long-source'],
])(
'normal: includes the prebuilt response for %s',
async (pathname, route) => {
const response = await read(pathname)
expect(response.route).toBe(route)
expect(response.params.id).toBe('known')
expect(await read(pathname)).toEqual(response)
}
)
it('normal: includes static Pages and public files', async () => {
expect(await (await fetchViaHTTP(serverAddress(), '/')).text()).toContain(
'static-home'
)
expect(
await (await fetchViaHTTP(serverAddress(), '/plain.txt')).text()
).toBe('public-file\n')
})
it('normal: writes runtime cache entries that survive restarting the standalone server', async () => {
const before = await read('/pages-victim/runtime')
expect(before.route).toBe('pages-victim')
await killApp(server)
await start()
expect(await read('/pages-victim/runtime')).toEqual(before)
})
it('normal: revalidates using the public pathname in the standalone server', async () => {
const before = await read('/pages-victim/on-demand')
const response = await fetchViaHTTP(
serverAddress(),
'/api/revalidate',
undefined,
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname: '/pages-victim/on-demand' }),
}
)
expect(response.status).toBe(200)
await retry(async () => {
const current = await read('/pages-victim/on-demand')
expect(current.route).toBe('pages-victim')
expect(current.generation).not.toBe(before.generation)
})
})
it.each([
['/%70ages-victim', '/pages-victim', 'pages-catchall', 'pages-victim'],
['/%61pp-victim', '/app-victim', 'pages-catchall', 'app-victim'],
[
'/app-only/%76ictim',
'/app-only/victim',
'app-catchall',
'app-only-victim',
],
['/%61pi/victim', '/api/victim', 'pages-catchall', 'route-victim'],
])(
'security: isolates %s in the standalone distribution',
async (alias, canonical, aliasOwner, owner) => {
const first = await read(`${alias}/standalone`)
expect(first.route).toBe(aliasOwner)
const second = await read(`${canonical}/standalone`)
expect(second.route).toBe(owner)
expect(await read(`${alias}/standalone`)).toEqual(first)
expect(await read(`${canonical}/standalone`)).toEqual(second)
}
)
})
describe('route-scoped-cache minimal-mode handler contract', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, '../route-scoped-cache'),
// This harness supplies trusted adapter routing metadata locally. Hosted
// platforms perform their own route selection and filter client headers.
skipDeployment: true,
startCommand: 'node minimal-server.js',
serverReadyPattern: /minimal server ready/,
})
if (skipped) return
it.each([
['allowed', 200],
['not-found', 404],
])(
'normal: preserves the App Handler publication allowlist for %s',
async (id, status) => {
const response = await next.fetch(`/api-admission/${id}`, {
headers: { 'x-matched-path': '/api-admission/[...slug]' },
})
expect(response.status).toBe(status)
expect((await response.json()).route).toBe('route-admission-closed')
}
)
it.each(['published', 'not-found'])(
'security: App Handler publication allowlist declines sibling admission for %s',
async (id) => {
const response = await next.fetch(`/api-admission/sibling/${id}`, {
headers: { 'x-matched-path': '/api-admission/[...slug]' },
})
expect(response.status).toBe(500)
expect(await response.text()).toBe('Internal Server Error')
}
)
it.each([
['/pages-victim/minimal', '/[...slug]', 'pages-catchall'],
['/pages-victim/minimal', '/pages-victim/[id]', 'pages-victim'],
['/closed/allowed', '/closed/[...slug]', 'pages-closed-catchall'],
['/fr/closed/allowed', '/closed/[...slug]', 'pages-closed-catchall'],
['/app-victim/minimal', '/[...slug]', 'pages-catchall'],
['/app-victim/minimal', '/app-victim/[id]', 'app-victim'],
['/app-only/victim/minimal', '/app-only/[...slug]', 'app-catchall'],
['/app-only/victim/minimal', '/app-only/victim/[id]', 'app-only-victim'],
])(
'normal: honors the selected route %s → %s',
async (pathname, selected, owner) => {
const states = []
for (let i = 0; i < 2; i++) {
const response = await next.fetch(pathname, {
headers: {
'x-matched-path': selected,
'x-invocation-id': 'shared-invocation',
},
})
expect(response.status).toBe(200)
const state = JSON.parse(
load(await response.text())('#route-state').text()
)
expect(state.route).toBe(owner)
states.push(state)
}
expect(states[1]).toEqual(states[0])
}
)
it.each(['', '/fr'])(
"normal: serves the closed route's own negative entry in locale %s",
async (locale) => {
const response = await next.fetch(`${locale}/closed/not-found`, {
headers: { 'x-matched-path': '/closed/[...slug]' },
})
expect(response.status).toBe(404)
}
)
it.each(
['', '/fr'].flatMap((locale) =>
['published', 'not-found'].map((id) => `${locale}/closed/sibling/${id}`)
)
)(
'security: the selected closed route declines sibling admission for %s',
async (pathname) => {
const response = await next.fetch(pathname, {
headers: { 'x-matched-path': '/closed/[...slug]' },
})
// This minimal harness maps a thrown NoFallbackError to 500. A real
// adapter handles that signal at its route boundary. The closed route
// must decline rather than render the excluded parameters.
expect(response.status).toBe(500)
expect(await response.text()).toBe('Internal Server Error')
}
)
})
# Route-scoped response cache regression tests
These tests specify the alternative to the route-rematching guard. A request
accepted by a route must be able to read and write that route's own response
cache, even when another route produces the same legacy pathname key. Returning
500 for the colliding request does not satisfy these tests.
The suites are intentionally added before the implementation. On the unmodified
baseline, ordinary behavior must pass and the affected isolation cases must
fail with wrong-owner content, a shared negative entry, an overwritten static
page, or a missing route-qualified custom-handler key. Some cross-router cases
already pass because existing filesystem namespaces separate them; those cases
also provide regression coverage.
## Coverage
| Suite | Coverage |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `route-scoped-cache.test.ts` | Default memory + disk, disk-only, and a recording custom handler; Pages, App Pages, Route Handlers, i18n, prebuilt responses, runtime responses, misses/hits, concurrent requests, restart persistence, cached redirects and 404s, fallback admission, ISR lifetimes, on-demand and only-generated revalidation, HTML/data/RSC, rewrites, query strings, trailing slashes, encoded slash/percent/Unicode/space parameters, static HTML, public files |
| `../route-scoped-cache-ppr/route-scoped-cache-ppr.test.ts` | Build-time and runtime PPR shells, partial shells, parameter variants, dynamic resumption, RSC navigation, full prefetch, lifetime and tag/path revalidation, cross-route collisions, intentionally shared `use cache` data |
| `../route-scoped-cache-standalone/route-scoped-cache-standalone.test.ts` | Standalone distribution copied outside the build tree, prebuilt assets, runtime disk persistence, on-demand revalidation and collisions; direct compiled-handler invocation in simulated minimal mode |
| `../../route-scoped-cache-export/route-scoped-cache-export.test.ts` | `output: 'export'` with trailing slashes on/off and a base path; exact public HTML/JSON/RSC/body paths, Unicode/space/index/nested paths, 404s, assets, links and HTTP serving by a plain static server |
Each collision is exercised with the encoded request first and the canonical
request first, including build-time entries. The `/index` and Unicode cases
also constrain compatibility: a route accepted by routing must continue to
render successfully rather than inheriting the guard's 500 response.
The custom handler treats keys as opaque and delegates existing serialization,
expiration and tag behavior to the existing filesystem handler. Its recording
assertions require distinct keys for the same legacy pathname, a fixed-length
source hash and a readable pathname. A long Unicode route group exercises both
build-time prerenders and runtime writes without exceeding filename limits.
The export server models a static server's `try_files $uri.html` behavior because
an App route may have both `known.html` and a `known/` segment-payload directory.
The export App fixture decodes its displayed slug; the baseline export renderer
can supply URI-encoded parameters. Filesystem and HTTP assertions still verify
the actual Unicode and space-containing public paths.
The classic suite also exercises `trailingSlash: true` both with and without
redirects. Prebuilt and runtime-created entries must retain their normal cache
lifetime and hit behavior in both configurations.
A closed Pages catch-all must honor its own `getStaticPaths` allowlist, even
when a sibling prerendered the same decoded pathname.
The admission regressions cover positive and negative sibling entries, HTML and
data requests, and both locales while preserving the catch-all's own allowlist.
Direct compiled-handler checks exercise the same rule in minimal mode.
App Route Handlers must likewise enforce their own generated parameter lists.
App Pages are checked through HTML and RSC requests as well. Dynamic App Pages
and Route Handlers must keep rendering dynamically when a sibling owns a
prerender at the same decoded pathname; foreign metadata must not classify them
as static or supply their prefetch metadata.
## Cache identity and build compatibility
Response keys contain the response kind, the SHA-256 hash of the source route,
and the normalized request pathname. Pages use `definition.pathname` so index
modules have the same identity in both bundlers; App routes use the full
`definition.page`, including groups and slots. The hash occupies
one 64-character directory, with `$` separating it from the readable pathname.
For example, `/blog/post` rendered by `/blog/[slug]` uses
`/route-cache/PAGES/<sha256-of-/blog/[slug]>/$/blog/post`. Node and Edge produce
the same hash from the source's UTF-8 bytes. No route-description file is emitted.
Hashing bounds the added source namespace; request pathnames and PPR segment
paths retain their existing filesystem limits.
Custom handlers must preserve the entire opaque key. Fetch and image keys are
unchanged; image caching has an explicit context without a response-route owner.
The full source module identity includes route groups and parallel slots.
Prerender ownership comes from the existing `srcRoute` and `fallbackSourceRoute`
metadata, with locale normalization for static Pages entries. These fields use
the normalized source route, so the matched App module is normalized only for
this metadata check. Storage hashes include the full source module identity.
No additional per-path cache-key mapping is emitted in the prerender manifest.
Without a build adapter, build-time response artifacts retain their historical
`server/pages` and `server/app` locations. Their metadata records the exact
scoped key, source owner and fallback status that produced the immutable build
seed. Runtime regeneration writes only to `server/route-cache`; it never
updates the historical artifact. With an adapter configured, build-time
responses are written directly to scoped `server/route-cache` keys so
colliding routes stay isolated before packaging. Static `output: 'export'`
continues to emit normal public files.
The filesystem cache checks the scoped entry first. Only when its primary file
is absent may it admit a historical seed whose metadata exactly matches the
requested key and owner. A successful read promotes every payload into the
scoped location without deleting the build artifact and preserves the seed's
original age. The built-in filesystem publishes the primary scoped payload
with an atomic no-replace operation after writing its ancillary files. This
keeps an interrupted promotion retryable and avoids replacing a newer primary;
the ancillary files retain the cache's existing multi-file write semantics.
Custom handlers continue to receive only opaque scoped keys and are never
queried with the historical pathname.
## Deployment behavior
The classic and PPR HTTP suites retain deployment coverage. Vercel already
isolates cache entries by selected route, and may normalize encoded aliases
before invocation. Those assertions permit the platform's selected owner while
requiring the canonical route to keep its own content. Vercel can also terminate
an unlisted fallback-false route with 404 at a function boundary. Exact local
cache headers, process restart, and custom-handler recordings are asserted
locally; deployment branches assert the corresponding public response behavior.
Standalone packaging, simulated trusted adapter metadata, and exported-file
inspection are inherently local assertions. Those two suite files explicitly
exclude deploy mode. The minimal-mode harness does not claim to reproduce the
entire Vercel deployment pipeline.
## Running
Run all four files with `pnpm test-start` and `pnpm test-start-turbo`.
Use the normal isolated-package harness for packaging validation, especially
standalone. The tests use real fixtures, public HTTP requests and generated
artifacts; they do not modify compiled framework code or depend on a proposed
cache layout.
## Next 15 adaptations
The backport uses `experimental.adapterPath`, the flat adapter output format,
and `.prefetch.rsc` for PPR payloads. The PPR fixture uses the unstable cache-life
and cache-tag exports. Segment-prefetch protocol assertions from canary are not
included because Next 15 does not support `partialPrefetching`; full RSC
navigation and prefetch ownership are covered. The minimal handler fixture
initializes Node APIs and request metadata through the existing Next 15 entrypoints.
The Next 15 adapter baseline cannot build static locale-prefixed Pages prerenders
(`getParentOutput` looks up `/en/static` rather than `/static`) and does not emit
localized fallback output records. The i18n adapter regression therefore checks
its supported dynamic prerender outputs plus the scoped physical fallback files
for both locales, without changing the inherited adapter routing contract.
Parallel App entries use Next 15's lexical ordering consistently during build and
runtime selection, independent of manifest insertion order. Closed-route tests
check both legacy seeds and experimental adapter artifacts. Empty PPR shells and
empty App Route responses retain positive memory-cache accounting during seed
promotion; the LRU eviction invariant is unchanged.
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return [{ id: 'known' }]
}
export default async function Page({ params }) {
return <State value={state('app-grouped', await params)} />
}
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return [{ id: 'known' }]
}
export default async function Page({ params }) {
return <State value={state('app-long-source', await params)} />
}
import { state } from '../../../lib/state'
export const dynamic = 'force-static'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['allowed', 'not-found'].map((slug) => ({ slug: [slug] }))
}
export async function GET(_request, { params }) {
const resolved = await params
return Response.json(state('route-admission-closed', resolved), {
status: resolved.slug[0] === 'not-found' ? 404 : 200,
headers: { 'x-fixture-route': 'route-admission-closed' },
})
}
import { state } from '../../../../lib/state'
export const dynamic = 'force-static'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['published', 'not-found'].map((id) => ({ id }))
}
export async function GET(_request, { params }) {
const resolved = await params
return Response.json(state('route-admission-sibling', resolved), {
status: resolved.id === 'not-found' ? 404 : 200,
headers: { 'x-fixture-route': 'route-admission-sibling' },
})
}
import { state } from '../../../lib/state'
export const dynamic = 'force-dynamic'
export async function GET(_request, { params }) {
return Response.json(state('route-dynamic-catchall', await params))
}
import { state } from '../../../lib/state'
export const dynamic = 'force-static'
export function GET() {
return Response.json(state('route-dynamic-sibling'))
}
import { revalidatePath } from 'next/cache'
export async function POST(request) {
const { pathname } = await request.json()
if (typeof pathname !== 'string' || !pathname.startsWith('/app-victim/'))
return new Response(null, { status: 400 })
revalidatePath(pathname)
return Response.json({ revalidated: true })
}
import { state } from '../../../../lib/state'
export const dynamic = 'force-static'
export const revalidate = 3600
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export async function GET(_request, { params }) {
return Response.json(state('route-victim', await params), {
headers: { 'x-fixture-route': 'route-victim' },
})
}
import { notFound } from 'next/navigation'
import { state, State } from '../../../lib/state'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['allowed', 'not-found'].map((slug) => ({ slug: [slug] }))
}
export default async function Page({ params }) {
const resolved = await params
if (resolved.slug[0] === 'not-found') notFound()
return <State value={state('app-admission-closed', resolved)} />
}
import { notFound } from 'next/navigation'
import { state, State } from '../../../../lib/state'
export const dynamicParams = false
export const revalidate = false
export function generateStaticParams() {
return ['published', 'not-found'].map((id) => ({ id }))
}
export default async function Page({ params }) {
const resolved = await params
if (resolved.id === 'not-found') notFound()
return <State value={state('app-admission-sibling', resolved)} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 3600
export const dynamicParams = false
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-closed', await params)} />
}
import { state, State } from '../../../lib/state'
export const dynamic = 'force-dynamic'
export default async function Page({ params }) {
return <State value={state('app-dynamic-catchall', await params)} />
}
import { state, State } from '../../../lib/state'
export const dynamic = 'force-static'
export default function Page() {
return <State value={state('app-dynamic-sibling')} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 1
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-fast', await params)} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return []
}
export default async function Page({ params }) {
return <State value={state('app-catchall', await params)} />
}
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export const dynamicParams = false
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-only-closed', await params)} />
}
import { state, State } from '../../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-only-victim', await params)} />
}
import { state, State } from '../../../lib/state'
export const revalidate = 3600
export function generateStaticParams() {
return ['known', 'seed-cold', 'seed-warm'].map((id) => ({ id }))
}
export default async function Page({ params }) {
return <State value={state('app-victim', await params)} />
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
const fs = require('node:fs')
const path = require('node:path')
const FileSystemCache =
require('next/dist/server/lib/incremental-cache/file-system-cache').default
// Exercise the public handler calls using keys as opaque strings. Delegate value
// formats, expiration and tags to Next's existing handler instead of replicating it.
module.exports = class RecordingCacheHandler extends FileSystemCache {
record(operation, key, value, context) {
if (value?.kind === 'FETCH') return
const body = value?.kind === 'PAGES' ? value.pageData?.pageProps : undefined
fs.appendFileSync(
path.join(process.cwd(), 'cache-operations.jsonl'),
JSON.stringify({
operation,
key,
kind: value?.kind,
hasRouteContext: 'route' in context,
route: body?.route,
params: body?.params,
}) + '\n'
)
}
async get(key, context) {
const value = await super.get(key, context)
if (context.kind !== 'FETCH') this.record('get', key, value?.value, context)
return value
}
async set(key, value, context) {
if (!context.fetchCache) this.record('set', key, value, context)
return super.set(key, value, context)
}
}
export function state(route, params = {}, locale = null) {
return { route, params, locale, generation: crypto.randomUUID() }
}
export function State({ value }) {
return <pre id="route-state">{JSON.stringify(value)}</pre>
}
const http = require('node:http')
require('next/dist/server/node-environment')
require('next/dist/server/require-hook')
require('next/dist/server/node-polyfill-crypto')
const { addRequestMeta } = require('next/dist/server/request-meta')
const {
getRouteRegex,
} = require('next/dist/shared/lib/router/utils/route-regex')
const {
getRouteMatcher,
} = require('next/dist/shared/lib/router/utils/route-matcher')
const routes = {
'/[...slug]': require('./.next/server/pages/[...slug].js'),
'/pages-victim/[id]': require('./.next/server/pages/pages-victim/[id].js'),
'/closed/[...slug]': require('./.next/server/pages/closed/[...slug].js'),
'/api-admission/[...slug]': require('./.next/server/app/api-admission/[...slug]/route.js'),
'/app-victim/[id]': require('./.next/server/app/app-victim/[id]/page.js'),
'/app-only/[...slug]': require('./.next/server/app/app-only/[...slug]/page.js'),
'/app-only/victim/[id]': require('./.next/server/app/app-only/victim/[id]/page.js'),
}
// A test adapter supplies the trusted route selection. This deliberately does
// not rerun next start's router before invoking the selected compiled handler.
const server = http.createServer((req, res) => {
const route = routes[req.headers['x-matched-path']]
if (!route) {
res.statusCode = 404
res.end()
return
}
// Next 15 adapters supply the matched params to App handlers; their full
// module names still include /page or /route at this entrypoint.
const pathname =
new URL(req.url, 'http://localhost').pathname.replace(
/^\/(en|fr)(?=\/|$)/,
''
) || '/'
const params = getRouteMatcher(getRouteRegex(req.headers['x-matched-path']))(
pathname
)
if (params) addRequestMeta(req, 'params', params)
addRequestMeta(req, 'minimalMode', true)
addRequestMeta(req, 'relativeProjectDir', '.')
addRequestMeta(req, 'initURL', `http://localhost${req.url}`)
Promise.resolve(route.handler(req, res, { waitUntil() {} })).catch(
(error) => {
console.error(error)
if (!res.writableEnded) {
res.statusCode = 500
res.end('Internal Server Error')
}
}
)
})
server.listen(Number(process.env.PORT), () => {
console.log(`- Local: http://localhost:${server.address().port}`)
console.log('minimal server ready')
})
module.exports = {
trailingSlash: process.env.TRAILING_SLASH === '1',
skipTrailingSlashRedirect: process.env.SKIP_TRAILING_SLASH_REDIRECT === '1',
output: process.env.STANDALONE === '1' ? 'standalone' : undefined,
cacheHandler:
process.env.CACHE_STORAGE === 'custom'
? require.resolve('./cache-handler.js')
: undefined,
cacheMaxMemorySize: process.env.CACHE_STORAGE === 'disk' ? 0 : undefined,
i18n: { locales: ['en', 'fr'], defaultLocale: 'en' },
experimental: { cpus: 2, cacheComponents: false, ppr: false },
async rewrites() {
return [{ source: '/rewritten/:id', destination: '/pages-victim/:id' }]
},
}
export default function Page() {
return <p id="not-found">fixture-not-found</p>
}
import { state, State } from '../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return { paths: [], fallback: 'blocking' }
}
export function getStaticProps({ params, locale }) {
return { props: state('pages-catchall', params, locale), revalidate: 3600 }
}
export default async function handler(req, res) {
const { pathname, onlyGenerated = false } = req.body || {}
if (
req.method !== 'POST' ||
typeof pathname !== 'string' ||
!/^\/(fr\/)?pages-victim\//.test(pathname)
)
return res.status(400).end()
await res.revalidate(pathname, { unstable_onlyGenerated: onlyGenerated })
res.json({ revalidated: true })
}
export default function Page() {
return <p id="static-page">static-unicode</p>
}
import { state, State } from '../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['allowed', 'not-found'].map((slug) => ({
params: { slug: [slug] },
locale,
}))
),
fallback: false,
}
}
export function getStaticProps({ params, locale }) {
if (params.slug[0] === 'not-found') return { notFound: true }
return { props: state('pages-closed-catchall', params, locale) }
}
import { state, State } from '../../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['published', 'not-found'].map((id) => ({ params: { id }, locale }))
),
fallback: false,
}
}
export function getStaticProps({ params, locale }) {
if (params.id === 'not-found') return { notFound: true }
return {
props: state('pages-admission-sibling', params, locale),
revalidate: false,
}
}
export default function Page() {
return <p id="static-page">static-home</p>
}
import { state, State } from '../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['known', 'not-found'].map((id) => ({ params: { id }, locale }))
),
fallback: false,
}
}
export function getStaticProps({ params, locale }) {
if (params.id === 'not-found') return { notFound: true }
return { props: state('pages-closed', params, locale), revalidate: 3600 }
}
import { useRouter } from 'next/router'
import { state, State } from '../../lib/state'
export default function Page(props) {
return useRouter().isFallback ? (
<p id="fallback">Loading</p>
) : (
<State value={props} />
)
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].map((locale) => ({ params: { id: 'known' }, locale })),
fallback: true,
}
}
export function getStaticProps({ params, locale }) {
return { props: state('pages-fallback', params, locale), revalidate: 3600 }
}
import { state, State } from '../../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticPaths() {
return {
paths: ['en', 'fr'].flatMap((locale) =>
['known', 'seed-cold', 'seed-warm'].map((id) => ({
params: { id },
locale,
}))
),
fallback: 'blocking',
}
}
export function getStaticProps({ params, locale }) {
if (params.id.startsWith('missing-'))
return { notFound: true, revalidate: 3600 }
if (params.id === 'redirect')
return {
redirect: { destination: '/pages-victim/known', permanent: false },
}
return {
props: state('pages-victim', params, locale),
revalidate: params.id.startsWith('fast-') ? 1 : 3600,
}
}
export default function Page() {
return <p id="static-page">static-route</p>
}
import { state, State } from '../lib/state'
export default function Page(props) {
return <State value={props} />
}
export function getStaticProps({ locale }) {
return { props: state('pages-static-isr', {}, locale), revalidate: false }
}
export default function Page() {
return null
}
export function getStaticProps() {
return { notFound: true }
}
import { createHash } from 'crypto'
import { RouteKind } from 'next/dist/server/route-kind'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { load } from 'cheerio'
type State = {
route: string
params: { id?: string; slug?: string[] }
locale: string | null
generation: string
}
// Distinct URLs deliberately normalize to the same old incremental-cache key.
// The alternative fix must cache both owners successfully, not reject one.
const collisions = [
['/%70ages-victim', '/pages-victim', 'pages-catchall', 'pages-victim'],
['/fr/%70ages-victim', '/fr/pages-victim', 'pages-catchall', 'pages-victim'],
['/%61pp-victim', '/app-victim', 'pages-catchall', 'app-victim'],
['/app-only/%76ictim', '/app-only/victim', 'app-catchall', 'app-only-victim'],
['/%61pi/victim', '/api/victim', 'pages-catchall', 'route-victim'],
]
describe.each(['default', 'disk', 'custom'])(
'route-scoped-cache (%s)',
(storage) => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
env: { CACHE_STORAGE: storage },
})
async function read(pathname: string) {
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
const body = await response.text()
const state: State = response.headers
.get('content-type')
?.includes('application/json')
? JSON.parse(body)
: JSON.parse(load(body)('#route-state').text())
expect(state.generation).toEqual(expect.any(String))
return { state, response }
}
async function expectOwner(pathname: string, route: string, id?: string) {
const result = await read(pathname)
expect(result.state.route).toBe(route)
if (id !== undefined) expect(result.state.params.id).toBe(id)
return result
}
async function dataPath(pathname: string) {
const $ = await next.render$('/pages-victim/known')
const { buildId } = JSON.parse($('#__NEXT_DATA__').text())
return `/_next/data/${buildId}${pathname}.json`
}
async function readStaticPage(pathname: string) {
const manifest = await next.readJSON('.next/server/pages-manifest.json')
const filename = manifest[pathname === '/' ? '/en' : `/en${pathname}`]
expect(typeof filename).toBe('string')
return next.readFile(`.next/server/${filename}`)
}
it('normal: caches build-time and runtime entries from a long Unicode source', async () => {
for (const id of ['known', 'runtime']) {
const pathname = `/source-hash/${id}`
const first = await expectOwner(pathname, 'app-long-source', id)
expect((await read(pathname)).state).toEqual(first.state)
if (!isNextDeploy) {
// The ASCII suffix avoids an unrelated Turbopack UTF-8 chunk-name
// truncation bug while the encoded source still exceeds NAME_MAX.
const source = `/(${'é'.repeat(40)}${'a'.repeat(80)})/source-hash/[id]/page`
const artifact = next.getPrerenderFilePath(pathname, '.html', {
route: { kind: RouteKind.APP_PAGE, sourceRoute: source },
})
expect(await next.readFile(artifact)).toContain(
first.state.generation
)
}
}
})
it('normal: emits verified prerender seeds at historical paths', async () => {
if (isNextDeploy) {
await expectOwner('/pages-victim/known', 'pages-victim', 'known')
await expectOwner('/app-victim/known', 'app-victim', 'known')
await expectOwner('/api/victim/known', 'route-victim', 'known')
return
}
const manifest = await next.readJSON('.next/prerender-manifest.json')
expect(manifest).not.toHaveProperty('cacheKeys')
for (const [pathname, router, extensions] of [
['/en/pages-victim/known', 'pages', ['.html', '.json', '.meta']],
['/fr/pages-victim/known', 'pages', ['.html', '.json', '.meta']],
['/en/pages-fallback/[id]', 'pages', ['.html', '.meta']],
['/fr/pages-fallback/[id]', 'pages', ['.html', '.meta']],
['/app-victim/known', 'app', ['.html', '.rsc', '.meta']],
['/grouped/known', 'app', ['.html', '.rsc', '.meta']],
['/api/victim/known', 'app', ['.body', '.meta']],
] as const) {
for (const extension of extensions) {
expect(
await next.hasFile(
next.getPrerenderFilePath(pathname, extension, { router })
)
).toBe(true)
}
const metadata = await next.readJSON(
next.getPrerenderFilePath(pathname, '.meta', { router })
)
expect(metadata.routeCache).toEqual(
expect.objectContaining({
key: expect.stringMatching(/^\/route-cache\//),
owner: expect.objectContaining({ sourceRoute: expect.any(String) }),
isFallback: expect.any(Boolean),
})
)
}
for (const {
artifactPath,
requestPath,
router,
extension,
expectedOwner,
} of [
{
artifactPath: '/en/pages-victim/known',
requestPath: '/pages-victim/known',
router: 'pages',
extension: '.html',
expectedOwner: 'pages-victim',
},
{
artifactPath: '/grouped/known',
requestPath: '/grouped/known',
router: 'app',
extension: '.html',
expectedOwner: 'app-grouped',
},
{
artifactPath: '/api/victim/known',
requestPath: '/api/victim/known',
router: 'app',
extension: '.body',
expectedOwner: 'route-victim',
},
] as const) {
const historicalPath = next.getPrerenderFilePath(
artifactPath,
extension,
{ router }
)
const seed = await next.readFile(historicalPath)
const first = await expectOwner(requestPath, expectedOwner, 'known')
expect(seed).toContain(first.state.generation)
const metadata = await next.readJSON(
next.getPrerenderFilePath(artifactPath, '.meta', { router })
)
expect(
await next.readFile(
next.getPrerenderFilePath(artifactPath, extension, {
route: metadata.routeCache.owner,
})
)
).toBe(seed)
}
})
it('normal: runtime regeneration writes only scoped artifacts', async () => {
const pathname = '/pages-victim/known'
const before = await expectOwner(pathname, 'pages-victim')
const legacyPath = '.next/server/pages/en/pages-victim/known.html'
const legacySeed = isNextDeploy
? undefined
: await next.readFile(legacyPath)
if (!isNextDeploy) {
expect(legacySeed).toContain(before.state.generation)
}
const revalidate = await next.fetch('/api/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname }),
})
expect(revalidate.status).toBe(200)
await retry(async () => {
const after = await expectOwner(pathname, 'pages-victim')
expect(after.state.generation).not.toBe(before.state.generation)
if (!isNextDeploy) {
expect(await next.readFile(legacyPath)).toBe(legacySeed)
expect(
await next.readFile(
next.getPrerenderFilePath('/en/pages-victim/known', '.html', {
route: {
kind: RouteKind.PAGES,
sourceRoute: '/pages-victim/[id]',
},
})
)
).toContain(after.state.generation)
}
})
})
it.each(['', '/fr'])(
'normal: retains static Pages ownership and lifetime for locale %s',
async (locale) => {
const { response, state } = await expectOwner(
`${locale}/static-isr`,
'pages-static-isr'
)
expect(state.locale).toBe(locale ? 'fr' : 'en')
const repeated = await expectOwner(
`${locale}/static-isr`,
'pages-static-isr'
)
expect(repeated.state).toEqual(state)
expect((await next.fetch(`${locale}/static-not-found`)).status).toBe(
404
)
if (!isNextDeploy) {
expect(response.headers.get('x-nextjs-cache')).toBe('HIT')
expect(response.headers.get('cache-control')).toContain(
's-maxage=31536000'
)
}
}
)
it.each([
['/app-dynamic', 'app-dynamic-catchall', 'app-dynamic-sibling'],
['/api-dynamic', 'route-dynamic-catchall', 'route-dynamic-sibling'],
])(
'normal: preserves dynamic rendering when a sibling prerender exists for %s',
async (prefix, owner, sibling) => {
const canonical = await expectOwner(`${prefix}/sibling`, sibling)
const alias = `${prefix}/%73ibling`
const first = await read(alias)
const second = await read(alias)
if (isNextDeploy && first.state.route === sibling) {
expect(second.state).toEqual(first.state)
} else {
expect(first.state.route).toBe(owner)
expect(second.state.route).toBe(owner)
expect(second.state.generation).not.toBe(first.state.generation)
}
expect((await read(`${prefix}/sibling`)).state).toEqual(canonical.state)
}
)
for (const [prefix, closed, sibling, formats] of [
[
'/api-admission',
'route-admission-closed',
'route-admission-sibling',
['GET', 'HEAD'],
],
[
'/app-admission',
'app-admission-closed',
'app-admission-sibling',
['GET', 'RSC'],
],
] as const) {
it(`normal: preserves the App publication allowlist for ${prefix}`, async () => {
await expectOwner(`${prefix}/allowed`, closed)
expect((await next.fetch(`${prefix}/not-found`)).status).toBe(404)
await expectOwner(`${prefix}/sibling/published`, sibling, 'published')
expect((await next.fetch(`${prefix}/sibling/not-found`)).status).toBe(
404
)
})
it.each(
['published', 'not-found'].flatMap((id) =>
formats.map((format) => [id, format])
)
)(
`security: App publication allowlist for ${prefix} cannot borrow sibling admission (%s, %s)`,
async (id, format) => {
for (let attempt = 0; attempt < 2; attempt++) {
const response = await next.fetch(`${prefix}/%73ibling/${id}`, {
method: format === 'HEAD' ? 'HEAD' : 'GET',
headers: format === 'RSC' ? { RSC: '1' } : {},
})
if (isNextDeploy && response.status === 404) continue
expect(response.status).toBe(200)
expect(response.headers.get('x-fixture-route')).not.toBe(closed)
if (format !== 'HEAD') {
const body = await response.text()
expect(body).not.toContain(closed)
expect(
body.includes('pages-catchall') ||
(isNextDeploy && body.includes(sibling))
).toBe(true)
}
}
}
)
}
it.each([
['/pages-victim/known', 'pages-victim'],
['/fr/pages-victim/known', 'pages-victim'],
['/app-victim/known', 'app-victim'],
['/app-only/victim/known', 'app-only-victim'],
['/api/victim/known', 'route-victim'],
['/grouped/known', 'app-grouped'],
['/pages-fallback/known', 'pages-fallback'],
['/fr/pages-fallback/known', 'pages-fallback'],
])(
'normal: reads the build-time response for %s',
async (pathname, route) => {
const first = await expectOwner(pathname, route, 'known')
const second = await expectOwner(pathname, route, 'known')
expect(second.state.generation).toBe(first.state.generation)
if (!isNextDeploy)
expect(first.response.headers.get('x-nextjs-cache')).toBe('HIT')
}
)
it.each([
['/pages-fallback', 'en'],
['/fr/pages-fallback', 'fr'],
])(
'normal: serves the fallback shell and then data for %s',
async (prefix, locale) => {
const pathname = `${prefix}/fallback-runtime`
const response = await next.fetch(pathname)
expect(response.status).toBe(200)
const $ = load(await response.text())
const data = JSON.parse($('#__NEXT_DATA__').text())
if (!isNextDeploy) {
// The platform may complete a fallback before sending its response.
// next start serves the build-time fallback HTML on the initial request.
expect(data.isFallback).toBe(true)
expect($('#fallback').text()).toBe('Loading')
}
const result = await next.fetch(
await dataPath(`/${locale}/pages-fallback/fallback-runtime`)
)
expect(result.status).toBe(200)
expect((await result.json()).pageProps).toMatchObject({
route: 'pages-fallback',
params: { id: 'fallback-runtime' },
locale,
})
const ready = await expectOwner(
pathname,
'pages-fallback',
'fallback-runtime'
)
expect(ready.state.locale).toBe(locale)
expect((await expectOwner(pathname, 'pages-fallback')).state).toEqual(
ready.state
)
}
)
it.each([
['/pages-victim', 'pages-victim'],
['/app-victim', 'app-victim'],
['/api/victim', 'route-victim'],
])(
'normal: caches a runtime-generated response for %s',
async (prefix, route) => {
const path = `${prefix}/normal-runtime`
const first = await expectOwner(path, route, 'normal-runtime')
const hit = await expectOwner(path, route, 'normal-runtime')
expect(hit.state.generation).toBe(first.state.generation)
if (!isNextDeploy) {
expect(first.response.headers.get('x-nextjs-cache')).toBe('MISS')
expect(hit.response.headers.get('x-nextjs-cache')).toBe('HIT')
}
}
)
it('normal: separates locale variants', async () => {
const en = await read('/pages-victim/locale')
const fr = await read('/fr/pages-victim/locale')
expect(en.state.locale).toBe('en')
expect(fr.state.locale).toBe('fr')
expect(en.state.generation).not.toBe(fr.state.generation)
expect((await read('/pages-victim/locale')).state).toEqual(en.state)
expect((await read('/fr/pages-victim/locale')).state).toEqual(fr.state)
})
it.each(['a%2Fb', 'a%252Fb', 'caf%C3%A9', 'with%20space'])(
'normal: preserves an encoded parameter %s',
async (encoded) => {
const path = `/pages-victim/${encoded}`
const first = await expectOwner(
path,
'pages-victim',
decodeURIComponent(encoded)
)
const second = await read(path)
expect(second.state).toEqual(first.state)
}
)
it('normal: shares HTML and Pages data for the same route and locale', async () => {
const pathname = '/fr/pages-victim/html-data'
const html = await read(pathname)
const data = await next.fetch(await dataPath(pathname))
expect(data.status).toBe(200)
expect((await data.json()).pageProps).toEqual(html.state)
})
it('normal: shares RSC and HTML for the same App route', async () => {
const { state } = await expectOwner('/app-victim/html-rsc', 'app-victim')
const rsc = await next.fetch('/app-victim/html-rsc', {
headers: { RSC: '1' },
})
expect(rsc.status).toBe(200)
expect(rsc.headers.get('content-type')).toContain('text/x-component')
expect(await rsc.text()).toContain(state.generation)
})
it('normal: preserves rewrites, query handling and trailing-slash redirects', async () => {
const direct = await read('/pages-victim/rewritten')
expect((await read('/rewritten/rewritten')).state).toEqual(direct.state)
expect((await read('/pages-victim/rewritten?ignored=1')).state).toEqual(
direct.state
)
const redirect = await next.fetch('/pages-victim/rewritten/', {
redirect: 'manual',
})
expect(redirect.status).toBe(308)
expect(
new URL(redirect.headers.get('location')!, 'http://n').pathname
).toBe('/pages-victim/rewritten')
})
it('normal: keeps redirects and negative responses cacheable', async () => {
for (let i = 0; i < 2; i++) {
const redirect = await next.fetch('/pages-victim/redirect', {
redirect: 'manual',
})
expect(redirect.status).toBe(307)
expect(
new URL(redirect.headers.get('location')!, 'http://n').pathname
).toBe('/pages-victim/known')
expect((await next.fetch('/pages-victim/missing-normal')).status).toBe(
404
)
expect((await next.fetch('/pages-closed/not-found')).status).toBe(404)
}
})
it.each([
['/pages-closed/known', 'pages-closed'],
['/app-closed/known', 'app-closed'],
['/app-only/closed/known', 'app-only-closed'],
])(
'normal: serves a listed fallback:false path %s',
async (pathname, route) => {
await expectOwner(pathname, route, 'known')
}
)
it.each(['', '/fr'])(
'normal: preserves the closed catch-all allowlist for locale %s',
async (locale) => {
const allowed = await expectOwner(
`${locale}/closed/allowed`,
'pages-closed-catchall'
)
expect(allowed.state.params.slug).toEqual(['allowed'])
expect(allowed.state.locale).toBe(locale ? 'fr' : 'en')
expect((await next.fetch(`${locale}/closed/not-found`)).status).toBe(
404
)
await expectOwner(
`${locale}/closed/sibling/published`,
'pages-admission-sibling',
'published'
)
expect(
(await next.fetch(`${locale}/closed/sibling/not-found`)).status
).toBe(404)
}
)
it.each(
['', '/fr'].flatMap((locale) =>
['published', 'not-found'].flatMap((id) =>
['html', 'data'].map((format) => [locale, id, format])
)
)
)(
'security: a closed catch-all cannot borrow sibling admission (%s, %s, %s)',
async (locale, id, format) => {
const pathname = `${locale}/closed/%73ibling/${id}`
const requestPath =
format === 'data'
? await dataPath(`${locale || '/en'}/closed/%73ibling/${id}`)
: pathname
for (let attempt = 0; attempt < 2; attempt++) {
const response = await next.fetch(requestPath)
if (isNextDeploy && response.status === 404) continue
expect(response.status).toBe(200)
const body = await response.text()
const state: State = response.headers
.get('content-type')
?.includes('application/json')
? JSON.parse(body).pageProps
: JSON.parse(load(body)('#route-state').text())
// A platform may canonicalize the alias before invoking a route.
// Neither routing choice may admit the closed catch-all's excluded
// parameters using the sibling's positive or negative prerender.
expect(
isNextDeploy
? ['pages-catchall', 'pages-admission-sibling']
: ['pages-catchall']
).toContain(state.route)
}
}
)
it.each([
['/pages-closed/unlisted', 'pages-catchall'],
['/app-closed/unlisted', 'pages-catchall'],
['/app-only/closed/unlisted', 'app-catchall'],
])(
'normal: honors route admission before a cache read for %s',
async (pathname, route) => {
if (isNextDeploy) {
// The deployed router may terminate a fallback:false route at the
// function boundary instead of applying next start's route fall-through.
const response = await next.fetch(pathname)
expect([200, 404]).toContain(response.status)
if (response.status === 200) await expectOwner(pathname, route)
} else {
const first = await expectOwner(pathname, route)
expect((await expectOwner(pathname, route)).state).toEqual(
first.state
)
}
}
)
it.each([
['/pages-victim/fast-normal', 'pages-victim'],
['/app-fast/normal', 'app-fast'],
])('normal: regenerates a stale entry for %s', async (pathname, route) => {
const first = await expectOwner(pathname, route)
await retry(async () => {
const refreshed = await expectOwner(pathname, route)
expect(refreshed.state.generation).not.toBe(first.state.generation)
})
})
it.each([
['/pages-victim/on-demand', '/api/revalidate', 'pages-victim'],
['/fr/pages-victim/on-demand', '/api/revalidate', 'pages-victim'],
['/app-victim/on-demand', '/api/revalidate-app', 'app-victim'],
])(
'normal: revalidates %s through its public pathname',
async (pathname, endpoint, route) => {
const first = await expectOwner(pathname, route)
const response = await next.fetch(endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname }),
})
expect(response.status).toBe(200)
await retry(async () => {
const current = await expectOwner(pathname, route)
expect(current.state.generation).not.toBe(first.state.generation)
})
}
)
it('normal: only-generated revalidation does not create an absent entry', async () => {
const pathname = '/pages-victim/only-generated'
const response = await next.fetch('/api/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname, onlyGenerated: true }),
})
expect(response.status).toBe(200)
const first = await expectOwner(
pathname,
'pages-victim',
'only-generated'
)
if (!isNextDeploy)
expect(first.response.headers.get('x-nextjs-cache')).toBe('MISS')
expect((await read(pathname)).state).toEqual(first.state)
})
it('normal: serves static pages and public files', async () => {
expect(await next.render('/')).toContain('static-home')
expect(await next.render('/route')).toContain('static-route')
expect(await next.render('/plain.txt')).toBe('public-file\n')
})
for (const [
aliasPrefix,
canonicalPrefix,
aliasOwner,
canonicalOwner,
] of collisions) {
it.each(['cold', 'warm', 'seed-cold', 'seed-warm'])(
`security: isolates ${canonicalPrefix} in %s order`,
async (order) => {
const id = order.startsWith('seed-') ? order : `collision-${order}`
const alias = `${aliasPrefix}/${id}`
const canonical = `${canonicalPrefix}/${id}`
if (order.endsWith('warm'))
await expectOwner(canonical, canonicalOwner, id)
// Vercel already scopes by selected route, and may canonicalize an
// encoded path before invoking it. Both selections are valid there;
// next start must render its selected catch-all successfully.
const encoded = await read(alias)
expect(
isNextDeploy ? [aliasOwner, canonicalOwner] : [aliasOwner]
).toContain(encoded.state.route)
const ordinary = await expectOwner(canonical, canonicalOwner, id)
const again = await read(alias)
expect(again.state.route).toBe(encoded.state.route)
expect(again.state.generation).toBe(encoded.state.generation)
expect((await read(canonical)).state).toEqual(ordinary.state)
if (encoded.state.route === aliasOwner)
expect(encoded.state.generation).not.toBe(ordinary.state.generation)
}
)
}
it('security: keeps cache lifetimes independent for the same legacy key', async () => {
const aliasPath = '/%70ages-victim/fast-lifetimes'
const canonicalPath = '/pages-victim/fast-lifetimes'
const longLived = await read(aliasPath)
const shortLived = await expectOwner(
canonicalPath,
'pages-victim',
'fast-lifetimes'
)
await retry(async () => {
const refreshed = await expectOwner(
canonicalPath,
'pages-victim',
'fast-lifetimes'
)
expect(refreshed.state.generation).not.toBe(shortLived.state.generation)
})
const alias = await read(aliasPath)
if (!isNextDeploy) {
expect(alias.response.headers.get('x-nextjs-cache')).toBe('HIT')
expect(alias.state).toEqual(longLived.state)
} else {
expect(['pages-catchall', 'pages-victim']).toContain(alias.state.route)
}
})
it('security: on-demand revalidation updates only the selected Pages route', async () => {
const aliasPath = '/%70ages-victim/invalidation-scope'
const canonicalPath = '/pages-victim/invalidation-scope'
const alias = await read(aliasPath)
const before = await expectOwner(
canonicalPath,
'pages-victim',
'invalidation-scope'
)
const response = await next.fetch('/api/revalidate', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ pathname: canonicalPath }),
})
expect(response.status).toBe(200)
await retry(async () => {
const current = await expectOwner(
canonicalPath,
'pages-victim',
'invalidation-scope'
)
expect(current.state.generation).not.toBe(before.state.generation)
})
const currentAlias = await read(aliasPath)
if (!isNextDeploy || alias.state.route === 'pages-catchall')
expect(currentAlias.state).toEqual(alias.state)
else expect(currentAlias.state.route).toBe('pages-victim')
})
it('security: separates simultaneous writes by two owners', async () => {
await Promise.all([
read('/%70ages-victim/concurrent'),
expectOwner('/pages-victim/concurrent', 'pages-victim', 'concurrent'),
])
const alias = await read('/%70ages-victim/concurrent')
expect(
isNextDeploy ? ['pages-catchall', 'pages-victim'] : ['pages-catchall']
).toContain(alias.state.route)
await expectOwner(
'/pages-victim/concurrent',
'pages-victim',
'concurrent'
)
})
it('security: isolates Pages data requests from the sibling route', async () => {
const alias = await next.fetch(
await dataPath('/en/%70ages-victim/data-collision')
)
expect(alias.status).toBe(200)
const encodedState = (await alias.json()).pageProps
expect(
isNextDeploy ? ['pages-catchall', 'pages-victim'] : ['pages-catchall']
).toContain(encodedState.route)
const ordinary = await expectOwner(
'/pages-victim/data-collision',
'pages-victim',
'data-collision'
)
const data = await next.fetch(
await dataPath('/en/pages-victim/data-collision')
)
expect(data.status).toBe(200)
expect((await data.json()).pageProps).toEqual(ordinary.state)
})
it.each(['missing-cold', 'missing-warm'])(
'security: scopes runtime negative entries (%s)',
async (id) => {
const canonical = `/pages-victim/${id}`
if (id.endsWith('warm'))
expect((await next.fetch(canonical)).status).toBe(404)
const alias = await next.fetch(`/%70ages-victim/${id}`)
if (isNextDeploy && alias.status === 404) {
expect((await next.fetch(canonical)).status).toBe(404)
} else {
expect(alias.status).toBe(200)
expect(
JSON.parse(load(await alias.text())('#route-state').text()).route
).toBe('pages-catchall')
expect((await next.fetch(canonical)).status).toBe(404)
await expectOwner(`/%70ages-victim/${id}`, 'pages-catchall')
}
}
)
it('security: scopes the build-time notFoundRoutes entry to its owner', async () => {
expect((await next.fetch('/pages-closed/not-found')).status).toBe(404)
const alias = await next.fetch('/%70ages-closed/not-found')
if (isNextDeploy && alias.status === 404) {
expect((await next.fetch('/pages-closed/not-found')).status).toBe(404)
} else {
expect(alias.status).toBe(200)
expect(
JSON.parse(load(await alias.text())('#route-state').text()).route
).toBe('pages-catchall')
expect((await next.fetch('/pages-closed/not-found')).status).toBe(404)
}
})
it('security: allows /index without replacing the static homepage', async () => {
const original = isNextDeploy ? undefined : await readStaticPage('/')
expect(await next.render('/')).toContain('static-home')
if (isNextDeploy) {
// Vercel can normalize /index to the static homepage before invocation.
expect((await next.fetch('/index')).status).toBe(200)
} else {
await expectOwner('/index', 'pages-catchall')
}
expect(await next.render('/')).toContain('static-home')
if (!isNextDeploy) expect(await readStaticPage('/')).toBe(original)
})
it('security: allows a Unicode pathname that the catch-all accepts', async () => {
const original = isNextDeploy
? undefined
: await readStaticPage('/café/post')
const result = await next.fetch('/caf%C3%A9/post')
expect(result.status).toBe(200)
if (!isNextDeploy) {
const state = JSON.parse(
load(await result.text())('#route-state').text()
)
expect(state.route).toBe('pages-catchall')
expect(state.params.slug).toEqual(['café', 'post'])
expect(await readStaticPage('/café/post')).toBe(original)
}
})
it('security: preserves independent entries across a process restart', async () => {
const canonical = '/pages-victim/restart'
const before = await expectOwner(canonical, 'pages-victim', 'restart')
const alias = await read('/%70ages-victim/restart')
if (!isNextDeploy) {
await next.stop()
await next.start({ skipBuild: true })
}
// On a deployment these are platform-cache persistence assertions;
// local modes additionally discard every in-process cache above.
expect(
(await expectOwner(canonical, 'pages-victim', 'restart')).state
).toEqual(before.state)
expect((await read('/%70ages-victim/restart')).state).toEqual(alias.state)
expect(
isNextDeploy ? ['pages-catchall', 'pages-victim'] : ['pages-catchall']
).toContain(alias.state.route)
})
if (storage === 'custom') {
it('handler contract: exposes a bounded route namespace and readable pathname', async () => {
const first = await expectOwner(
'/pages-victim/handler-readable',
'pages-victim',
'handler-readable'
)
expect((await read('/pages-victim/handler-readable')).state).toEqual(
first.state
)
if (isNextDeploy) return // Platform ISR owns persistence in minimal mode.
const operations = (await next.readFile('cache-operations.jsonl'))
.trim()
.split('\n')
.map((line) => JSON.parse(line))
const write = operations.find(
(op) => op.operation === 'set' && op.params?.id === 'handler-readable'
)
expect(write).toBeDefined()
expect(operations.every((op) => op.hasRouteContext === false)).toBe(
true
)
expect(typeof write.key).toBe('string')
expect(write.key).toBe(
`/route-cache/PAGES/${createHash('sha256').update('/pages-victim/[id]').digest('hex')}/$/en/pages-victim/handler-readable`
)
expect(
operations.some(
(op) => op.operation === 'get' && op.key === write.key
)
).toBe(true)
})
it('handler contract: supplies distinct opaque keys for source routes', async () => {
await read('/%70ages-victim/handler-key')
await read('/pages-victim/handler-key')
if (isNextDeploy) {
// Platform ISR owns persistence in minimal mode; the self-hosted
// handler need not receive writes. Verify platform route isolation.
await expectOwner(
'/pages-victim/handler-key',
'pages-victim',
'handler-key'
)
return
}
const operations = (await next.readFile('cache-operations.jsonl'))
.trim()
.split('\n')
.map((line) => JSON.parse(line))
const writes = operations.filter(
(op) =>
op.operation === 'set' &&
JSON.stringify(op.params || {}).includes('handler-key')
)
const victim = writes.find((op) => op.route === 'pages-victim')
const catchall = writes.find((op) => op.route === 'pages-catchall')
expect(victim).toBeDefined()
expect(catchall).toBeDefined()
expect(victim.key).not.toBe(catchall.key)
expect(victim.key).toBe(
`/route-cache/PAGES/${createHash('sha256').update('/pages-victim/[id]').digest('hex')}/$/en/pages-victim/handler-key`
)
expect(catchall.key).toBe(
`/route-cache/PAGES/${createHash('sha256').update('/[...slug]').digest('hex')}/$/en/pages-victim/handler-key`
)
expect(
operations.some(
(op) => op.operation === 'get' && op.key === victim.key
)
).toBe(true)
})
}
}
)
describe.each([false, true])(
'route-scoped-cache with trailingSlash (skip redirect: %s)',
(skipRedirect) => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
env: {
TRAILING_SLASH: '1',
SKIP_TRAILING_SLASH_REDIRECT: skipRedirect ? '1' : '0',
},
})
it.each([
'/pages-victim/known/',
'/fr/pages-victim/known/',
'/app-victim/known/',
'/api/victim/known/',
'/pages-victim/trailing-runtime/',
'/app-victim/trailing-runtime/',
'/api/victim/trailing-runtime/',
])(
'preserves the response and its cache lifetime for %s',
async (pathname) => {
const first = await next.fetch(pathname)
expect(first.status).toBe(200)
const firstBody = await first.text()
const state = first.headers
.get('content-type')
?.includes('application/json')
? JSON.parse(firstBody)
: JSON.parse(load(firstBody)('#route-state').text())
const second = await next.fetch(pathname)
expect(second.status).toBe(200)
expect(await second.text()).toContain(state.generation)
if (!isNextDeploy) {
expect(second.headers.get('x-nextjs-cache')).toBe('HIT')
expect(second.headers.get('cache-control')).toContain('s-maxage=3600')
if (pathname.endsWith('/known/')) {
expect(first.headers.get('x-nextjs-cache')).toBe('HIT')
}
}
}
)
}
)
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
export const dynamic = 'force-static'
export function GET() {
return Response.json({ route: 'exported-route-handler' })
}
export function generateStaticParams() {
return ['known', 'index', 'café', 'with space'].map((slug) => ({ slug }))
}
export default async function Page({ params }) {
return <p id="state">{`app:${decodeURIComponent((await params).slug)}`}</p>
}
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <p id="state">export-not-found</p>
}
module.exports = {
output: 'export',
trailingSlash: process.env.TRAILING_SLASH === '1',
basePath: process.env.EXPORT_BASE_PATH || '',
experimental: { cpus: 2 },
}
export default function Page() {
return <p id="state">export-not-found</p>
}
export default function Page({ slug }) {
return <p id="state">{`docs:${slug.join('/')}`}</p>
}
export function getStaticPaths() {
return { paths: [{ params: { slug: ['guide', 'intro'] } }], fallback: false }
}
export function getStaticProps({ params }) {
return { props: params }
}
import Link from 'next/link'
export default function Page() {
return (
<>
<p id="state">export-home</p>
<Link id="pages-link" href="/posts/known">
post
</Link>
<Link id="app-link" href="/article/known">
article
</Link>
</>
)
}
export default function Page({ slug }) {
return <p id="state">{`pages:${slug}`}</p>
}
export function getStaticPaths() {
return {
paths: ['known', 'index', 'café', 'with space'].map((slug) => ({
params: { slug },
})),
fallback: false,
}
}
export function getStaticProps({ params }) {
return { props: params }
}
import { nextTestSetup } from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'
import { load } from 'cheerio'
import express from 'express'
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import path from 'node:path'
import { existsSync } from 'node:fs'
const variants = [
{ trailingSlash: false, basePath: '' },
{ trailingSlash: true, basePath: '' },
{ trailingSlash: false, basePath: '/prefix' },
]
for (const { trailingSlash, basePath } of variants) {
describe(`route-scoped-cache export (trailingSlash=${trailingSlash}, basePath=${basePath})`, () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
// These assertions inspect the exported filesystem and serve it with a
// plain static server. They specifically verify that no Next runtime is needed.
skipDeployment: true,
env: {
TRAILING_SLASH: trailingSlash ? '1' : '',
EXPORT_BASE_PATH: basePath,
},
})
if (skipped) return
let server: Server
let port: number
let origin: string
let buildId: string
const htmlFile = (pathname: string) =>
`out${pathname}${trailingSlash ? '/index' : ''}.html`
beforeAll(async () => {
const { exitCode } = await next.build()
if (exitCode !== 0) throw new Error(`Fixture build failed: ${exitCode}`)
buildId = (await next.readFile('.next/BUILD_ID')).trim()
const app = express()
const outputDirectory = path.join(next.testDir, 'out')
app.use(
basePath || '/',
(req, _res, nextMiddleware) => {
// A route can have both known.html and a known/ directory containing
// segment payloads. Model a static host's try_files $uri.html rule,
// rather than letting Express redirect to that sidecar directory.
if (
existsSync(
path.join(outputDirectory, decodeURIComponent(req.path) + '.html')
)
) {
req.url = req.url.replace(/^([^?]*)(.*)$/, '$1.html$2')
}
nextMiddleware()
},
express.static(outputDirectory, { extensions: ['html'] })
)
server = createServer(app)
await new Promise<void>((resolve) =>
server.listen(0, '127.0.0.1', resolve)
)
port = (server.address() as AddressInfo).port
origin = `http://127.0.0.1:${port}`
})
afterAll(async () => {
if (server)
await new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve()))
)
})
it('normal: publishes the homepage, public asset and custom 404 at public paths', async () => {
expect(load(await next.readFile('out/index.html'))('#state').text()).toBe(
'export-home'
)
expect(load(await next.readFile('out/404.html'))('#state').text()).toBe(
'export-not-found'
)
expect(await next.readFile('out/plain.txt')).toBe('export-public-file\n')
const response = await fetchViaHTTP(origin, `${basePath}/`)
expect(response.status).toBe(200)
const $ = load(await response.text())
expect($('#pages-link').attr('href')).toBe(
`${basePath}/posts/known${trailingSlash ? '/' : ''}`
)
expect($('#app-link').attr('href')).toBe(
`${basePath}/article/known${trailingSlash ? '/' : ''}`
)
expect((await fetchViaHTTP(origin, `${basePath}/absent`)).status).toBe(
404
)
})
it.each(['known', 'index', 'café', 'with space'])(
'normal: exports Pages HTML and data for %s without route-qualified public filenames',
async (slug) => {
const route = `/posts/${slug}`
expect(
load(await next.readFile(htmlFile(route)))('#state').text()
).toBe(`pages:${slug}`)
const dataPath = `/_next/data/${buildId}${route}.json`
expect((await next.readJSON(`out${dataPath}`)).pageProps).toEqual({
slug,
})
const response = await fetchViaHTTP(
origin,
`${basePath}/posts/${encodeURIComponent(slug)}${trailingSlash ? '/' : ''}`
)
expect(response.status).toBe(200)
expect(load(await response.text())('#state').text()).toBe(
`pages:${slug}`
)
const json = await fetchViaHTTP(origin, `${basePath}${dataPath}`)
expect(json.status).toBe(200)
expect((await json.json()).pageProps).toEqual({ slug })
}
)
it.each(['known', 'index', 'café', 'with space'])(
'normal: exports App HTML and RSC for %s without route-qualified public filenames',
async (slug) => {
const route = `/article/${slug}`
expect(
load(await next.readFile(htmlFile(route)))('#state').text()
).toBe(`app:${slug}`)
const rscPath = `${route}${trailingSlash ? '/index' : ''}.txt`
expect(await next.readFile(`out${rscPath}`)).toContain(`app:${slug}`)
const response = await fetchViaHTTP(
origin,
`${basePath}/article/${encodeURIComponent(slug)}${trailingSlash ? '/' : ''}`
)
expect(response.status).toBe(200)
expect(load(await response.text())('#state').text()).toBe(`app:${slug}`)
const rsc = await fetchViaHTTP(origin, `${basePath}${rscPath}`)
expect(rsc.status).toBe(200)
expect(await rsc.text()).toContain(`app:${slug}`)
}
)
it('normal: exports a catch-all route at its concrete nested URL', async () => {
expect(
load(await next.readFile(htmlFile('/docs/guide/intro')))(
'#state'
).text()
).toBe('docs:guide/intro')
const response = await fetchViaHTTP(
origin,
`${basePath}/docs/guide/intro${trailingSlash ? '/' : ''}`
)
expect(response.status).toBe(200)
expect(load(await response.text())('#state').text()).toBe(
'docs:guide/intro'
)
})
it('normal: exports a static Route Handler body at its public URL', async () => {
expect(await next.readJSON('out/api/exported')).toEqual({
route: 'exported-route-handler',
})
const response = await fetchViaHTTP(origin, `${basePath}/api/exported`)
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ route: 'exported-route-handler' })
})
it('normal: exports client assets referenced by the published HTML', async () => {
const $ = load(await next.readFile('out/index.html'))
const scripts = $('script[src]')
.map((_, element) => $(element).attr('src'))
.get()
expect(scripts.length).toBeGreaterThan(0)
for (const src of scripts) {
expect(src).toMatch(new RegExp(`^${basePath}/_next/`))
expect((await fetchViaHTTP(origin, src)).status).toBe(200)
}
})
})
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
import {
CacheHandler,
IncrementalCache,
} from 'next/dist/server/lib/incremental-cache'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import {
CachedRouteKind,
IncrementalCacheKind,
} from 'next/dist/server/response-cache'
function createCache() {
const get = jest
.fn<ReturnType<CacheHandler['get']>, Parameters<CacheHandler['get']>>()
.mockResolvedValue(null)
const set = jest
.fn<ReturnType<CacheHandler['set']>, Parameters<CacheHandler['set']>>()
.mockResolvedValue(undefined)
const preview = {
previewModeId: 'id',
previewModeSigningKey: 'key',
previewModeEncryptionKey: 'key',
}
const cache = new IncrementalCache({
dev: false,
requestHeaders: {},
getPrerenderManifest: () => ({
version: 4,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview,
}),
CurCacheHandler: class extends CacheHandler {
get = get
set = set
},
})
return { cache, get, set }
}
describe('IncrementalCache handler context', () => {
describe.each([
[RouteKind.PAGES, IncrementalCacheKind.PAGES, '/handler/[id]'],
[
RouteKind.APP_PAGE,
IncrementalCacheKind.APP_PAGE,
'/(group)/handler/[id]/page',
],
[
RouteKind.APP_ROUTE,
IncrementalCacheKind.APP_ROUTE,
'/handler/[id]/route',
],
] as const)('%s', (routeKind, kind, sourceRoute) => {
const pathname = '/handler/post'
const route = Object.freeze({ kind: routeKind, sourceRoute })
const cacheKey = getRouteCacheKey(pathname, route)
it('keeps ownership internal while preserving get options', async () => {
const { cache, get } = createCache()
const options = {
kind,
isFallback: true,
isRoutePPREnabled: true,
}
const context = Object.freeze({ route, ...options })
await cache.get(pathname, context)
expect(get).toHaveBeenCalledWith(cacheKey, options)
expect(context.route).toBe(route)
})
it('keeps ownership internal while preserving set options', async () => {
const { cache, set } = createCache()
const options = {
cacheControl: { revalidate: 60, expire: 120 },
isFallback: true,
isRoutePPREnabled: true,
}
const context = Object.freeze({ route, ...options })
await cache.set(pathname, null, context)
expect(set).toHaveBeenCalledWith(cacheKey, null, options)
expect(context.route).toBe(route)
})
})
it('preserves fetch keys and contexts', async () => {
const { cache, get, set } = createCache()
const getContext = Object.freeze({
kind: IncrementalCacheKind.FETCH,
fetchUrl: 'https://example.com/data',
fetchIdx: 1,
revalidate: 60,
tags: ['data'],
softTags: ['page'],
})
await cache.get('fetch-key', getContext)
expect(get).toHaveBeenCalledWith('fetch-key', getContext)
const value = {
kind: CachedRouteKind.FETCH as const,
data: {
headers: {},
body: 'response',
status: 200,
url: getContext.fetchUrl,
},
revalidate: 60,
}
const setContext = Object.freeze({
fetchCache: true,
fetchUrl: getContext.fetchUrl,
fetchIdx: 1,
tags: ['data'],
})
await cache.set('fetch-key', value, setContext)
expect(set).toHaveBeenCalledWith('fetch-key', value, setContext)
})
})
import { promises as fs } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import FileSystemCache from 'next/dist/server/lib/incremental-cache/file-system-cache'
import { nodeFs } from 'next/dist/server/lib/node-fs-methods'
......@@ -6,6 +8,9 @@ import {
CachedRouteKind,
IncrementalCacheKind,
} from 'next/dist/server/response-cache'
import { getRouteCacheKey } from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
import type { CacheFs } from 'next/dist/shared/lib/utils'
const cacheDir = fileURLToPath(new URL('./cache', import.meta.url))
......@@ -127,3 +132,521 @@ describe('FileSystemCache (isrMemory 0)', () => {
})
})
})
describe('FileSystemCache route-scoped build seeds', () => {
let serverDistDir: string
beforeEach(async () => {
serverDistDir = await fs.mkdtemp(join(tmpdir(), 'next-route-seed-'))
})
afterEach(async () => {
await fs.rm(serverDistDir, { recursive: true, force: true })
})
const owner = {
kind: RouteKind.PAGES,
sourceRoute: '/posts/[slug]',
}
const pathname = '/posts/first'
async function writeSeed(options?: {
owner?: typeof owner
isFallback?: boolean
modified?: Date
headers?: Record<string, string>
}) {
const seedOwner = options?.owner ?? owner
const key = getRouteCacheKey(pathname, owner)
const base = join(serverDistDir, 'pages', 'posts', 'first')
await fs.mkdir(join(serverDistDir, 'pages', 'posts'), { recursive: true })
await fs.writeFile(`${base}.html`, 'build html')
await fs.writeFile(`${base}.json`, JSON.stringify({ source: 'build' }))
await fs.writeFile(
`${base}.meta`,
JSON.stringify({
headers: options?.headers,
routeCache: {
key: getRouteCacheKey(pathname, seedOwner),
owner: seedOwner,
isFallback: options?.isFallback ?? false,
},
})
)
if (options?.modified) {
await fs.utimes(`${base}.html`, options.modified, options.modified)
}
return { base, key }
}
function createCache(
flushToDisk = true,
fsImpl: CacheFs = nodeFs,
maxMemoryCacheSize = 0
) {
return new FileSystemCache({
_requestHeaders: {},
flushToDisk,
fs: fsImpl,
serverDistDir,
revalidatedTags: [],
maxMemoryCacheSize,
})
}
const getContext = {
kind: IncrementalCacheKind.PAGES,
isFallback: false,
} as const
it('normalizes the cache root before reading and promoting a build seed', async () => {
const { key } = await writeSeed()
const cache = new FileSystemCache({
_requestHeaders: {},
flushToDisk: true,
fs: nodeFs,
serverDistDir: `${serverDistDir}/nested/..`,
revalidatedTags: [],
maxMemoryCacheSize: 0,
})
expect((await cache.get(key, getContext))?.value).toMatchObject({
html: 'build html',
})
expect(await fs.readFile(`${join(serverDistDir, key)}.html`, 'utf8')).toBe(
'build html'
)
})
it('verifies ownership, promotes all files, and preserves seed age', async () => {
const modified = new Date(Date.now() - 60_000)
const { base, key } = await writeSeed({ modified })
const first = await createCache().get(key, getContext)
expect(first?.value).toMatchObject({
html: 'build html',
pageData: { source: 'build' },
})
expect(first?.lastModified).toBe(modified.getTime())
const scopedBase = join(serverDistDir, key)
expect(await fs.readFile(`${scopedBase}.html`, 'utf8')).toBe('build html')
expect(JSON.parse(await fs.readFile(`${scopedBase}.meta`, 'utf8'))).toEqual(
expect.objectContaining({ routeCacheLastModified: modified.getTime() })
)
await fs.writeFile(`${base}.html`, 'tampered seed')
const restarted = await createCache().get(key, getContext)
expect(restarted?.value).toMatchObject({ html: 'build html' })
expect(restarted?.lastModified).toBe(modified.getTime())
await createCache().set(
key,
{
kind: CachedRouteKind.PAGES,
html: 'runtime html',
pageData: { source: 'runtime' },
headers: undefined,
status: undefined,
},
{ isFallback: false }
)
const afterRuntimeWrite = await createCache().get(key, getContext)
expect(afterRuntimeWrite?.value).toMatchObject({ html: 'runtime html' })
expect(afterRuntimeWrite?.lastModified).toBeGreaterThan(modified.getTime())
expect(afterRuntimeWrite?.lastModified).toBe(
(await fs.stat(`${scopedBase}.html`)).mtime.getTime()
)
expect(
JSON.parse(await fs.readFile(`${scopedBase}.meta`, 'utf8'))
).not.toHaveProperty('routeCacheLastModified')
})
it.each([
['/', '/'],
['/index', '/index'],
])(
'verifies normalized %s without normalizing its suffix twice',
async (requestPath, sourceRoute) => {
const indexOwner = { kind: RouteKind.PAGES, sourceRoute }
const key = getRouteCacheKey(requestPath, indexOwner)
const suffix = key.slice(key.indexOf('/$/') + 2)
const base = join(serverDistDir, 'pages', suffix)
await fs.mkdir(join(base, '..'), { recursive: true })
await fs.writeFile(`${base}.html`, requestPath)
await fs.writeFile(`${base}.json`, '{}')
await fs.writeFile(
`${base}.meta`,
JSON.stringify({
routeCache: {
key,
owner: indexOwner,
isFallback: false,
},
})
)
expect((await createCache().get(key, getContext))?.value).toMatchObject({
html: requestPath,
})
}
)
it('rejects missing, wrong-owner, fallback-mismatched, and partial entries', async () => {
const { base, key } = await writeSeed({
owner: { ...owner, sourceRoute: '/other/[slug]' },
})
expect(await createCache().get(key, getContext)).toBeNull()
await writeSeed({ isFallback: true })
expect(await createCache().get(key, getContext)).toBeNull()
await fs.rm(`${base}.meta`)
expect(await createCache().get(key, getContext)).toBeNull()
await writeSeed()
await fs.mkdir(join(serverDistDir, key, '..'), { recursive: true })
await fs.writeFile(`${join(serverDistDir, key)}.html`, 'partial scoped')
expect(await createCache().get(key, getContext)).toBeNull()
})
it.each([false, true])(
'promotes an owned PPR shell for an isFallback=%s lookup',
async (isFallback) => {
const appOwner = {
kind: RouteKind.APP_PAGE,
sourceRoute: '/posts/[slug]/page',
}
const key = getRouteCacheKey('/posts/[slug]', appOwner)
const base = join(serverDistDir, 'app', 'posts', '[slug]')
await fs.mkdir(join(base, '..'), { recursive: true })
await fs.writeFile(`${base}.html`, 'build shell')
await fs.writeFile(`${base}.prefetch.rsc`, 'build prefetch')
await fs.writeFile(
`${base}.meta`,
JSON.stringify({
postponed: 'postponed data',
routeCache: { key, owner: appOwner, isFallback: true },
})
)
const context = {
kind: IncrementalCacheKind.APP_PAGE,
isRoutePPREnabled: true,
isFallback,
} as const
const otherKey = getRouteCacheKey('/posts/[slug]', {
...appOwner,
sourceRoute: '/[...slug]/page',
})
expect(await createCache().get(otherKey, context)).toBeNull()
expect((await createCache().get(key, context))?.value).toMatchObject({
html: 'build shell',
postponed: 'postponed data',
})
await fs.rm(`${base}.html`)
expect((await createCache().get(key, context))?.value).toMatchObject({
html: 'build shell',
postponed: 'postponed data',
})
expect(
(await createCache().get(key, { ...context, isFallback: false }))?.value
).toMatchObject({ rscData: Buffer.from('build prefetch') })
}
)
it('promotes a PPR fallback without an optional prefetch payload', async () => {
const appOwner = {
kind: RouteKind.APP_PAGE,
sourceRoute: '/posts/[slug]/page',
}
const key = getRouteCacheKey('/posts/[slug]', appOwner)
const base = join(serverDistDir, 'app', 'posts', '[slug]')
await fs.mkdir(join(base, '..'), { recursive: true })
await fs.writeFile(`${base}.html`, 'build shell')
await fs.writeFile(
`${base}.meta`,
JSON.stringify({
postponed: 'postponed data',
routeCache: { key, owner: appOwner, isFallback: true },
})
)
const context = {
kind: IncrementalCacheKind.APP_PAGE,
isRoutePPREnabled: true,
isFallback: true,
} as const
expect((await createCache().get(key, context))?.value).toMatchObject({
html: 'build shell',
})
expect(await fs.readFile(`${join(serverDistDir, key)}.html`, 'utf8')).toBe(
'build shell'
)
// Ordinary reads still require a full prefetch payload on Next 15.
expect(
await createCache().get(key, { ...context, isFallback: false })
).toBeNull()
})
it('serves read-only seeds without creating a scoped entry', async () => {
const { key } = await writeSeed()
expect(
(await createCache(false).get(key, getContext))?.value
).toMatchObject({ html: 'build html' })
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
})
it('serves seeds without durable promotion when atomic writes are unavailable', async () => {
const { key } = await writeSeed()
const { writeFileAtomic: _writeFileAtomic, ...fsWithoutAtomic } = nodeFs
expect(
(await createCache(true, fsWithoutAtomic).get(key, getContext))?.value
).toMatchObject({ html: 'build html' })
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
})
it('does not promote an invalidated seed', async () => {
const { key } = await writeSeed({
headers: { 'x-next-cache-tags': 'invalidated-seed' },
modified: new Date(Date.now() - 60_000),
})
const cache = createCache()
await cache.revalidateTag('invalidated-seed')
expect(await cache.get(key, getContext)).toBeNull()
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
})
it('keeps serving the seed when promotion fails before publication', async () => {
const { key } = await writeSeed()
const scopedMeta = `${join(serverDistDir, key)}.meta`
const failingFs: CacheFs = {
...nodeFs,
writeFile: async (...args: Parameters<typeof nodeFs.writeFile>) => {
if (args[0] === scopedMeta) throw new Error('injected meta failure')
return nodeFs.writeFile(...args)
},
}
const cache = createCache(true, failingFs)
expect((await cache.get(key, getContext))?.value).toMatchObject({
html: 'build html',
})
expect((await cache.get(key, getContext))?.value).toMatchObject({
html: 'build html',
})
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
})
it('does not start writes before all promotion source reads succeed', async () => {
const { base, key } = await writeSeed()
let jsonReads = 0
const failingFs: CacheFs = {
...nodeFs,
readFile: (async (...args: Parameters<typeof nodeFs.readFile>) => {
if (args[0] === `${base}.json` && ++jsonReads === 2) {
throw new Error('injected second-read failure')
}
return nodeFs.readFile(...args)
}) as typeof nodeFs.readFile,
}
expect(
(await createCache(true, failingFs).get(key, getContext))?.value
).toMatchObject({ html: 'build html' })
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
expect((await createCache().get(key, getContext))?.value).toMatchObject({
html: 'build html',
})
})
it('waits for atomic primary publication before another get reads disk', async () => {
const { key } = await writeSeed()
let releasePublication!: () => void
let markPublicationStarted!: () => void
const publicationStarted = new Promise<void>((resolve) => {
markPublicationStarted = resolve
})
const publicationGate = new Promise<void>((resolve) => {
releasePublication = resolve
})
const suspendedFs: CacheFs = {
...nodeFs,
writeFileAtomic: async (
...args: Parameters<NonNullable<typeof nodeFs.writeFileAtomic>>
) => {
markPublicationStarted()
await publicationGate
return nodeFs.writeFileAtomic!(...args)
},
}
const cache = createCache(true, suspendedFs)
const first = cache.get(key, getContext)
await publicationStarted
let secondSettled = false
const second = cache.get(key, getContext).finally(() => {
secondSettled = true
})
await new Promise<void>((resolve) => setImmediate(resolve))
expect(secondSettled).toBe(false)
releasePublication()
await expect(first).resolves.toMatchObject({
value: { html: 'build html' },
})
await expect(second).resolves.toMatchObject({
value: { html: 'build html' },
})
expect(await fs.readFile(`${join(serverDistDir, key)}.html`, 'utf8')).toBe(
'build html'
)
})
it('does not expose a partial temporary primary after atomic publication fails', async () => {
const { key } = await writeSeed()
const partialFs: CacheFs = {
...nodeFs,
writeFileAtomic: async (
...args: Parameters<NonNullable<typeof nodeFs.writeFileAtomic>>
) => {
const [target, data] = args
await fs.writeFile(
`${target}.partial`,
Buffer.from(data).subarray(0, 2)
)
throw new Error('injected partial temporary write')
},
}
const cache = createCache(true, partialFs)
expect((await cache.get(key, getContext))?.value).toMatchObject({
html: 'build html',
})
expect((await cache.get(key, getContext))?.value).toMatchObject({
html: 'build html',
})
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
})
it('does not let an older seed promotion replace a concurrent runtime set', async () => {
const { base, key } = await writeSeed()
let releaseRead!: () => void
let markReadStarted!: () => void
const readStarted = new Promise<void>((resolve) => {
markReadStarted = resolve
})
const readGate = new Promise<void>((resolve) => {
releaseRead = resolve
})
const suspendedFs: CacheFs = {
...nodeFs,
readFile: (async (...args: Parameters<typeof nodeFs.readFile>) => {
if (args[0] === `${base}.html`) {
markReadStarted()
await readGate
}
return nodeFs.readFile(...args)
}) as typeof nodeFs.readFile,
}
const cache = createCache(true, suspendedFs, 1024)
const seedRead = cache.get(key, getContext)
await readStarted
await cache.set(
key,
{
kind: CachedRouteKind.PAGES,
html: 'runtime html',
pageData: { source: 'runtime' },
headers: undefined,
status: undefined,
},
{ isFallback: false }
)
releaseRead()
expect((await seedRead)?.value).toMatchObject({ html: 'build html' })
expect((await cache.get(key, getContext))?.value).toMatchObject({
html: 'runtime html',
pageData: { source: 'runtime' },
})
expect(await fs.readFile(`${join(serverDistDir, key)}.html`, 'utf8')).toBe(
'runtime html'
)
})
it('keeps an in-memory negative entry authoritative over a build seed', async () => {
const { key } = await writeSeed()
const cache = new FileSystemCache({
_requestHeaders: {},
flushToDisk: true,
fs: nodeFs,
serverDistDir,
revalidatedTags: [],
maxMemoryCacheSize: 1024,
})
await cache.set(key, null, { isFallback: false })
expect((await cache.get(key, getContext))?.value).toBeNull()
await expect(fs.stat(`${join(serverDistDir, key)}.html`)).rejects.toThrow()
})
it('promotes an empty PPR fallback with memory caching enabled', async () => {
const appOwner = {
kind: RouteKind.APP_PAGE,
sourceRoute: '/empty/[slug]/page',
}
const key = getRouteCacheKey('/empty/[slug]', appOwner)
const base = join(serverDistDir, 'app', 'empty', '[slug]')
await fs.mkdir(join(base, '..'), { recursive: true })
await fs.writeFile(`${base}.html`, '')
await fs.writeFile(
`${base}.meta`,
JSON.stringify({
postponed: 'postponed data',
routeCache: { key, owner: appOwner, isFallback: true },
})
)
const context = {
kind: IncrementalCacheKind.APP_PAGE,
isRoutePPREnabled: true,
isFallback: true,
} as const
expect(
(await createCache(true, nodeFs, 1024).get(key, context))?.value
).toMatchObject({
html: '',
})
expect(await fs.readFile(`${join(serverDistDir, key)}.html`, 'utf8')).toBe(
''
)
})
it('promotes an empty App Route response with memory caching enabled', async () => {
const owner = { kind: RouteKind.APP_ROUTE, sourceRoute: '/empty/route' }
const key = getRouteCacheKey('/empty', owner)
const base = join(serverDistDir, 'app', 'empty')
await fs.mkdir(join(base, '..'), { recursive: true })
await fs.writeFile(`${base}.body`, '')
await fs.writeFile(
`${base}.meta`,
JSON.stringify({
status: 204,
routeCache: { key, owner, isFallback: false },
})
)
const context = {
kind: IncrementalCacheKind.APP_ROUTE,
isFallback: false,
} as const
const cache = createCache(true, nodeFs, 1024)
expect((await cache.get(key, context))?.value).toMatchObject({
body: Buffer.alloc(0),
status: 204,
})
expect((await cache.get(key, context))?.value).toMatchObject({
body: Buffer.alloc(0),
status: 204,
})
})
})
import { createHash } from 'crypto'
import {
getResponseCacheOwner,
getRouteCacheKey,
isRouteCacheOwner,
} from 'next/dist/server/lib/route-cache-key'
import { RouteKind } from 'next/dist/server/route-kind'
const pages = (sourceRoute: string) => ({ kind: RouteKind.PAGES, sourceRoute })
describe('response cache identity', () => {
it('rejects callers that omit the source route', () => {
expect(() => {
// @ts-expect-error a pathname alone cannot identify a response cache entry
getRouteCacheKey('/blog/post')
}).toThrow('Response cache requires a source route')
})
it('separates source routes that accept the same normalized pathname', () => {
expect(getRouteCacheKey('/blog/post', pages('/blog/[slug]'))).not.toBe(
getRouteCacheKey('/blog/post', pages('/[...slug]'))
)
})
it.each(['/', '/nested', '/blog/[slug]', '/index'])(
'uses the Pages pathname regardless of the bundler module name: %s',
(pathname) => {
const webpack = getResponseCacheOwner({
kind: RouteKind.PAGES,
page: pathname,
pathname,
})
const turbopack = getResponseCacheOwner({
kind: RouteKind.PAGES,
page: pathname === '/' ? '/index' : `${pathname}/index`,
pathname,
})
expect(webpack).toEqual(pages(pathname))
expect(turbopack).toEqual(webpack)
expect(getRouteCacheKey('/post', turbopack)).toBe(
getRouteCacheKey('/post', webpack)
)
}
)
describe.each(['nodejs', 'edge'])('%s hashing', (runtime) => {
beforeEach(() => {
jest.replaceProperty(process, 'env', {
...process.env,
NEXT_RUNTIME: runtime,
})
})
afterEach(() => jest.restoreAllMocks())
it.each(['/blog/[slug]', '/(group)/@slot/café/😀/page'])(
'uses SHA-256 of the full source module: %s',
(page) => {
const hash = createHash('sha256').update(page).digest('hex')
expect(getRouteCacheKey('/blog/post', pages(page))).toBe(
`/route-cache/PAGES/${hash}/$/blog/post`
)
}
)
it.each([
`/${'é'.repeat(50)}/page`,
`/${Array.from({ length: 80 }, (_, i) => `(group${i})`).join('/')}/page`,
])('bounds source directory length and depth: %s', (page) => {
expect(
getRouteCacheKey('/short', {
kind: RouteKind.APP_PAGE,
sourceRoute: page,
})
).toMatch(/^\/route-cache\/APP_PAGE\/[a-f0-9]{64}\/\$\/short$/)
})
})
it('separates response kinds and internal app module identities', () => {
const keys = [
{ kind: RouteKind.PAGES, page: '/blog/[slug]' },
{ kind: RouteKind.APP_PAGE, page: '/blog/[slug]' },
{ kind: RouteKind.APP_ROUTE, page: '/blog/[slug]' },
{ kind: RouteKind.APP_PAGE, page: '/(group)/blog/[slug]/page' },
{ kind: RouteKind.APP_PAGE, page: '/@slot/blog/[slug]/page' },
].map((definition) => {
const owner = getResponseCacheOwner({
...definition,
pathname: '/blog/[slug]',
})
expect(owner.sourceRoute).toBe(definition.page)
return getRouteCacheKey('/blog/post', owner)
})
expect(new Set(keys).size).toBe(keys.length)
})
it('cannot confuse a source-route delimiter with the pathname', () => {
expect(getRouteCacheKey('/b/$/c', pages('/a'))).not.toBe(
getRouteCacheKey('/c', pages('/a/$/b'))
)
expect(getRouteCacheKey('/post', pages('/%24'))).not.toBe(
getRouteCacheKey('/post', pages('/$'))
)
})
it('normalizes the pathname exactly once', () => {
const route = pages('/[[...slug]]')
const keys = ['/', '/index', '/index/index'].map((pathname) =>
getRouteCacheKey(pathname, route)
)
expect(new Set(keys).size).toBe(3)
expect(keys.map((key) => key.split('/$/')[1])).toEqual([
'index',
'index/index',
'index/index/index',
])
})
it('retains locale and escaped pathname distinctions', () => {
const route = pages('/[...slug]')
const keys = ['/en/post', '/fr/post', '/a/b', '/a%2Fb', '/a%252Fb'].map(
(pathname) => getRouteCacheKey(pathname, route)
)
expect(new Set(keys).size).toBe(keys.length)
})
it.each(['/a/../b', '/a/./b', '/a//b'])(
'rejects pathname traversal or normalization across the namespace: %s',
(pathname) => {
expect(() => getRouteCacheKey(pathname, pages('/[...slug]'))).toThrow()
}
)
})
describe('prerender ownership without a cache-key manifest', () => {
it('recognizes a Pages index module without admitting a sibling', () => {
const prerender = {
srcRoute: '/[first]',
dataRoute: '/_next/data/build/en/first.json',
}
expect(
isRouteCacheOwner(
'/en/first',
getResponseCacheOwner({
kind: RouteKind.PAGES,
page: '/[first]/index',
pathname: '/[first]',
}),
prerender,
['en', 'es']
)
).toBe(true)
expect(
isRouteCacheOwner(
'/en/first',
getResponseCacheOwner({
kind: RouteKind.PAGES,
page: '/[...slug]/index',
pathname: '/[...slug]',
}),
prerender,
['en', 'es']
)
).toBe(false)
})
it('requires the source route of a concrete prerender', () => {
const prerender = {
srcRoute: '/blog/[slug]',
dataRoute: '/_next/data/build/blog/post.json',
}
expect(
isRouteCacheOwner('/blog/post', pages('/blog/[slug]'), prerender)
).toBe(true)
expect(
isRouteCacheOwner('/blog/post', pages('/[...slug]'), prerender)
).toBe(false)
expect(
isRouteCacheOwner('/blog/post', pages('/blog/[slug]'), undefined)
).toBe(false)
})
it('recognizes static Pages owners with and without locales', () => {
const prerender = {
srcRoute: null,
dataRoute: '/_next/data/build/about.json',
}
expect(isRouteCacheOwner('/about', pages('/about'), prerender)).toBe(true)
expect(
isRouteCacheOwner('/fr/about', pages('/about'), prerender, ['en', 'fr'])
).toBe(true)
expect(isRouteCacheOwner('/fr', pages('/'), prerender, ['en', 'fr'])).toBe(
true
)
expect(
isRouteCacheOwner('/other/about', pages('/about'), prerender, [
'en',
'fr',
])
).toBe(false)
})
it('recognizes locale-prefixed Pages fallback shells', () => {
const prerender = {
dataRoute: '/_next/data/build/blog/[slug].json',
fallbackSourceRoute: undefined,
}
expect(
isRouteCacheOwner('/fr/blog/[slug]', pages('/blog/[slug]'), prerender, [
'en',
'fr',
])
).toBe(true)
expect(
isRouteCacheOwner('/fr/blog/[slug]', pages('/[...slug]'), prerender, [
'en',
'fr',
])
).toBe(false)
})
it('uses the original source for partially specialized PPR shells', () => {
const prerender = {
fallbackSourceRoute: '/catalog/[category]/[item]',
dataRoute: '/catalog/a/[item].rsc',
}
expect(
isRouteCacheOwner(
'/catalog/a/[item]',
{
kind: RouteKind.APP_PAGE,
sourceRoute: '/(shop)/catalog/[category]/[item]/page',
},
prerender
)
).toBe(true)
expect(
isRouteCacheOwner(
'/catalog/a/[item]',
{
kind: RouteKind.APP_PAGE,
sourceRoute: '/catalog/a/[item]/page',
},
prerender
)
).toBe(false)
})
it('uses App route normalization for groups, slots, and escaped underscores', () => {
expect(
isRouteCacheOwner(
'/_blog/post',
{
kind: RouteKind.APP_PAGE,
sourceRoute: '/(group)/@slot/%5Fblog/[slug]/page',
},
{ srcRoute: '/_blog/[slug]', dataRoute: '/_blog/post.rsc' }
)
).toBe(true)
expect(
isRouteCacheOwner(
'/photos/post',
{
kind: RouteKind.APP_PAGE,
sourceRoute: '/@modal/(.)photos/[slug]/page',
},
{ srcRoute: '/photos/[slug]', dataRoute: '/photos/post.rsc' }
)
).toBe(false)
})
it('keeps response kinds distinct when source pathnames agree', () => {
const pathname = '/blog/[slug]'
const sources = [
pages(pathname),
{ kind: RouteKind.APP_PAGE, sourceRoute: `${pathname}/page` },
{ kind: RouteKind.APP_ROUTE, sourceRoute: `${pathname}/route` },
]
const dataRoutes = [
'/_next/data/build/blog/post.json',
'/blog/post.rsc',
null,
]
for (const [index, route] of sources.entries()) {
for (const [other, dataRoute] of dataRoutes.entries()) {
expect(
isRouteCacheOwner('/blog/post', route, {
srcRoute: pathname,
dataRoute,
})
).toBe(index === other)
}
}
})
it('preserves App locale segments and literal Unicode and index paths', () => {
for (const pathname of ['/fr/about', '/café', '/index']) {
expect(
isRouteCacheOwner(
pathname,
{
kind: RouteKind.APP_PAGE,
sourceRoute: `${pathname}/page`,
},
{ srcRoute: pathname, dataRoute: `${pathname}.rsc` },
['en', 'fr']
)
).toBe(true)
}
expect(
isRouteCacheOwner(
'/fr/about',
{
kind: RouteKind.APP_PAGE,
sourceRoute: '/about/page',
},
{ srcRoute: null, dataRoute: '/fr/about.rsc' },
['en', 'fr']
)
).toBe(false)
})
})
describe('Next 15 parallel app entry ownership', () => {
const {
selectAppPageEntry,
} = require('next/dist/shared/lib/router/utils/app-paths')
it.each([false, true])(
'selects lexical-last independent of input order (%s)',
(reverse) => {
const entries = ['/stories/@slot/[slug]/page', '/stories/[slug]/page']
if (reverse) entries.reverse()
expect(selectAppPageEntry('/stories/[slug]', entries)).toBe(
'/stories/[slug]/page'
)
}
)
it('preserves groups and encoded underscores while ignoring catchall aliases', () => {
expect(
selectAppPageEntry('/_stories/[slug]', [
'/(group)/%5Fstories/@slot/[slug]/page',
'/(group)/%5Fstories/[slug]/page',
'/[...all]/page',
])
).toBe('/(group)/%5Fstories/[slug]/page')
})
})
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