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 & { ...@@ -43,6 +43,7 @@ type ApiContext = __ApiPreviewProps & {
hostname?: string hostname?: string
revalidate?: RevalidateFn revalidate?: RevalidateFn
multiZoneDraftMode?: boolean multiZoneDraftMode?: boolean
dev: boolean
} }
function getMaxContentLength(responseLimit?: ResponseLimit) { function getMaxContentLength(responseLimit?: ResponseLimit) {
...@@ -271,11 +272,16 @@ async function revalidate( ...@@ -271,11 +272,16 @@ async function revalidate(
} }
const allowedRevalidateHeaderKeys = [ const allowedRevalidateHeaderKeys = [
...(context.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)) { for (const key of Object.keys(req.headers)) {
if (allowedRevalidateHeaderKeys.includes(key)) { if (allowedRevalidateHeaderKeys.includes(key)) {
revalidateHeaders[key] = req.headers[key] as string revalidateHeaders[key] = req.headers[key] as string
...@@ -296,6 +302,7 @@ async function revalidate( ...@@ -296,6 +302,7 @@ async function revalidate(
if ( if (
cacheHeader?.toUpperCase() !== 'REVALIDATED' && cacheHeader?.toUpperCase() !== 'REVALIDATED' &&
res.status !== 200 &&
!(res.status === 404 && opts.unstable_onlyGenerated) !(res.status === 404 && opts.unstable_onlyGenerated)
) { ) {
throw new Error(`Invalid response ${res.status}`) throw new Error(`Invalid response ${res.status}`)
......
...@@ -2328,13 +2328,8 @@ export default abstract class Server< ...@@ -2328,13 +2328,8 @@ export default abstract class Server<
stripFlightHeaders(req.headers) stripFlightHeaders(req.headers)
} }
let isOnDemandRevalidate = false let { isOnDemandRevalidate, revalidateOnlyGenerated } =
let revalidateOnlyGenerated = false checkIsOnDemandRevalidate(req, this.renderOpts.previewProps)
if (isSSG) {
;({ isOnDemandRevalidate, revalidateOnlyGenerated } =
checkIsOnDemandRevalidate(req, this.renderOpts.previewProps))
}
if (isSSG && this.minimalMode && req.headers[MATCHED_PATH_HEADER]) { if (isSSG && this.minimalMode && req.headers[MATCHED_PATH_HEADER]) {
// the url value is already correct when the matched-path header is set // the url value is already correct when the matched-path header is set
......
...@@ -75,6 +75,7 @@ export class DevBundlerService { ...@@ -75,6 +75,7 @@ export class DevBundlerService {
if ( if (
mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' && mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&
mocked.res.statusCode !== 200 &&
!(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated) !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)
) { ) {
throw new Error(`Invalid response ${mocked.res.statusCode}`) throw new Error(`Invalid response ${mocked.res.statusCode}`)
......
...@@ -1224,6 +1224,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1224,6 +1224,7 @@ export default class NextNodeServer extends BaseServer<
if ( if (
mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' && mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&
mocked.res.statusCode !== 200 &&
!(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated) !(mocked.res.statusCode === 404 && opts.unstable_onlyGenerated)
) { ) {
throw new Error(`Invalid response ${mocked.res.statusCode}`) throw new Error(`Invalid response ${mocked.res.statusCode}`)
......
...@@ -154,6 +154,7 @@ export class PagesAPIRouteModule extends RouteModule< ...@@ -154,6 +154,7 @@ export class PagesAPIRouteModule extends RouteModule<
allowedRevalidateHeaderKeys: context.allowedRevalidateHeaderKeys, allowedRevalidateHeaderKeys: context.allowedRevalidateHeaderKeys,
hostname: context.hostname, hostname: context.hostname,
multiZoneDraftMode: context.multiZoneDraftMode, multiZoneDraftMode: context.multiZoneDraftMode,
dev: context.dev,
}, },
context.minimalMode, context.minimalMode,
context.dev, context.dev,
......
'use client' 'use client'
import { useTransition } from 'react'
export function RevalidateButtons({ export function RevalidateButtons({
revalidatePath, revalidatePath,
}: { }: {
revalidatePath: () => Promise<void> revalidatePath: () => Promise<void>
}) { }) {
const [isPending, startTransition] = useTransition()
return ( return (
<form> <form>
<button id="revalidate-path" formAction={revalidatePath}> <button id="revalidate-path" formAction={revalidatePath}>
...@@ -12,9 +16,12 @@ export function RevalidateButtons({ ...@@ -12,9 +16,12 @@ export function RevalidateButtons({
</button>{' '} </button>{' '}
<button <button
id="revalidate-api-route" id="revalidate-api-route"
disabled={isPending}
formAction={async () => { formAction={async () => {
await fetch('/api/revalidate?path=/on-demand-revalidate', { startTransition(async () => {
method: 'POST', await fetch('/api/revalidate?path=/on-demand-revalidate', {
method: 'POST',
})
}) })
}} }}
> >
......
...@@ -303,31 +303,30 @@ describe('use-cache', () => { ...@@ -303,31 +303,30 @@ describe('use-cache', () => {
}) })
} }
if (isNextStart) { it('should revalidate caches during on-demand revalidation', async () => {
// res.revalidate does not work in dev mode const browser = await next.browser('/on-demand-revalidate')
it('should revalidate caches during on-demand revalidation', async () => { const initial = await browser.elementById('value').text()
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 // Bust the ISR cache first to populate the "use cache" in-memory cache for
// the subsequent on-demand revalidation. // the subsequent on-demand revalidation.
await browser.elementById('revalidate-path').click() await browser.elementById('revalidate-path').click()
await retry(async () => { await retry(async () => {
expect(await browser.elementById('value').text()).not.toBe(initial) 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.elementById('revalidate-api-route').click()
await browser.waitForIdleNetwork() await browser.waitForElementByCss('#revalidate-api-route:enabled')
await retry(async () => { await retry(async () => {
await browser.refresh() await browser.refresh()
expect(await browser.elementById('value').text()).not.toBe(value) expect(await browser.elementById('value').text()).not.toBe(value)
})
}) })
})
if (isNextStart) {
it('should prerender fully cacheable pages as static HTML', async () => { it('should prerender fully cacheable pages as static HTML', async () => {
const prerenderManifest = JSON.parse( const prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json') await next.readFile('.next/prerender-manifest.json')
......
...@@ -1877,7 +1877,6 @@ describe('Prerender', () => { ...@@ -1877,7 +1877,6 @@ describe('Prerender', () => {
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.json()).toEqual({ revalidated: false })
expect(stripAnsi(next.cliOutput)).not.toContain('hasHeader') 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