Commit 85bb8728 authored by Zack Tanner's avatar Zack Tanner

fix: ensure route handlers properly track dynamic access (#66446)

In #60645, dynamic access tracking was refactored but we erroneously
stopped tracking dynamic access in route handlers. Request proxying, as
well as tracking segment level configs (such as `export const dynamic =
'force-dynamic'`), were only enabled during static generation. This was
an unintended breaking change that consequently caused dynamic access to
not properly bail from data cache in various circumstances.

This adds some more rigorous testing for route handlers, as this seems
to be a fairly large gap in our fetch cache testing currently.

This PR is easiest to review with [whitespace
disabled](https://github.com/vercel/next.js/pull/66446/files?w=1).
parent 2e7a96a1
...@@ -146,7 +146,7 @@ export function trackDynamicDataAccessed( ...@@ -146,7 +146,7 @@ export function trackDynamicDataAccessed(
if (store.isStaticGeneration) { if (store.isStaticGeneration) {
// We aren't prerendering but we are generating a static page. We need to bail out of static generation // We aren't prerendering but we are generating a static page. We need to bail out of static generation
const err = new DynamicServerError( const err = new DynamicServerError(
`Route ${pathname} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` `Route ${pathname} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
) )
store.dynamicUsageDescription = expression store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack store.dynamicUsageStack = err.stack
......
...@@ -42,13 +42,17 @@ import * as serverHooks from '../../../../client/components/hooks-server-context ...@@ -42,13 +42,17 @@ import * as serverHooks from '../../../../client/components/hooks-server-context
import { DynamicServerError } from '../../../../client/components/hooks-server-context' import { DynamicServerError } from '../../../../client/components/hooks-server-context'
import { requestAsyncStorage } from '../../../../client/components/request-async-storage.external' import { requestAsyncStorage } from '../../../../client/components/request-async-storage.external'
import { staticGenerationAsyncStorage } from '../../../../client/components/static-generation-async-storage.external' import {
staticGenerationAsyncStorage,
type StaticGenerationStore,
} from '../../../../client/components/static-generation-async-storage.external'
import { actionAsyncStorage } from '../../../../client/components/action-async-storage.external' import { actionAsyncStorage } from '../../../../client/components/action-async-storage.external'
import * as sharedModules from './shared-modules' import * as sharedModules from './shared-modules'
import { getIsServerAction } from '../../../lib/server-action-request-meta' import { getIsServerAction } from '../../../lib/server-action-request-meta'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
import { cleanURL } from './helpers/clean-url' import { cleanURL } from './helpers/clean-url'
import { StaticGenBailoutError } from '../../../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../../../client/components/static-generation-bailout'
import { trackDynamicDataAccessed } from '../../../app-render/dynamic-rendering'
/** /**
* The AppRouteModule is the type of the module exported by the bundled App * The AppRouteModule is the type of the module exported by the bundled App
...@@ -308,7 +312,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -308,7 +312,6 @@ export class AppRouteRouteModule extends RouteModule<
let request = rawRequest let request = rawRequest
// Update the static generation store based on the dynamic property. // Update the static generation store based on the dynamic property.
if (isStaticGeneration) {
switch (this.dynamic) { switch (this.dynamic) {
case 'force-dynamic': { case 'force-dynamic': {
// Routes of generated paths should be dynamic // Routes of generated paths should be dynamic
...@@ -321,10 +324,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -321,10 +324,7 @@ export class AppRouteRouteModule extends RouteModule<
staticGenerationStore.forceStatic = true staticGenerationStore.forceStatic = true
// We also Proxy the request to replace dynamic data on the request // We also Proxy the request to replace dynamic data on the request
// with empty stubs to allow for safely executing as static // with empty stubs to allow for safely executing as static
request = new Proxy( request = new Proxy(rawRequest, forceStaticRequestHandlers)
rawRequest,
forceStaticRequestHandlers
)
break break
case 'error': case 'error':
// The dynamic property is set to error, so we should throw an // The dynamic property is set to error, so we should throw an
...@@ -337,25 +337,12 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -337,25 +337,12 @@ export class AppRouteRouteModule extends RouteModule<
) )
break break
default: default:
// When we are statically generating a route we want to bail out if anything dynamic // We proxy `NextRequest` to track dynamic access, and potentially bail out of static generation
// is accessed. We only create this proxy in the staticGenerationCase because it is overhead request = proxyNextRequest(
// for dynamic runtime executions
request = new Proxy(
rawRequest, rawRequest,
staticGenerationRequestHandlers staticGenerationStore
) )
} }
} else {
// Generally if we are in a dynamic render we don't have to modify much however for
// force-static specifically we ensure the dynamic and static behavior is consistent
// by proxying the request in the same way in both cases
if (this.dynamic === 'force-static') {
// The dynamic property is set to force-static, so we should
// force the page to be static.
staticGenerationStore.forceStatic = true
request = new Proxy(rawRequest, forceStaticRequestHandlers)
}
}
// If the static generation store does not have a revalidate value // If the static generation store does not have a revalidate value
// set, then we should set it the revalidate value from the userland // set, then we should set it the revalidate value from the userland
...@@ -661,7 +648,48 @@ const forceStaticNextUrlHandlers = { ...@@ -661,7 +648,48 @@ const forceStaticNextUrlHandlers = {
}, },
} }
const staticGenerationRequestHandlers = { function proxyNextRequest(
request: NextRequest,
staticGenerationStore: StaticGenerationStore
) {
const nextUrlHandlers = {
get(
target: NextURL & UrlSymbolTarget,
prop: string | symbol,
receiver: any
): unknown {
switch (prop) {
case 'search':
case 'searchParams':
case 'url':
case 'href':
case 'toJSON':
case 'toString':
case 'origin': {
trackDynamicDataAccessed(staticGenerationStore, `nextUrl.${prop}`)
const result = Reflect.get(target, prop, receiver)
if (typeof result === 'function') {
return result.bind(target)
}
return result
}
case 'clone':
return (
target[urlCloneSymbol] ||
(target[urlCloneSymbol] = () =>
new Proxy(target.clone(), nextUrlHandlers))
)
default:
const result = Reflect.get(target, prop, receiver)
if (typeof result === 'function') {
return result.bind(target)
}
return result
}
},
}
const nextRequestHandlers = {
get( get(
target: NextRequest & RequestSymbolTarget, target: NextRequest & RequestSymbolTarget,
prop: string | symbol, prop: string | symbol,
...@@ -671,10 +699,7 @@ const staticGenerationRequestHandlers = { ...@@ -671,10 +699,7 @@ const staticGenerationRequestHandlers = {
case 'nextUrl': case 'nextUrl':
return ( return (
target[nextURLSymbol] || target[nextURLSymbol] ||
(target[nextURLSymbol] = new Proxy( (target[nextURLSymbol] = new Proxy(target.nextUrl, nextUrlHandlers))
target.nextUrl,
staticGenerationNextUrlHandlers
))
) )
case 'headers': case 'headers':
case 'cookies': case 'cookies':
...@@ -684,10 +709,15 @@ const staticGenerationRequestHandlers = { ...@@ -684,10 +709,15 @@ const staticGenerationRequestHandlers = {
case 'json': case 'json':
case 'text': case 'text':
case 'arrayBuffer': case 'arrayBuffer':
case 'formData': case 'formData': {
throw new DynamicServerError( trackDynamicDataAccessed(staticGenerationStore, `request.${prop}`)
`Route ${target.nextUrl.pathname} couldn't be rendered statically because it accessed \`request.${prop}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
) const result = Reflect.get(target, prop, receiver)
if (typeof result === 'function') {
return result.bind(target)
}
return result
}
case 'clone': case 'clone':
return ( return (
target[requestCloneSymbol] || target[requestCloneSymbol] ||
...@@ -701,7 +731,7 @@ const staticGenerationRequestHandlers = { ...@@ -701,7 +731,7 @@ const staticGenerationRequestHandlers = {
// to probably embed the static generation logic into the class itself removing the need // to probably embed the static generation logic into the class itself removing the need
// for any kind of proxying // for any kind of proxying
target.clone() as NextRequest, target.clone() as NextRequest,
staticGenerationRequestHandlers nextRequestHandlers
)) ))
) )
default: default:
...@@ -714,39 +744,9 @@ const staticGenerationRequestHandlers = { ...@@ -714,39 +744,9 @@ const staticGenerationRequestHandlers = {
}, },
// We don't need to proxy set because all the properties we proxy are ready only // We don't need to proxy set because all the properties we proxy are ready only
// and will be ignored // and will be ignored
}
const staticGenerationNextUrlHandlers = {
get(
target: NextURL & UrlSymbolTarget,
prop: string | symbol,
receiver: any
): unknown {
switch (prop) {
case 'search':
case 'searchParams':
case 'url':
case 'href':
case 'toJSON':
case 'toString':
case 'origin':
throw new DynamicServerError(
`Route ${target.pathname} couldn't be rendered statically because it accessed \`nextUrl.${prop}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
case 'clone':
return (
target[urlCloneSymbol] ||
(target[urlCloneSymbol] = () =>
new Proxy(target.clone(), staticGenerationNextUrlHandlers))
)
default:
const result = Reflect.get(target, prop, receiver)
if (typeof result === 'function') {
return result.bind(target)
}
return result
} }
},
return new Proxy(request, nextRequestHandlers)
} }
const requireStaticRequestHandlers = { const requireStaticRequestHandlers = {
...@@ -774,7 +774,7 @@ const requireStaticRequestHandlers = { ...@@ -774,7 +774,7 @@ const requireStaticRequestHandlers = {
case 'arrayBuffer': case 'arrayBuffer':
case 'formData': case 'formData':
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${target.nextUrl.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it accessed \`request.${prop}\`.` `Route ${target.nextUrl.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`request.${prop}\`.`
) )
case 'clone': case 'clone':
return ( return (
...@@ -819,7 +819,7 @@ const requireStaticNextUrlHandlers = { ...@@ -819,7 +819,7 @@ const requireStaticNextUrlHandlers = {
case 'toString': case 'toString':
case 'origin': case 'origin':
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${target.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it accessed \`nextUrl.${prop}\`.` `Route ${target.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`nextUrl.${prop}\`.`
) )
case 'clone': case 'clone':
return ( return (
......
...@@ -840,6 +840,8 @@ createNextDescribe( ...@@ -840,6 +840,8 @@ createNextDescribe(
"variable-revalidate/authorization.rsc", "variable-revalidate/authorization.rsc",
"variable-revalidate/authorization/page.js", "variable-revalidate/authorization/page.js",
"variable-revalidate/authorization/page_client-reference-manifest.js", "variable-revalidate/authorization/page_client-reference-manifest.js",
"variable-revalidate/authorization/route-cookies/route.js",
"variable-revalidate/authorization/route-request/route.js",
"variable-revalidate/cookie.html", "variable-revalidate/cookie.html",
"variable-revalidate/cookie.rsc", "variable-revalidate/cookie.rsc",
"variable-revalidate/cookie/page.js", "variable-revalidate/cookie/page.js",
...@@ -2456,6 +2458,38 @@ createNextDescribe( ...@@ -2456,6 +2458,38 @@ createNextDescribe(
}, 'success') }, 'success')
}) })
it('should skip fetch cache when an authorization header is present after dynamic usage', async () => {
const initialReq = await next.fetch(
'/variable-revalidate/authorization/route-cookies'
)
const initialJson = await initialReq.json()
await retry(async () => {
const req = await next.fetch(
'/variable-revalidate/authorization/route-cookies'
)
const json = await req.json()
expect(json).not.toEqual(initialJson)
})
})
it('should skip fetch cache when accessing request properties', async () => {
const initialReq = await next.fetch(
'/variable-revalidate/authorization/route-request'
)
const initialJson = await initialReq.json()
await retry(async () => {
const req = await next.fetch(
'/variable-revalidate/authorization/route-request'
)
const json = await req.json()
expect(json).not.toEqual(initialJson)
})
})
it('should not cache correctly with POST method request init', async () => { it('should not cache correctly with POST method request init', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
next.url, next.url,
......
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
export async function GET() {
const cookieData = cookies()
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
headers: {
Authorization: 'Bearer token',
},
}
).then((res) => res.text())
console.log('has cookie data', !!cookieData)
return NextResponse.json({ random: data })
}
import { NextResponse } from 'next/server'
export async function GET(request) {
const requestCookies = request.cookies
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
headers: {
Authorization: 'Bearer token',
},
}
).then((res) => res.text())
console.log('has cookie data', !!requestCookies)
return NextResponse.json({ random: data })
}
...@@ -163,10 +163,10 @@ createNextDescribe( ...@@ -163,10 +163,10 @@ createNextDescribe(
if (!isNextDev) { if (!isNextDev) {
it('should track dynamic apis when rendering app routes', async () => { it('should track dynamic apis when rendering app routes', async () => {
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
`Caught Error: Dynamic server usage: Route /routes/url couldn't be rendered statically because it accessed \`request.url\`.` `Caught Error: Dynamic server usage: Route /routes/url couldn't be rendered statically because it used \`request.url\`.`
) )
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
`Caught Error: Dynamic server usage: Route /routes/next-url couldn't be rendered statically because it accessed \`nextUrl.toString\`.` `Caught Error: Dynamic server usage: Route /routes/next-url couldn't be rendered statically because it used \`nextUrl.toString\`.`
) )
}) })
} }
...@@ -239,10 +239,10 @@ createNextDescribe( ...@@ -239,10 +239,10 @@ createNextDescribe(
'Error: Route /search with `dynamic = "error"` couldn\'t be rendered statically because it used `searchParams`.' 'Error: Route /search with `dynamic = "error"` couldn\'t be rendered statically because it used `searchParams`.'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /routes/form-data/error with `dynamic = "error"` couldn\'t be rendered statically because it accessed `request.formData`.' 'Error: Route /routes/form-data/error with `dynamic = "error"` couldn\'t be rendered statically because it used `request.formData`.'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /routes/next-url/error with `dynamic = "error"` couldn\'t be rendered statically because it accessed `nextUrl.toString`.' 'Error: Route /routes/next-url/error with `dynamic = "error"` couldn\'t be rendered statically because it used `nextUrl.toString`.'
) )
}) })
} }
......
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