Unverified Commit 17b09f82 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix on-demand revalidation with `"use cache"` in dev mode (#76122)

This PR is a follow-up to #76100 that enables on-demand revalidation via
an API route in development mode. This is accomplished by implementing
three changes:
1. We need to forward the user cookies, including the
`__next_hmr_refresh_hash__` value, which is required to generate the
same cache key _during_ the revalidation as _before_ and, more
importantly, _after_ the revalidation. Otherwise the revalidated cache
entries will use a different cache key (without the refresh hash), and
on subsequent page reload, the stale cached data would still be shown
(using the cache key with refresh hash).
2. When checking if a `revalidate()` call succeeded, we allow `200`
responses in general, and only check the `'x-nextjs-cache'` header for
`404` response. This matches the historic intent of the feature.
([x-ref-1](https://github.com/vercel/next.js/pull/36108/files#diff-8d464ed8b3d6ed08deabeaa05180900c38f8943d75368798861d1734103512fcR338-R342),
[x-ref-2](https://github.com/vercel/next.js/pull/34826/files#diff-8d464ed8b3d6ed08deabeaa05180900c38f8943d75368798861d1734103512fcR318-R324)).
3. The `isOnDemandRevalidate` status is now also set for non-`isSSG`
pages, based on the `'x-prerender-revalidate'` header. This matches the
logic in the incremental cache handler, which enables cache revalidation
in dev mode when using `unstable_cache`.
parent 6b0724ba
......@@ -43,6 +43,7 @@ type ApiContext = __ApiPreviewProps & {
hostname?: string
revalidate?: RevalidateFn
multiZoneDraftMode?: boolean
dev: boolean
}
function getMaxContentLength(responseLimit?: ResponseLimit) {
......@@ -271,11 +272,16 @@ async function revalidate(
}
const allowedRevalidateHeaderKeys = [
...(context.allowedRevalidateHeaderKeys || []),
...(context.trustHostHeader
? ['cookie', 'x-vercel-protection-bypass']
: []),
]
if (context.trustHostHeader || context.dev) {
allowedRevalidateHeaderKeys.push('cookie')
}
if (context.trustHostHeader) {
allowedRevalidateHeaderKeys.push('x-vercel-protection-bypass')
}
for (const key of Object.keys(req.headers)) {
if (allowedRevalidateHeaderKeys.includes(key)) {
revalidateHeaders[key] = req.headers[key] as string
......@@ -296,6 +302,7 @@ async function revalidate(
if (
cacheHeader?.toUpperCase() !== 'REVALIDATED' &&
res.status !== 200 &&
!(res.status === 404 && opts.unstable_onlyGenerated)
) {
throw new Error(`Invalid response ${res.status}`)
......
......@@ -2328,13 +2328,8 @@ export default abstract class Server<
stripFlightHeaders(req.headers)
}
let isOnDemandRevalidate = false
let revalidateOnlyGenerated = false
if (isSSG) {
;({ isOnDemandRevalidate, revalidateOnlyGenerated } =
checkIsOnDemandRevalidate(req, this.renderOpts.previewProps))
}
let { isOnDemandRevalidate, revalidateOnlyGenerated } =
checkIsOnDemandRevalidate(req, this.renderOpts.previewProps)
if (isSSG && this.minimalMode && req.headers[MATCHED_PATH_HEADER]) {
// the url value is already correct when the matched-path header is set
......
......@@ -75,6 +75,7 @@ export class DevBundlerService {
if (
mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&
mocked.res.statusCode !== 200 &&
!(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)
) {
throw new Error(`Invalid response ${mocked.res.statusCode}`)
......
......@@ -1224,6 +1224,7 @@ export default class NextNodeServer extends BaseServer<
if (
mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&
mocked.res.statusCode !== 200 &&
!(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)
) {
throw new Error(`Invalid response ${mocked.res.statusCode}`)
......
......@@ -154,6 +154,7 @@ export class PagesAPIRouteModule extends RouteModule<
allowedRevalidateHeaderKeys: context.allowedRevalidateHeaderKeys,
hostname: context.hostname,
multiZoneDraftMode: context.multiZoneDraftMode,
dev: context.dev,
},
context.minimalMode,
context.dev,
......
'use client'
import { useTransition } from 'react'
export function RevalidateButtons({
revalidatePath,
}: {
revalidatePath: () => Promise<void>
}) {
const [isPending, startTransition] = useTransition()
return (
<form>
<button id="revalidate-path" formAction={revalidatePath}>
......@@ -12,9 +16,12 @@ export function RevalidateButtons({
</button>{' '}
<button
id="revalidate-api-route"
disabled={isPending}
formAction={async () => {
await fetch('/api/revalidate?path=/on-demand-revalidate', {
method: 'POST',
startTransition(async () => {
await fetch('/api/revalidate?path=/on-demand-revalidate', {
method: 'POST',
})
})
}}
>
......
......@@ -303,31 +303,30 @@ describe('use-cache', () => {
})
}
if (isNextStart) {
// res.revalidate does not work in dev mode
it('should revalidate caches during on-demand revalidation', async () => {
const browser = await next.browser('/on-demand-revalidate')
const initial = await browser.elementById('value').text()
it('should revalidate caches during on-demand revalidation', async () => {
const browser = await next.browser('/on-demand-revalidate')
const initial = await browser.elementById('value').text()
// Bust the ISR cache first to populate the "use cache" in-memory cache for
// the subsequent on-demand revalidation.
await browser.elementById('revalidate-path').click()
// Bust the ISR cache first to populate the "use cache" in-memory cache for
// the subsequent on-demand revalidation.
await browser.elementById('revalidate-path').click()
await retry(async () => {
expect(await browser.elementById('value').text()).not.toBe(initial)
})
await retry(async () => {
expect(await browser.elementById('value').text()).not.toBe(initial)
})
const value = await browser.elementById('value').text()
const value = await browser.elementById('value').text()
await browser.elementById('revalidate-api-route').click()
await browser.waitForIdleNetwork()
await browser.elementById('revalidate-api-route').click()
await browser.waitForElementByCss('#revalidate-api-route:enabled')
await retry(async () => {
await browser.refresh()
expect(await browser.elementById('value').text()).not.toBe(value)
})
await retry(async () => {
await browser.refresh()
expect(await browser.elementById('value').text()).not.toBe(value)
})
})
if (isNextStart) {
it('should prerender fully cacheable pages as static HTML', async () => {
const prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
......
......@@ -1877,7 +1877,6 @@ describe('Prerender', () => {
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ revalidated: false })
expect(stripAnsi(next.cliOutput)).not.toContain('hasHeader')
})
......
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