Unverified Commit b58b1dc9 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Use rewritten pathname for implicit cache tags (#88732)

When a page is accessed via a rewrite, use the destination path (not the source path) when computing implicit tags. This ensures that calling `revalidatePath('/dest')` correctly invalidates cache entries for pages rewritten to that destination.

Fixes `'use cache'` and fetch cache with rewrites. ISR page cache was not affected because it already uses the rewritten pathname as the cache key (via `resolvedUrlPathname` in `base-server.ts`).
parent a77fd58c
...@@ -2017,9 +2017,22 @@ async function renderToHTMLOrFlightImpl( ...@@ -2017,9 +2017,22 @@ async function renderToHTMLOrFlightImpl(
const isPossibleActionRequest = getIsPossibleServerAction(req) const isPossibleActionRequest = getIsPossibleServerAction(req)
// For implicit tags, we need to use the rewritten pathname (if a rewrite
// occurred) rather than the original request pathname. Implicit tags are used
// to check cache staleness on read (for 'use cache') and as soft tags for
// fetch cache. Using the destination path ensures that
// revalidatePath('/dest') invalidates cache entries for pages rewritten to
// that destination.
// TODO: simplify getImplicitTags to accept pathname instead of url object,
// and rename 'rewroteURL' to 'rewrittenPathname' in request-meta.ts.
const rewrittenPathname = getRequestMeta(req, 'rewroteURL')
const implicitTagsUrl = rewrittenPathname
? { ...url, pathname: rewrittenPathname }
: url
const implicitTags = await getImplicitTags( const implicitTags = await getImplicitTags(
workStore.page, workStore.page,
url, implicitTagsUrl,
fallbackRouteParams fallbackRouteParams
) )
......
import { revalidatePath } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
const isCacheComponentsEnabled = !!process.env.__NEXT_CACHE_COMPONENTS
export async function GET(request: NextRequest) {
const sourcePath = request.nextUrl.searchParams.get('path')
if (!sourcePath) {
return NextResponse.json(
{ error: 'Missing path parameter' },
{ status: 400 }
)
}
const prefix = isCacheComponentsEnabled ? '/cache-components' : '/legacy'
revalidatePath(`${prefix}${sourcePath}`)
return NextResponse.json({ revalidated: true })
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import SharedPage from '../../shared-page'
async function CachedContent() {
'use cache: remote'
return <SharedPage isDynamic={true} />
}
async function Content() {
await connection()
return <CachedContent />
}
export default function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Content />
</Suspense>
)
}
import SharedPage from '../../shared-page'
export default async function Page() {
'use cache'
return <SharedPage isDynamic={false} />
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import SharedPage from '../../shared-page'
export const dynamic = 'force-dynamic'
export const fetchCache = 'force-cache'
export default function Page() {
return <SharedPage isDynamic={true} />
}
import SharedPage from '../../shared-page'
export const revalidate = 900
export const fetchCache = 'force-cache'
export default function Page() {
return <SharedPage isDynamic={false} />
}
async function getData() {
const res = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
)
return res.text()
}
export default async function SharedPage({
isDynamic,
}: {
isDynamic: boolean
}) {
const data = await getData()
return (
<div>
<h1>{isDynamic ? 'Dynamic' : 'Static'} Page</h1>
<p>
Random data: <span id="random-data">{data}</span>
</p>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
module.exports = {
rewrites: async () => {
const isCacheComponentsEnabled =
process.env.__NEXT_CACHE_COMPONENTS === 'true'
return [
{
source: '/static',
destination: isCacheComponentsEnabled
? '/cache-components/static'
: '/legacy/static',
},
{
source: '/dynamic',
destination: isCacheComponentsEnabled
? '/cache-components/dynamic'
: '/legacy/dynamic',
},
]
},
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
describe('revalidatePath with rewrites', () => {
const { next } = nextTestSetup({
files: __dirname,
buildArgs: [
'--debug-build-paths',
isCacheComponentsEnabled
? '!app/legacy/**/*'
: '!app/cache-components/**/*',
],
})
describe('static page', () => {
it('should revalidate a static page that was rewritten', async () => {
const browser = await next.browser('/static')
const initialRandomData = await browser.elementById('random-data').text()
expect(initialRandomData).toBeTruthy()
// Verify the data is cached after refresh
await browser.refresh()
const refreshedRandomData = await browser
.elementById('random-data')
.text()
expect(refreshedRandomData).toBe(initialRandomData)
// Trigger revalidation via route handler
const revalidateRes = await next.fetch('/api/revalidate?path=/static')
expect(revalidateRes.status).toBe(200)
// Verify the data changed after revalidation
await retry(async () => {
await browser.refresh()
const randomData = await browser.elementById('random-data').text()
expect(randomData).not.toBe(initialRandomData)
})
})
})
describe('dynamic page', () => {
it('should revalidate a dynamic page that was rewritten', async () => {
const browser = await next.browser('/dynamic')
const initialRandomData = await browser.elementById('random-data').text()
expect(initialRandomData).toBeTruthy()
// Verify the data is cached after refresh
await browser.refresh()
const refreshedRandomData = await browser
.elementById('random-data')
.text()
expect(refreshedRandomData).toBe(initialRandomData)
// Trigger revalidation via route handler
const revalidateRes = await next.fetch('/api/revalidate?path=/dynamic')
expect(revalidateRes.status).toBe(200)
// Verify the data changed after revalidation
await retry(async () => {
await browser.refresh()
const randomData = await browser.elementById('random-data').text()
expect(randomData).not.toBe(initialRandomData)
})
})
})
})
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