Unverified Commit 90a49278 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix: use RDC for server action requests (#88129)

When a server action triggers a re-render of the underlying page (eg by
calling `refresh()`), cached data that was part of the Resume Data Cache
(RDC) was not provided to the server action handler, and so those parts
of the UI would update with new data. A subsequent refresh of the page
would revert back to the ISR data, which means the server action causes
the data to temporarily get into an "ahead" state that will never
actually be reflected in the ISR shell.

This provides the RDC data to the server action handler. For self-hosted
deployments, Next.js can look up the cached entry directly since the
cache and renderer are co-located. For deployments on Vercel, the
caching layer and rendering layer are separate services, and server
actions bypass the cache. This means the serverless function has no way
to access the cached RDC on its own, so the underlying CDN must fetch it
and pass it via the request body. The `x-next-resume-state-length` is
sent to the serverless function so that it can determine how to split
off the RDC data from the action body.

Fixes NAR-478
Fixes NAR-502
parent 76a15d8d
...@@ -976,5 +976,6 @@ ...@@ -976,5 +976,6 @@
"975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action", "975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"976": "Decompressed resume data cache exceeded %s byte limit", "976": "Decompressed resume data cache exceeded %s byte limit",
"977": "maxPostponedStateSize must be a valid number (bytes) or filesize format string (e.g., \"5mb\")", "977": "maxPostponedStateSize must be a valid number (bytes) or filesize format string (e.g., \"5mb\")",
"978": "Next.js has blocked a javascript: URL as a security precaution." "978": "Next.js has blocked a javascript: URL as a security precaution.",
"979": "invariant: expected %s bytes of postponed state but only received %s bytes"
} }
...@@ -56,12 +56,16 @@ import { ...@@ -56,12 +56,16 @@ import {
HTML_CONTENT_TYPE_HEADER, HTML_CONTENT_TYPE_HEADER,
NEXT_CACHE_TAGS_HEADER, NEXT_CACHE_TAGS_HEADER,
NEXT_RESUME_HEADER, NEXT_RESUME_HEADER,
NEXT_RESUME_STATE_LENGTH_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
import type { CacheControl } from '../../server/lib/cache-control' import type { CacheControl } from '../../server/lib/cache-control'
import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags' import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags'
import { sendRenderResult } from '../../server/send-payload' import { sendRenderResult } from '../../server/send-payload'
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external' import { NoFallbackError } from '../../shared/lib/no-fallback-error.external'
import { parseMaxPostponedStateSize } from '../../shared/lib/size-limit' import {
DEFAULT_MAX_POSTPONED_STATE_SIZE,
parseMaxPostponedStateSize,
} from '../../shared/lib/size-limit'
// These are injected by the loader afterwards. // These are injected by the loader afterwards.
...@@ -229,6 +233,92 @@ export async function handler( ...@@ -229,6 +233,92 @@ export async function handler(
nextConfig.experimental.ppr nextConfig.experimental.ppr
) )
// Stash postponed state for server actions when in minimal mode.
// We extract it here so the RDC is available for the re-render after the action completes.
const resumeStateLengthHeader = req.headers[NEXT_RESUME_STATE_LENGTH_HEADER]
if (
!getRequestMeta(req, 'postponed') &&
isMinimalMode &&
couldSupportPPR &&
isPossibleServerAction &&
resumeStateLengthHeader &&
typeof resumeStateLengthHeader === 'string'
) {
const stateLength = parseInt(resumeStateLengthHeader, 10)
const maxPostponedStateSize =
nextConfig.experimental.maxPostponedStateSize ??
DEFAULT_MAX_POSTPONED_STATE_SIZE
const maxPostponedStateSizeBytes = parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize
)
if (!isNaN(stateLength) && stateLength > 0) {
if (
maxPostponedStateSizeBytes === undefined ||
stateLength > maxPostponedStateSizeBytes
) {
res.statusCode = 413
res.end(
`Postponed state exceeded ${maxPostponedStateSize} limit. ` +
`To configure the limit, see: https://nextjs.org/docs/app/api-reference/config/next-config-js/max-postponed-state-size`
)
ctx.waitUntil?.(Promise.resolve())
return null
}
// Calculate max total body size to prevent buffering excessively large
// payloads before the action handler checks. We use stateLength (not
// maxPostponedStateSizeBytes) so the postponed state doesn't eat into
// the action body budget - it's already validated above.
const defaultActionBodySizeLimit = '1 MB'
const actionBodySizeLimit =
nextConfig.experimental.serverActions?.bodySizeLimit ??
defaultActionBodySizeLimit
const actionBodySizeLimitBytes =
actionBodySizeLimit !== defaultActionBodySizeLimit
? (
require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')
).parse(actionBodySizeLimit)
: 1024 * 1024 // 1 MB
const maxTotalBodySize = stateLength + actionBodySizeLimitBytes
// Read the entire body, checking size as we go.
const bodyChunks: Array<Buffer> = []
let size = 0
for await (const chunk of req) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
size += buffer.byteLength
if (size > maxTotalBodySize) {
res.statusCode = 413
res.end(
`Request body exceeded limit. ` +
`To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`
)
ctx.waitUntil?.(Promise.resolve())
return null
}
bodyChunks.push(buffer)
}
const fullBody = Buffer.concat(bodyChunks)
if (fullBody.length >= stateLength) {
// Extract postponed state from the beginning
const postponedState = fullBody
.subarray(0, stateLength)
.toString('utf8')
addRequestMeta(req, 'postponed', postponedState)
// Store the remaining action body for the action handler
const actionBody = fullBody.subarray(stateLength)
addRequestMeta(req, 'actionBody', actionBody)
} else {
throw new Error(
`invariant: expected ${stateLength} bytes of postponed state but only received ${fullBody.length} bytes`
)
}
}
}
if ( if (
!getRequestMeta(req, 'postponed') && !getRequestMeta(req, 'postponed') &&
couldSupportPPR && couldSupportPPR &&
...@@ -856,17 +946,20 @@ export async function handler( ...@@ -856,17 +946,20 @@ export async function handler(
? minimalPostponed ? minimalPostponed
: undefined : undefined
// If this is a dynamic RSC request, we should use the postponed data from // If this is a dynamic RSC request or a server action request, we should
// the static render (if available). This ensures that we can utilize the // use the postponed data from the static render (if available). This
// resume data cache (RDC) from the static render to ensure that the data // ensures that we can utilize the resume data cache (RDC) from the static
// is consistent between the static and dynamic renders. // render to ensure that the data is consistent between the static and
// dynamic renders (for navigations) or when re-rendering after a server
// action.
if ( if (
// Only enable RDC for Navigations if the feature is enabled. // Only enable RDC for Navigations if the feature is enabled.
supportsRDCForNavigations && supportsRDCForNavigations &&
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
!isMinimalMode && !isMinimalMode &&
incrementalCache && incrementalCache &&
isDynamicRSCRequest && // Include both dynamic RSC requests (navigations) and server actions
(isDynamicRSCRequest || isPossibleServerAction) &&
// We don't typically trigger an on-demand revalidation for dynamic RSC // We don't typically trigger an on-demand revalidation for dynamic RSC
// requests, as we're typically revalidating the page in the background // requests, as we're typically revalidating the page in the background
// instead. However, if the cache entry is stale, we should trigger a // instead. However, if the cache entry is stale, we should trigger a
......
...@@ -25,6 +25,7 @@ export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER = ...@@ -25,6 +25,7 @@ export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =
'x-next-revalidate-tag-token' 'x-next-revalidate-tag-token'
export const NEXT_RESUME_HEADER = 'next-resume' export const NEXT_RESUME_HEADER = 'next-resume'
export const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length'
// if these change make sure we update the related // if these change make sure we update the related
// documentation as well // documentation as well
......
...@@ -870,6 +870,13 @@ export async function handleAction({ ...@@ -870,6 +870,13 @@ export async function handleAction({
const { pipeline } = const { pipeline } =
require('node:stream/promises') as typeof import('node:stream/promises') require('node:stream/promises') as typeof import('node:stream/promises')
// If actionBody was stashed in request meta (from parsing the postponed
// state prefix in minimal mode), use it instead of req.body
const actionBodyFromMeta = getRequestMeta(req, 'actionBody')
const body: import('node:stream').Readable = actionBodyFromMeta
? Readable.from(actionBodyFromMeta)
: req.body
const defaultBodySizeLimit = '1 MB' const defaultBodySizeLimit = '1 MB'
const bodySizeLimit = const bodySizeLimit =
serverActions?.bodySizeLimit ?? defaultBodySizeLimit serverActions?.bodySizeLimit ?? defaultBodySizeLimit
...@@ -923,7 +930,7 @@ export async function handleAction({ ...@@ -923,7 +930,7 @@ export async function handleAction({
const abortController = new AbortController() const abortController = new AbortController()
try { try {
;[, boundActionArguments] = await Promise.all([ ;[, boundActionArguments] = await Promise.all([
pipeline(req.body, sizeLimitTransform, busboy, { pipeline(body, sizeLimitTransform, busboy, {
signal: abortController.signal, signal: abortController.signal,
}), }),
decodeReplyFromBusboy(busboy, serverModuleMap, { decodeReplyFromBusboy(busboy, serverModuleMap, {
...@@ -956,7 +963,7 @@ export async function handleAction({ ...@@ -956,7 +963,7 @@ export async function handleAction({
const abortController = new AbortController() const abortController = new AbortController()
try { try {
;[, formData] = await Promise.all([ ;[, formData] = await Promise.all([
pipeline(req.body, sizeLimitTransform, sizeLimitedBody, { pipeline(body, sizeLimitTransform, sizeLimitedBody, {
signal: abortController.signal, signal: abortController.signal,
}), }),
fakeRequest.formData(), fakeRequest.formData(),
...@@ -1032,7 +1039,7 @@ export async function handleAction({ ...@@ -1032,7 +1039,7 @@ export async function handleAction({
const chunks: Buffer[] = [] const chunks: Buffer[] = []
await Promise.all([ await Promise.all([
pipeline(req.body, sizeLimitTransform, sizeLimitedBody), pipeline(body, sizeLimitTransform, sizeLimitedBody),
(async () => { (async () => {
for await (const chunk of sizeLimitedBody) { for await (const chunk of sizeLimitedBody) {
chunks.push(Buffer.from(chunk)) chunks.push(Buffer.from(chunk))
......
...@@ -2201,9 +2201,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -2201,9 +2201,6 @@ async function renderToHTMLOrFlightImpl(
let didExecuteServerAction = false let didExecuteServerAction = false
let formState: null | any = null let formState: null | any = null
if (isPossibleActionRequest) { if (isPossibleActionRequest) {
// For action requests, we don't want to use the resume data cache.
requestStore.renderResumeDataCache = null
// For action requests, we handle them differently with a special render result. // For action requests, we handle them differently with a special render result.
const actionRequestResult = await handleAction({ const actionRequestResult = await handleAction({
req, req,
...@@ -2250,8 +2247,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -2250,8 +2247,6 @@ async function renderToHTMLOrFlightImpl(
} }
didExecuteServerAction = true didExecuteServerAction = true
// Restore the resume data cache
requestStore.renderResumeDataCache = renderResumeDataCache
} }
const options: RenderResultOptions = { const options: RenderResultOptions = {
......
...@@ -441,11 +441,31 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -441,11 +441,31 @@ export class IncrementalCache implements IncrementalCacheType {
if (resumeDataCache) { if (resumeDataCache) {
const memoryCacheData = resumeDataCache.fetch.get(cacheKey) const memoryCacheData = resumeDataCache.fetch.get(cacheKey)
if (memoryCacheData?.kind === CachedRouteKind.FETCH) { if (memoryCacheData?.kind === CachedRouteKind.FETCH) {
if (IncrementalCache.debug) { // Check if any tags were recently revalidated before returning RDC entry.
console.log('IncrementalCache: rdc:hit', cacheKey) // When a server action calls updateTag(), the re-render should see fresh
} // data instead of stale RDC data.
const workStore = workAsyncStorage.getStore()
const combinedTags = [...(ctx.tags || []), ...(ctx.softTags || [])]
const hasRevalidatedTag = combinedTags.some(
(tag) =>
this.revalidatedTags?.includes(tag) ||
workStore?.pendingRevalidatedTags?.some(
(item) => item.tag === tag
)
)
return { isStale: false, value: memoryCacheData } if (hasRevalidatedTag) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:revalidated-tag', cacheKey)
}
// Fall through to cacheHandler lookup
} else {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:hit', cacheKey)
}
return { isStale: false, value: memoryCacheData }
}
} else if (IncrementalCache.debug) { } else if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:miss', cacheKey) console.log('IncrementalCache: rdc:miss', cacheKey)
} }
......
...@@ -48,6 +48,7 @@ const INTERNAL_HEADERS = [ ...@@ -48,6 +48,7 @@ const INTERNAL_HEADERS = [
'x-middleware-next', 'x-middleware-next',
'x-now-route-matches', 'x-now-route-matches',
'x-matched-path', 'x-matched-path',
'x-next-resume-state-length',
] ]
export const filterInternalHeaders = ( export const filterInternalHeaders = (
......
...@@ -145,6 +145,13 @@ export interface RequestMeta { ...@@ -145,6 +145,13 @@ export interface RequestMeta {
*/ */
postponed?: string postponed?: string
/**
* The action body extracted from a server action request when the postponed
* state was prepended to the body by the proxy. This allows the action
* handler to read the action payload without re-reading the consumed stream.
*/
actionBody?: Buffer
/** /**
* If provided, this will be called when a response cache entry was generated * If provided, this will be called when a response cache entry was generated
* or looked up in the cache. * or looked up in the cache.
......
...@@ -1240,7 +1240,27 @@ export async function cache( ...@@ -1240,7 +1240,27 @@ export async function cache(
} }
const cachedEntry = renderResumeDataCache.cache.get(serializedCacheKey) const cachedEntry = renderResumeDataCache.cache.get(serializedCacheKey)
if (cachedEntry !== undefined) { if (cachedEntry !== undefined) {
const existingEntry = await cachedEntry let existingEntry: CacheEntry | undefined = await cachedEntry
// Check if the RDC entry should be discarded due to recently revalidated tags.
// When a server action calls updateTag(), the re-render should see fresh data
// instead of stale RDC data.
if (existingEntry !== undefined) {
const implicitTags = workUnitStore?.implicitTags?.tags ?? []
if (
existingEntry.tags.some((tag) =>
isRecentlyRevalidatedTag(tag, workStore)
) ||
implicitTags.some((tag) => isRecentlyRevalidatedTag(tag, workStore))
) {
debug?.(
'discarding RDC entry due to recently revalidated tags',
serializedCacheKey
)
existingEntry = undefined
}
}
if (workUnitStore !== undefined && existingEntry !== undefined) { if (workUnitStore !== undefined && existingEntry !== undefined) {
if ( if (
existingEntry.revalidate === 0 || existingEntry.revalidate === 0 ||
...@@ -1362,22 +1382,31 @@ export async function cache( ...@@ -1362,22 +1382,31 @@ export async function cache(
} }
} }
debug?.('Resume Data Cache entry found', serializedCacheKey) if (existingEntry !== undefined) {
debug?.('Resume Data Cache entry found', serializedCacheKey)
// We want to make sure we only propagate cache life & tags if the // We want to make sure we only propagate cache life & tags if the
// entry was *not* omitted from the prerender. So we only do this // entry was *not* omitted from the prerender. So we only do this
// after the above early returns. // after the above early returns.
propagateCacheLifeAndTags(cacheContext, existingEntry) propagateCacheLifeAndTags(cacheContext, existingEntry)
const [streamA, streamB] = existingEntry.value.tee() const [streamA, streamB] = existingEntry.value.tee()
existingEntry.value = streamB existingEntry.value = streamB
if (cacheSignal) { if (cacheSignal) {
// When we have a cacheSignal we need to block on reading the cache // When we have a cacheSignal we need to block on reading the cache
// entry before ending the read. // entry before ending the read.
stream = createTrackedReadableStream(streamA, cacheSignal) stream = createTrackedReadableStream(streamA, cacheSignal)
} else {
stream = streamA
}
} else { } else {
stream = streamA // Entry was discarded (e.g. due to recently revalidated tags)
debug?.('Resume Data Cache entry discarded', serializedCacheKey)
if (cacheSignal) {
cacheSignal.endRead()
}
} }
} else { } else {
debug?.('Resume Data Cache entry not found', serializedCacheKey) debug?.('Resume Data Cache entry not found', serializedCacheKey)
......
'use server'
import { refresh } from 'next/cache'
export async function refreshAction() {
// Simulate some IO before calling refresh
await new Promise((resolve) => setTimeout(resolve, 100))
refresh()
}
'use server'
import { updateTag } from 'next/cache'
export async function revalidateAction() {
updateTag('revalidate-action-test')
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { cacheTag } from 'next/cache'
import { RevalidateButton } from './revalidate-button'
async function getCachedRandom() {
'use cache'
cacheTag('revalidate-action-test')
return Math.random()
}
async function DynamicContent() {
// Make the page dynamic/PPR by accessing connection()
await connection()
// Generate uncached value after dynamic access
const uncachedValue = Math.random()
return <p id="uncached-value">{uncachedValue}</p>
}
export default async function Page() {
const cachedValue = await getCachedRandom()
return (
<div>
<p id="cached-value">{cachedValue}</p>
<Suspense fallback={<p id="uncached-value">Loading...</p>}>
<DynamicContent />
</Suspense>
<RevalidateButton />
</div>
)
}
'use client'
import { revalidateAction } from './actions'
export function RevalidateButton() {
return (
<form action={revalidateAction}>
<button id="revalidate-button" type="submit">
Revalidate
</button>
</form>
)
}
'use server'
import { updateTag } from 'next/cache'
export async function revalidateFetchAction() {
updateTag('revalidate-fetch-action-test')
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { RevalidateButton } from './revalidate-button'
async function DynamicContent() {
// Make the page dynamic/PPR by accessing connection()
await connection()
// Generate uncached value after dynamic access
const uncachedValue = Math.random()
return <p id="uncached-value">{uncachedValue}</p>
}
export default async function Page() {
// Use fetch with cache and tags
const cachedValue = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache', next: { tags: ['revalidate-fetch-action-test'] } }
).then((res) => res.text())
return (
<div>
<p id="cached-value">{cachedValue}</p>
<Suspense fallback={<p id="uncached-value">Loading...</p>}>
<DynamicContent />
</Suspense>
<RevalidateButton />
</div>
)
}
'use client'
import { revalidateFetchAction } from './actions'
export function RevalidateButton() {
return (
<form action={revalidateFetchAction}>
<button id="revalidate-button" type="submit">
Revalidate
</button>
</form>
)
}
import React, { Suspense } from 'react'
import { cacheTag } from 'next/cache'
import { refreshAction } from '../actions'
async function getCachedRandomNumber() {
'use cache'
cacheTag('server-action-test')
await new Promise((resolve) => setTimeout(resolve, 100))
return Math.random()
}
async function getUncachedRandomNumber() {
// No 'use cache' - this will generate a new value on every render
await new Promise((resolve) => setTimeout(resolve, 100))
return Math.random()
}
async function DynamicComponent() {
const uncachedNumber = await getUncachedRandomNumber()
return <p id="uncached-random">{uncachedNumber}</p>
}
export default async function Page() {
const cachedNumber = await getCachedRandomNumber()
return (
<>
<p id="cached-random">{cachedNumber}</p>
<form action={refreshAction}>
<button id="refresh-button" type="submit">
Refresh
</button>
</form>
<Suspense fallback={<p id="uncached-random">Loading...</p>}>
<DynamicComponent />
</Suspense>
</>
)
}
...@@ -3,7 +3,7 @@ import { retry } from 'next-test-utils' ...@@ -3,7 +3,7 @@ import { retry } from 'next-test-utils'
import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param' import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
describe('resume-data-cache', () => { describe('resume-data-cache', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -131,4 +131,122 @@ describe('resume-data-cache', () => { ...@@ -131,4 +131,122 @@ describe('resume-data-cache', () => {
// between the static and dynamic renders. // between the static and dynamic renders.
} }
) )
// TODO: Re-enable this test once necessary upstream changes are merged to support this
if (!isNextDeploy) {
it('should use RDC for server action re-renders', async () => {
const browser = await next.browser('/server-action')
// Get the initial values
const initialCachedValue = await browser
.elementByCss('#cached-random')
.text()
const initialUncachedValue = await browser
.elementByCss('#uncached-random')
.text()
await browser.elementByCss('#refresh-button').click()
// Wait for the action to complete and verify:
// 1. The uncached value should change
// 2. The cached value should remain the same (proving RDC is being used)
await retry(async () => {
const cachedValueAfterAction = await browser
.elementByCss('#cached-random')
.text()
const uncachedValueAfterAction = await browser
.elementByCss('#uncached-random')
.text()
// Uncached value should have changed - this proves the action caused a re-render
expect(uncachedValueAfterAction).not.toBe(initialUncachedValue)
// Cached value should remain the same - this proves the RDC is being used
// to maintain consistency during server action re-renders
expect(cachedValueAfterAction).toBe(initialCachedValue)
})
})
}
it('should see fresh data after updateTag in server action with use cache', async () => {
// This test verifies that when a server action calls updateTag(),
// the subsequent re-render sees fresh data instead of stale RDC data.
// This is the "read your own writes" behavior for 'use cache'.
const browser = await next.browser('/revalidate-action')
// Get the initial cached value from the page render
const initialCachedValue = await browser
.elementByCss('#cached-value')
.text()
const initialUncachedValue = await browser
.elementByCss('#uncached-value')
.text()
// Click the revalidate button to trigger the server action
await browser.elementByCss('#revalidate-button').click()
// Wait for the re-render and verify:
// 1. The uncached value should change (proves re-render happened)
// 2. The cached value should ALSO change (proves updateTag was respected)
await retry(async () => {
const cachedValueAfterAction = await browser
.elementByCss('#cached-value')
.text()
const uncachedValueAfterAction = await browser
.elementByCss('#uncached-value')
.text()
// Uncached value should change - this proves the action triggered a re-render
expect(uncachedValueAfterAction).not.toBe(initialUncachedValue)
// Cached value should also change, which proves that the RDC read respected
// pendingRevalidatedTags and fetched fresh data instead of returning
// the stale value from the RDC.
// If this fails, it means the RDC is not respecting updateTag()
// calls made during server actions
expect(cachedValueAfterAction).not.toBe(initialCachedValue)
})
})
it('should see fresh data after updateTag in server action with fetch cache', async () => {
// This test verifies that when a server action calls updateTag(),
// the subsequent re-render sees fresh data instead of stale RDC data.
// This is the "read your own writes" behavior for fetch cache.
const browser = await next.browser('/revalidate-fetch-action')
// Get the initial cached value from the page render
const initialCachedValue = await browser
.elementByCss('#cached-value')
.text()
const initialUncachedValue = await browser
.elementByCss('#uncached-value')
.text()
// Click the revalidate button to trigger the server action
await browser.elementByCss('#revalidate-button').click()
// Wait for the re-render and verify:
// 1. The uncached value should change (proves re-render happened)
// 2. The cached value should ALSO change (proves updateTag was respected)
await retry(async () => {
const cachedValueAfterAction = await browser
.elementByCss('#cached-value')
.text()
const uncachedValueAfterAction = await browser
.elementByCss('#uncached-value')
.text()
// Uncached value should change - this proves the action triggered a re-render
expect(uncachedValueAfterAction).not.toBe(initialUncachedValue)
// Cached value should also change, which proves that the RDC read respected
// pendingRevalidatedTags and fetched fresh data instead of returning
// the stale value from the RDC.
// If this fails, it means the RDC is not respecting updateTag()
// calls made during server actions
expect(cachedValueAfterAction).not.toBe(initialCachedValue)
})
})
}) })
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