Unverified Commit 754c6480 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Invalidate client cache when cookies have changed in Server Actions (#51290)

Similar to tags and paths, when `cookies().set()` is called we have to
invalidate the client router cache as well so routes with
`cookies().get()` will not holding the stale data. This is critical for
auth and other scenarios.

In the future we can have an optimization to only invalidate routes that
actually rely on cookies, similar to paths.
parent d27cda21
...@@ -32,6 +32,7 @@ type FetchServerActionResult = { ...@@ -32,6 +32,7 @@ type FetchServerActionResult = {
actionFlightData?: FlightData | undefined | null actionFlightData?: FlightData | undefined | null
revalidatedParts: { revalidatedParts: {
tag: boolean tag: boolean
cookie: boolean
paths: string[] paths: string[]
} }
} }
...@@ -67,16 +68,18 @@ async function fetchServerAction( ...@@ -67,16 +68,18 @@ async function fetchServerAction(
let revalidatedParts: FetchServerActionResult['revalidatedParts'] let revalidatedParts: FetchServerActionResult['revalidatedParts']
try { try {
const revalidatedHeader = JSON.parse( const revalidatedHeader = JSON.parse(
res.headers.get('x-action-revalidated') || '[0,[]]' res.headers.get('x-action-revalidated') || '[[],0,0]'
) )
revalidatedParts = { revalidatedParts = {
tag: !!revalidatedHeader[0], paths: revalidatedHeader[0] || [],
paths: revalidatedHeader[1] || [], tag: !!revalidatedHeader[1],
cookie: revalidatedHeader[2],
} }
} catch (e) { } catch (e) {
revalidatedParts = { revalidatedParts = {
tag: false,
paths: [], paths: [],
tag: false,
cookie: false,
} }
} }
...@@ -153,7 +156,7 @@ export function serverActionReducer( ...@@ -153,7 +156,7 @@ export function serverActionReducer(
// Invalidate the cache for the revalidated parts. This has to be done before the // Invalidate the cache for the revalidated parts. This has to be done before the
// cache is updated with the action's flight data again. // cache is updated with the action's flight data again.
if (revalidatedParts.tag) { if (revalidatedParts.tag || revalidatedParts.cookie) {
// Invalidate everything if the tag is set. // Invalidate everything if the tag is set.
state.prefetchCache.clear() state.prefetchCache.clear()
} else if (revalidatedParts.paths.length > 0) { } else if (revalidatedParts.paths.length > 0) {
......
...@@ -22,7 +22,11 @@ import { FlightRenderResult } from './flight-render-result' ...@@ -22,7 +22,11 @@ import { FlightRenderResult } from './flight-render-result'
import { ActionResult } from './types' import { ActionResult } from './types'
import { ActionAsyncStorage } from '../../client/components/action-async-storage' import { ActionAsyncStorage } from '../../client/components/action-async-storage'
import { filterReqHeaders, forbiddenHeaders } from '../lib/server-ipc/utils' import { filterReqHeaders, forbiddenHeaders } from '../lib/server-ipc/utils'
import { appendMutableCookies } from '../web/spec-extension/adapters/request-cookies' import {
appendMutableCookies,
getModifiedCookieValues,
} from '../web/spec-extension/adapters/request-cookies'
import { RequestStore } from '../../client/components/request-async-storage'
function nodeToWebReadableStream(nodeReadable: import('stream').Readable) { function nodeToWebReadableStream(nodeReadable: import('stream').Readable) {
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
...@@ -129,7 +133,13 @@ function fetchIPv4v6( ...@@ -129,7 +133,13 @@ function fetchIPv4v6(
async function addRevalidationHeader( async function addRevalidationHeader(
res: ServerResponse, res: ServerResponse,
staticGenerationStore: StaticGenerationStore {
staticGenerationStore,
requestStore,
}: {
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
}
) { ) {
await Promise.all(staticGenerationStore.pendingRevalidates || []) await Promise.all(staticGenerationStore.pendingRevalidates || [])
...@@ -137,7 +147,8 @@ async function addRevalidationHeader( ...@@ -137,7 +147,8 @@ async function addRevalidationHeader(
// client router cache as they may be stale. And if a path was revalidated, the // client router cache as they may be stale. And if a path was revalidated, the
// client needs to invalidate all subtrees below that path. // client needs to invalidate all subtrees below that path.
// To keep the header size small, we use a tuple of [isTagRevalidated ? 1 : 0, [paths]] // To keep the header size small, we use a tuple of
// [[revalidatedPaths], isTagRevalidated ? 1 : 0, isCookieRevalidated ? 1 : 0]
// instead of a JSON object. // instead of a JSON object.
// TODO-APP: Currently the prefetch cache doesn't have subtree information, // TODO-APP: Currently the prefetch cache doesn't have subtree information,
...@@ -145,9 +156,16 @@ async function addRevalidationHeader( ...@@ -145,9 +156,16 @@ async function addRevalidationHeader(
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple // TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty. // is always empty.
const isTagRevalidated = staticGenerationStore.revalidatedTags?.length ? 1 : 0
const isCookieRevalidated = getModifiedCookieValues(
requestStore.mutableCookies
).length
? 1
: 0
res.setHeader( res.setHeader(
'x-action-revalidated', 'x-action-revalidated',
JSON.stringify([staticGenerationStore.revalidatedTags?.length ? 1 : 0, []]) JSON.stringify([[], isTagRevalidated, isCookieRevalidated])
) )
} }
...@@ -226,6 +244,7 @@ export async function handleAction({ ...@@ -226,6 +244,7 @@ export async function handleAction({
serverActionsManifest, serverActionsManifest,
generateFlight, generateFlight,
staticGenerationStore, staticGenerationStore,
requestStore,
}: { }: {
req: IncomingMessage req: IncomingMessage
res: ServerResponse res: ServerResponse
...@@ -238,6 +257,7 @@ export async function handleAction({ ...@@ -238,6 +257,7 @@ export async function handleAction({
asNotFound?: boolean asNotFound?: boolean
}) => Promise<RenderResult> }) => Promise<RenderResult>
staticGenerationStore: StaticGenerationStore staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
}): Promise<undefined | RenderResult | 'not-found'> { }): Promise<undefined | RenderResult | 'not-found'> {
let actionId = req.headers[ACTION.toLowerCase()] as string let actionId = req.headers[ACTION.toLowerCase()] as string
const contentType = req.headers['content-type'] const contentType = req.headers['content-type']
...@@ -374,7 +394,10 @@ export async function handleAction({ ...@@ -374,7 +394,10 @@ export async function handleAction({
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { if (isFetchAction) {
await addRevalidationHeader(res, staticGenerationStore) await addRevalidationHeader(res, {
staticGenerationStore,
requestStore,
})
actionResult = await generateFlight({ actionResult = await generateFlight({
actionResult: Promise.resolve(returnVal), actionResult: Promise.resolve(returnVal),
...@@ -391,7 +414,10 @@ export async function handleAction({ ...@@ -391,7 +414,10 @@ export async function handleAction({
// if it's a fetch action, we don't want to mess with the status code // if it's a fetch action, we don't want to mess with the status code
// and we'll handle it on the client router // and we'll handle it on the client router
await addRevalidationHeader(res, staticGenerationStore) await addRevalidationHeader(res, {
staticGenerationStore,
requestStore,
})
if (isFetchAction) { if (isFetchAction) {
return createRedirectRenderResult( return createRedirectRenderResult(
...@@ -418,7 +444,10 @@ export async function handleAction({ ...@@ -418,7 +444,10 @@ export async function handleAction({
} else if (isNotFoundError(err)) { } else if (isNotFoundError(err)) {
res.statusCode = 404 res.statusCode = 404
await addRevalidationHeader(res, staticGenerationStore) await addRevalidationHeader(res, {
staticGenerationStore,
requestStore,
})
if (isFetchAction) { if (isFetchAction) {
const promise = Promise.reject(err) const promise = Promise.reject(err)
......
...@@ -224,6 +224,13 @@ export async function renderToHTMLOrFlight( ...@@ -224,6 +224,13 @@ export async function renderToHTMLOrFlight(
staticGenerationStore.fetchMetrics = [] staticGenerationStore.fetchMetrics = []
;(renderOpts as any).fetchMetrics = staticGenerationStore.fetchMetrics ;(renderOpts as any).fetchMetrics = staticGenerationStore.fetchMetrics
const requestStore = requestAsyncStorage.getStore()
if (!requestStore) {
throw new Error(
`Invariant: Render expects to have requestAsyncStorage, none found`
)
}
// don't modify original query object // don't modify original query object
query = { ...query } query = { ...query }
stripInternalQueries(query) stripInternalQueries(query)
...@@ -1617,6 +1624,7 @@ export async function renderToHTMLOrFlight( ...@@ -1617,6 +1624,7 @@ export async function renderToHTMLOrFlight(
serverActionsManifest, serverActionsManifest,
generateFlight, generateFlight,
staticGenerationStore, staticGenerationStore,
requestStore,
}) })
if (actionRequestResult === 'not-found') { if (actionRequestResult === 'not-found') {
......
...@@ -49,7 +49,9 @@ export class RequestCookiesAdapter { ...@@ -49,7 +49,9 @@ export class RequestCookiesAdapter {
const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies') const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies')
function getModifiedCookieValues(cookies: ResponseCookies): ResponseCookie[] { export function getModifiedCookieValues(
cookies: ResponseCookies
): ResponseCookie[] {
const modified: ResponseCookie[] | undefined = (cookies as unknown as any)[ const modified: ResponseCookie[] | undefined = (cookies as unknown as any)[
SYMBOL_MODIFY_COOKIE_VALUES SYMBOL_MODIFY_COOKIE_VALUES
] ]
......
...@@ -503,8 +503,65 @@ createNextDescribe( ...@@ -503,8 +503,65 @@ createNextDescribe(
}, 'success') }, 'success')
}) })
it('should revalidate when cookies.set is called in a client action', async () => {
const browser = await next.browser('/revalidate')
await browser.refresh()
let randomCookie
await check(async () => {
randomCookie = JSON.parse(
await browser.elementByCss('#random-cookie').text()
).value
return randomCookie ? 'success' : 'failure'
}, 'success')
console.log(123, await browser.elementByCss('body').text())
await browser.elementByCss('#another').click()
await check(async () => {
return browser.elementByCss('#title').text()
}, 'another route')
const newRandomCookie = JSON.parse(
await browser.elementByCss('#random-cookie').text()
).value
console.log(456, await browser.elementByCss('body').text())
// Should be the same value
expect(randomCookie).toEqual(newRandomCookie)
await browser.elementByCss('#back').click()
// Modify the cookie
await browser.elementByCss('#set-cookie').click()
// Should be different
let revalidatedRandomCookie
await check(async () => {
revalidatedRandomCookie = JSON.parse(
await browser.elementByCss('#random-cookie').text()
).value
return randomCookie !== revalidatedRandomCookie
? 'success'
: 'failure'
}, 'success')
await browser.elementByCss('#another').click()
// The other page should be revalidated too
await check(async () => {
const newRandomCookie = await JSON.parse(
await browser.elementByCss('#random-cookie').text()
).value
return revalidatedRandomCookie === newRandomCookie
? 'success'
: 'failure'
}, 'success')
})
it.each(['tag', 'path'])( it.each(['tag', 'path'])(
'should invalidate client cache when %s is revalidate', 'should invalidate client cache when %s is revalidated',
async (type) => { async (type) => {
const browser = await next.browser('/revalidate') const browser = await next.browser('/revalidate')
await browser.refresh() await browser.refresh()
...@@ -527,10 +584,15 @@ createNextDescribe( ...@@ -527,10 +584,15 @@ createNextDescribe(
await browser.elementByCss('#back').click() await browser.elementByCss('#back').click()
if (type === 'tag') { switch (type) {
await browser.elementByCss('#revalidate-thankyounext').click() case 'tag':
} else { await browser.elementByCss('#revalidate-thankyounext').click()
await browser.elementByCss('#revalidate-path').click() break
case 'path':
await browser.elementByCss('#revalidate-path').click()
break
default:
throw new Error(`Invalid type: ${type}`)
} }
// Should be different // Should be different
......
import { revalidateTag } from 'next/cache' import { revalidateTag } from 'next/cache'
import { cookies } from 'next/headers'
import Link from 'next/link' import Link from 'next/link'
export default async function Page() { export default async function Page() {
...@@ -30,6 +31,12 @@ export default async function Page() { ...@@ -30,6 +31,12 @@ export default async function Page() {
revalidate thankyounext revalidate thankyounext
</button> </button>
</form> </form>
<p>
random cookie:{' '}
<span id="random-cookie">
{JSON.stringify(cookies().get('random'))}
</span>
</p>
</> </>
) )
} }
...@@ -51,7 +51,7 @@ export default async function Page() { ...@@ -51,7 +51,7 @@ export default async function Page() {
</span>{' '} </span>{' '}
<span> <span>
<Link href="/revalidate-2" id="another"> <Link href="/revalidate-2" id="another">
/revalidate/another-route /revalidate-2
</Link> </Link>
</span> </span>
</p> </p>
......
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