Unverified Commit 3be4ec65 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

bugfix: revalidate + force-cache should work (#72347)

When using `fetch('', { cache: 'force-cache', { next: { revalidate: 5 } })` on a page that bailed out of ISR, we were effectively ignoring both values and treating the fetch as uncacheable, for several reasons:

- When `cache` and `revalidate` are both specified, we were assuming any combination of the two values is invalid, and we'd unset both the revalidate & fetch configs. In actuality these two properties are only problematic when they convey different caching semantics. This check was modified to instead only warn & unset on conflicting values, specifically `cache: 'no-store` and `revalidate: >0` as well as `cache: 'force-cache'` and `revalidate: 0`.
- When `force-dynamic` was set, we'd opt into no-store behavior on the fetch even if the fetch had an explicit cache config, which is incorrect.

Fixes #71881
parent 4373f96f
...@@ -298,31 +298,54 @@ export function createPatchedFetcher( ...@@ -298,31 +298,54 @@ export function createPatchedFetcher(
typeof currentFetchCacheConfig === 'string' && typeof currentFetchCacheConfig === 'string' &&
typeof currentFetchRevalidate !== 'undefined' typeof currentFetchRevalidate !== 'undefined'
) { ) {
// when providing fetch with a Request input, it'll automatically set a cache value of 'default' // If the revalidate value conflicts with the cache value, we should warn the user and unset the conflicting values.
// we only want to warn if the user is explicitly setting a cache value const isConflictingRevalidate =
if (!(isRequestInput && currentFetchCacheConfig === 'default')) { // revalidate: 0 and cache: force-cache
(currentFetchCacheConfig === 'force-cache' &&
currentFetchRevalidate === 0) ||
// revalidate: >0 or revalidate: false and cache: no-store
(currentFetchCacheConfig === 'no-store' &&
(currentFetchRevalidate > 0 || currentFetchRevalidate === false))
if (isConflictingRevalidate) {
cacheWarning = `Specified "cache: ${currentFetchCacheConfig}" and "revalidate: ${currentFetchRevalidate}", only one should be specified.` cacheWarning = `Specified "cache: ${currentFetchCacheConfig}" and "revalidate: ${currentFetchRevalidate}", only one should be specified.`
}
currentFetchCacheConfig = undefined currentFetchCacheConfig = undefined
currentFetchRevalidate = undefined
}
} }
if (currentFetchCacheConfig === 'force-cache') { const hasExplicitFetchCacheOptOut =
currentFetchRevalidate = false // fetch config itself signals not to cache
} else if ( currentFetchCacheConfig === 'no-cache' ||
// if we are inside of "use cache"/"unstable_cache"
// we shouldn't set the revalidate to 0 as it's overridden
// by the cache context
workUnitStore?.type !== 'cache' &&
(currentFetchCacheConfig === 'no-cache' ||
currentFetchCacheConfig === 'no-store' || currentFetchCacheConfig === 'no-store' ||
// the fetch isn't explicitly caching and the segment level cache config signals not to cache
// note: `pageFetchCacheMode` is also set by being in an unstable_cache context.
pageFetchCacheMode === 'force-no-store' || pageFetchCacheMode === 'force-no-store' ||
pageFetchCacheMode === 'only-no-store' || pageFetchCacheMode === 'only-no-store'
// If no explicit fetch cache mode is set, but dynamic = `force-dynamic` is set, // If no explicit fetch cache mode is set, but dynamic = `force-dynamic` is set,
// we shouldn't consider caching the fetch. This is because the `dynamic` cache // we shouldn't consider caching the fetch. This is because the `dynamic` cache
// is considered a "top-level" cache mode, whereas something like `fetchCache` is more // is considered a "top-level" cache mode, whereas something like `fetchCache` is more
// fine-grained. Top-level modes are responsible for setting reasonable defaults for the // fine-grained. Top-level modes are responsible for setting reasonable defaults for the
// other configurations. // other configurations.
(!pageFetchCacheMode && workStore.forceDynamic)) const noFetchConfigAndForceDynamic =
!pageFetchCacheMode &&
!currentFetchCacheConfig &&
workStore.forceDynamic
if (
// force-cache was specified without a revalidate value. We set the revalidate value to false
// which will signal the cache to not revalidate
currentFetchCacheConfig === 'force-cache' &&
typeof currentFetchRevalidate === 'undefined'
) {
currentFetchRevalidate = false
} else if (
// if we are inside of "use cache"/"unstable_cache"
// we shouldn't set the revalidate to 0 as it's overridden
// by the cache context
workUnitStore?.type !== 'cache' &&
(hasExplicitFetchCacheOptOut || noFetchConfigAndForceDynamic)
) { ) {
currentFetchRevalidate = 0 currentFetchRevalidate = 0
} }
......
...@@ -835,6 +835,8 @@ describe('app-dir static/dynamic handling', () => { ...@@ -835,6 +835,8 @@ describe('app-dir static/dynamic handling', () => {
"fetch-no-cache/page_client-reference-manifest.js", "fetch-no-cache/page_client-reference-manifest.js",
"flight/[slug]/[slug2]/page.js", "flight/[slug]/[slug2]/page.js",
"flight/[slug]/[slug2]/page_client-reference-manifest.js", "flight/[slug]/[slug2]/page_client-reference-manifest.js",
"force-cache-revalidate/page.js",
"force-cache-revalidate/page_client-reference-manifest.js",
"force-cache.html", "force-cache.html",
"force-cache.rsc", "force-cache.rsc",
"force-cache/large-data/page.js", "force-cache/large-data/page.js",
...@@ -2790,7 +2792,6 @@ describe('app-dir static/dynamic handling', () => { ...@@ -2790,7 +2792,6 @@ describe('app-dir static/dynamic handling', () => {
let prevHtml = await res.text() let prevHtml = await res.text()
let prev$ = cheerio.load(prevHtml) let prev$ = cheerio.load(prevHtml)
const cliOutputLength = next.cliOutput.length
await retry(async () => { await retry(async () => {
const curRes = await next.fetch('/force-cache') const curRes = await next.fetch('/force-cache')
...@@ -2813,18 +2814,42 @@ describe('app-dir static/dynamic handling', () => { ...@@ -2813,18 +2814,42 @@ describe('app-dir static/dynamic handling', () => {
prev$('#data-auto-cache').text() prev$('#data-auto-cache').text()
) )
}) })
})
if (isNextDev) { it('should cache correctly for cache: "force-cache" and "revalidate"', async () => {
await retry(() => { let prevValue: string | undefined
const cliOutput = next.cliOutput await retry(async () => {
.slice(cliOutputLength) const res = await next.fetch('/force-cache-revalidate')
.replace(/in \d+ms/g, 'in 0ms') // stub request durations expect(res.status).toBe(200)
let prevHtml = await res.text()
let prev$ = cheerio.load(prevHtml)
const curRes = await next.fetch('/force-cache-revalidate')
expect(curRes.status).toBe(200)
const curHtml = await curRes.text()
const cur$ = cheerio.load(curHtml)
expect(cur$('#data-force-cache').text()).toBe(
prev$('#data-force-cache').text()
)
expect(stripAnsi(cliOutput)).toContain(` prevValue = cur$('#data-force-cache').text()
│ GET https://next-data-api-en../api/random?d4 200 in 0ms (cache hit) })
│ │ ⚠ Specified "cache: force-cache" and "revalidate: 3", only one should be specified.`)
// wait for revalidation
await waitFor(3000)
await retry(async () => {
const curRes = await next.fetch('/force-cache-revalidate')
expect(curRes.status).toBe(200)
const curHtml = await curRes.text()
const cur$ = cheerio.load(curHtml)
expect(cur$('#data-force-cache').text()).not.toBe(prevValue)
}) })
}
}) })
it('should cache correctly for cache: no-store', async () => { it('should cache correctly for cache: no-store', async () => {
......
// we want to bail out of ISR, but still leverage fetch caching
export const dynamic = 'force-dynamic'
export default async function Page() {
const dataForceCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?b2',
{
cache: 'force-cache',
next: {
revalidate: 3,
},
}
).then((res) => res.text())
return (
<>
<p>/force-cache-revalidate</p>
<p id="data-force-cache">
"cache: no-cache, revalidate: 3" {dataForceCache}
</p>
</>
)
}
...@@ -7,7 +7,7 @@ export default async function Page() { ...@@ -7,7 +7,7 @@ export default async function Page() {
), ),
{ {
next: { next: {
revalidate: 3, revalidate: 0,
}, },
} }
) )
...@@ -21,7 +21,7 @@ export default async function Page() { ...@@ -21,7 +21,7 @@ export default async function Page() {
), ),
{ {
next: { next: {
revalidate: 3, revalidate: 0,
}, },
} }
) )
...@@ -30,11 +30,35 @@ export default async function Page() { ...@@ -30,11 +30,35 @@ export default async function Page() {
'https://next-data-api-endpoint.vercel.app/api/random?request-string', 'https://next-data-api-endpoint.vercel.app/api/random?request-string',
{ {
next: { next: {
revalidate: 3, revalidate: 0,
}, },
cache: 'force-cache', cache: 'force-cache',
} }
) )
await fetch(
new Request(
'https://next-data-api-endpoint.vercel.app/api/random?no-store-request-input-cache-override',
{
cache: 'no-store',
}
),
{
next: {
revalidate: 3,
},
}
)
await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?no-store-request-string',
{
next: {
revalidate: 3,
},
cache: 'no-store',
}
)
return <div>Hello World!</div> return <div>Hello World!</div>
} }
...@@ -21,11 +21,12 @@ describe('app-dir - fetch warnings', () => { ...@@ -21,11 +21,12 @@ describe('app-dir - fetch warnings', () => {
}) })
if (isNextDev) { if (isNextDev) {
describe('force-cache and revalidate: 0', () => {
it('should log when request input is a string', async () => { it('should log when request input is a string', async () => {
await retry(() => { await retry(() => {
expect(next.cliOutput).toInclude(` expect(next.cliOutput).toInclude(`
│ GET https://next-data-api-endpoint.vercel.app/api/random?request-string │ GET https://next-data-api-endpoint.vercel.app/api/random?request-string
│ │ ⚠ Specified "cache: force-cache" and "revalidate: 3", only one should be specified.`) │ │ ⚠ Specified "cache: force-cache" and "revalidate: 0", only one should be specified.`)
}) })
}) })
...@@ -33,15 +34,34 @@ describe('app-dir - fetch warnings', () => { ...@@ -33,15 +34,34 @@ describe('app-dir - fetch warnings', () => {
await retry(() => { await retry(() => {
expect(next.cliOutput).toInclude(` expect(next.cliOutput).toInclude(`
│ GET https://next-data-api-endpoint.vercel.app/api/random?request-input-cache-override │ GET https://next-data-api-endpoint.vercel.app/api/random?request-input-cache-override
│ │ ⚠ Specified "cache: force-cache" and "revalidate: 3", only one should be specified.`) │ │ ⚠ Specified "cache: force-cache" and "revalidate: 0", only one should be specified.`)
}) })
}) })
it('should not log when overriding cache within the Request object', async () => { it('should not log when not overriding cache within the Request object', async () => {
await retry(() => { await retry(() => {
expect(next.cliOutput).not.toInclude(` expect(next.cliOutput).not.toInclude(`
│ GET https://next-data-api-endpoint.vercel.app/api/random?request-input │ GET https://next-data-api-endpoint.vercel.app/api/random?request-input
│ │ ⚠ Specified "cache: force-cache" and "revalidate: 3", only one should be specified.`) │ │ ⚠ Specified "cache:`)
})
})
})
describe('no-store and revalidate > 0', () => {
it('should log when request input is a string', async () => {
await retry(() => {
expect(next.cliOutput).toInclude(`
│ GET https://next-data-api-endpoint.vercel.app/api/random?no-store-request-string
│ │ ⚠ Specified "cache: no-store" and "revalidate: 3", only one should be specified.`)
})
})
it('should log when request input is a Request instance', async () => {
await retry(() => {
expect(next.cliOutput).toInclude(`
│ GET https://next-data-api-endpoint.vercel.app/api/random?no-store-request-input-cache-override
│ │ ⚠ Specified "cache: no-store" and "revalidate: 3", only one should be specified.`)
})
}) })
}) })
} else { } else {
......
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