Unverified Commit 734fa1df authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

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 34c2a05d
...@@ -154,7 +154,7 @@ export function trackDynamicDataAccessed( ...@@ -154,7 +154,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
......
...@@ -374,11 +374,15 @@ function createPatchedFetcher( ...@@ -374,11 +374,15 @@ function createPatchedFetcher(
getRequestMeta('method')?.toLowerCase() || 'get' getRequestMeta('method')?.toLowerCase() || 'get'
) )
// if there are authorized headers or a POST method and /**
// dynamic data usage was present above the tree we bail * We automatically disable fetch caching under the following conditions:
// e.g. if cookies() is used before an authed/POST fetch * - Fetch cache configs are not set. Specifically:
// or no user provided fetch cache config or revalidate * - A page fetch cache mode is not set (export const fetchCache=...)
// is provided we don't cache * - A fetch cache mode is not set in the fetch call (fetch(url, { cache: ... }))
* - A fetch revalidate value is not set in the fetch call (fetch(url, { revalidate: ... }))
* - OR the fetch comes after a configuration that triggered dynamic rendering (e.g., reading cookies())
* and the fetch was considered uncacheable (e.g., POST method or has authorization headers)
*/
const autoNoCache = const autoNoCache =
// this condition is hit for null/undefined // this condition is hit for null/undefined
// eslint-disable-next-line eqeqeq // eslint-disable-next-line eqeqeq
......
...@@ -154,6 +154,44 @@ describe('app-dir static/dynamic handling', () => { ...@@ -154,6 +154,44 @@ describe('app-dir static/dynamic handling', () => {
expect($2('#data').text()).toBeTruthy() expect($2('#data').text()).toBeTruthy()
expect($2('#data').text()).not.toBe(initData) expect($2('#data').text()).not.toBe(initData)
}) })
// Check route handlers as well
const initFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/no-fetch-cache/route')
).json()
await retry(async () => {
const newFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/no-fetch-cache/route')
).json()
expect(newFetchData).toBeTruthy()
expect(newFetchData).not.toEqual(initFetchData)
})
})
it('force-dynamic should supercede a "default" cache value', async () => {
const $ = await next.render$('/force-dynamic-fetch-cache/default-cache')
const initData = $('#data').text()
await retry(async () => {
const $2 = await next.render$(
'/force-dynamic-fetch-cache/default-cache'
)
expect($2('#data').text()).toBeTruthy()
expect($2('#data').text()).not.toBe(initData)
})
// Check route handlers as well
const initFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/default-cache/route')
).json()
await retry(async () => {
const newFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/default-cache/route')
).json()
expect(newFetchData).toBeTruthy()
expect(newFetchData).not.toEqual(initFetchData)
})
}) })
it('fetchCache config should supercede dynamic config when force-dynamic is used', async () => { it('fetchCache config should supercede dynamic config when force-dynamic is used', async () => {
...@@ -168,6 +206,42 @@ describe('app-dir static/dynamic handling', () => { ...@@ -168,6 +206,42 @@ describe('app-dir static/dynamic handling', () => {
expect($2('#data').text()).toBeTruthy() expect($2('#data').text()).toBeTruthy()
expect($2('#data').text()).toBe(initData) expect($2('#data').text()).toBe(initData)
}) })
// Check route handlers as well
const initFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/with-fetch-cache/route')
).json()
await retry(async () => {
const newFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/with-fetch-cache/route')
).json()
expect(newFetchData).toBeTruthy()
expect(newFetchData).toEqual(initFetchData)
})
})
it('fetch `cache` should supercede dynamic config when force-dynamic is used', async () => {
const $ = await next.render$('/force-dynamic-fetch-cache/force-cache')
const initData = $('#data').text()
await retry(async () => {
const $2 = await next.render$('/force-dynamic-fetch-cache/force-cache')
expect($2('#data').text()).toBeTruthy()
expect($2('#data').text()).toBe(initData)
})
// Check route handlers as well
const initFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/force-cache/route')
).json()
await retry(async () => {
const newFetchData = await (
await next.fetch('/force-dynamic-fetch-cache/force-cache/route')
).json()
expect(newFetchData).toBeTruthy()
expect(newFetchData).toEqual(initFetchData)
})
}) })
if (!process.env.CUSTOM_CACHE_HANDLER) { if (!process.env.CUSTOM_CACHE_HANDLER) {
...@@ -725,10 +799,18 @@ describe('app-dir static/dynamic handling', () => { ...@@ -725,10 +799,18 @@ describe('app-dir static/dynamic handling', () => {
"force-cache/page_client-reference-manifest.js", "force-cache/page_client-reference-manifest.js",
"force-dynamic-catch-all/[slug]/[[...id]]/page.js", "force-dynamic-catch-all/[slug]/[[...id]]/page.js",
"force-dynamic-catch-all/[slug]/[[...id]]/page_client-reference-manifest.js", "force-dynamic-catch-all/[slug]/[[...id]]/page_client-reference-manifest.js",
"force-dynamic-fetch-cache/default-cache/page.js",
"force-dynamic-fetch-cache/default-cache/page_client-reference-manifest.js",
"force-dynamic-fetch-cache/default-cache/route/route.js",
"force-dynamic-fetch-cache/force-cache/page.js",
"force-dynamic-fetch-cache/force-cache/page_client-reference-manifest.js",
"force-dynamic-fetch-cache/force-cache/route/route.js",
"force-dynamic-fetch-cache/no-fetch-cache/page.js", "force-dynamic-fetch-cache/no-fetch-cache/page.js",
"force-dynamic-fetch-cache/no-fetch-cache/page_client-reference-manifest.js", "force-dynamic-fetch-cache/no-fetch-cache/page_client-reference-manifest.js",
"force-dynamic-fetch-cache/no-fetch-cache/route/route.js",
"force-dynamic-fetch-cache/with-fetch-cache/page.js", "force-dynamic-fetch-cache/with-fetch-cache/page.js",
"force-dynamic-fetch-cache/with-fetch-cache/page_client-reference-manifest.js", "force-dynamic-fetch-cache/with-fetch-cache/page_client-reference-manifest.js",
"force-dynamic-fetch-cache/with-fetch-cache/route/route.js",
"force-dynamic-no-prerender/[id]/page.js", "force-dynamic-no-prerender/[id]/page.js",
"force-dynamic-no-prerender/[id]/page_client-reference-manifest.js", "force-dynamic-no-prerender/[id]/page_client-reference-manifest.js",
"force-dynamic-prerender/[slug]/page.js", "force-dynamic-prerender/[slug]/page.js",
...@@ -896,6 +978,8 @@ describe('app-dir static/dynamic handling', () => { ...@@ -896,6 +978,8 @@ describe('app-dir static/dynamic handling', () => {
"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",
...@@ -2104,6 +2188,10 @@ describe('app-dir static/dynamic handling', () => { ...@@ -2104,6 +2188,10 @@ describe('app-dir static/dynamic handling', () => {
expect(cur$('#data-revalidate-and-fetch-cache').text()).toBe( expect(cur$('#data-revalidate-and-fetch-cache').text()).toBe(
prev$('#data-revalidate-and-fetch-cache').text() prev$('#data-revalidate-and-fetch-cache').text()
) )
expect(cur$('#data-auto-cache').text()).not.toBe(
prev$('data-auto-cache').text()
)
} finally { } finally {
prevHtml = curHtml prevHtml = curHtml
prev$ = cur$ prev$ = cur$
...@@ -2562,6 +2650,38 @@ describe('app-dir static/dynamic handling', () => { ...@@ -2562,6 +2650,38 @@ describe('app-dir static/dynamic handling', () => {
}, '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,
......
export const dynamic = 'force-dynamic'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'default' }
).then((res) => res.text())
return (
<>
<p id="page">/force-dynamic-fetch-cache/default-cache</p>
<p id="data">{data}</p>
</>
)
}
import { NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export async function GET() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'default' }
).then((res) => res.text())
return NextResponse.json({ random: data })
}
export const dynamic = 'force-dynamic'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache' }
).then((res) => res.text())
return (
<>
<p id="page">/force-dynamic-fetch-cache/force-cache</p>
<p id="data">{data}</p>
</>
)
}
import { NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export async function GET() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache' }
).then((res) => res.text())
return NextResponse.json({ random: data })
}
import { NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export async function GET() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return NextResponse.json({ random: data })
}
import { NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export const fetchCache = 'force-cache'
export async function GET() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return NextResponse.json({ random: data })
}
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 })
}
...@@ -166,10 +166,10 @@ describe('dynamic-data', () => { ...@@ -166,10 +166,10 @@ describe('dynamic-data', () => {
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\`.`
) )
}) })
} }
...@@ -244,10 +244,10 @@ describe('dynamic-data with dynamic = "error"', () => { ...@@ -244,10 +244,10 @@ describe('dynamic-data with dynamic = "error"', () => {
'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