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

Fix `revalidatePath` with params and trailing slash when deployed (#88623)

parent d3de9bce
...@@ -978,5 +978,6 @@ ...@@ -978,5 +978,6 @@
"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", "979": "invariant: expected %s bytes of postponed state but only received %s bytes",
"980": "Failed to load client middleware manifest" "980": "Failed to load client middleware manifest",
"981": "resolvedPathname must be set in request metadata"
} }
...@@ -24,6 +24,7 @@ import { trace } from '../trace' ...@@ -24,6 +24,7 @@ import { trace } from '../trace'
import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env' import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
import { addRequestMeta } from '../server/request-meta' import { addRequestMeta } from '../server/request-meta'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { createRequestResponseMocks } from '../server/lib/mock-request' import { createRequestResponseMocks } from '../server/lib/mock-request'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
...@@ -176,6 +177,9 @@ async function exportPageImpl( ...@@ -176,6 +177,9 @@ async function exportPageImpl(
req.url += '/' req.url += '/'
} }
// Set the resolved pathname without trailing slash as request metadata.
addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath))
if ( if (
locale && locale &&
buildExport && buildExport &&
......
...@@ -2021,18 +2021,16 @@ async function renderToHTMLOrFlightImpl( ...@@ -2021,18 +2021,16 @@ async function renderToHTMLOrFlightImpl(
const isPossibleActionRequest = getIsPossibleServerAction(req) const isPossibleActionRequest = getIsPossibleServerAction(req)
// For implicit tags, we need to use the rewritten pathname (if a rewrite // For implicit tags, we use the resolved pathname which has dynamic params
// occurred) rather than the original request pathname. Implicit tags are used // interpolated, is decoded, and has trailing slash removed.
// to check cache staleness on read (for 'use cache') and as soft tags for const resolvedPathname = getRequestMeta(req, 'resolvedPathname')
// fetch cache. Using the destination path ensures that if (!resolvedPathname) {
// revalidatePath('/dest') invalidates cache entries for pages rewritten to throw new InvariantError('resolvedPathname must be set in request metadata')
// that destination. }
const implicitTagsPathname =
getRequestMeta(req, 'rewrittenPathname') || url.pathname
const implicitTags = await getImplicitTags( const implicitTags = await getImplicitTags(
workStore.page, workStore.page,
implicitTagsPathname, resolvedPathname,
fallbackRouteParams fallbackRouteParams
) )
......
...@@ -86,6 +86,12 @@ export interface RequestMeta { ...@@ -86,6 +86,12 @@ export interface RequestMeta {
*/ */
rewrittenPathname?: string rewrittenPathname?: string
/**
* The resolved pathname for the request. Dynamic route params are
* interpolated, the pathname is decoded, and the trailing slash is removed.
*/
resolvedPathname?: string
/** /**
* The cookies that were added by middleware and were added to the response. * The cookies that were added by middleware and were added to the response.
*/ */
......
...@@ -935,6 +935,7 @@ export abstract class RouteModule< ...@@ -935,6 +935,7 @@ export abstract class RouteModule<
} catch (_) {} } catch (_) {}
resolvedPathname = removeTrailingSlash(resolvedPathname) resolvedPathname = removeTrailingSlash(resolvedPathname)
addRequestMeta(req, 'resolvedPathname', resolvedPathname)
let deploymentId let deploymentId
if (nextConfig.experimental?.runtimeServerDeploymentId) { if (nextConfig.experimental?.runtimeServerDeploymentId) {
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
ActionDidRevalidateDynamicOnly, ActionDidRevalidateDynamicOnly,
ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate, ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,
} from '../../../shared/lib/action-revalidation-kind' } from '../../../shared/lib/action-revalidation-kind'
import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'
type CacheLifeConfig = { type CacheLifeConfig = {
expire?: number expire?: number
...@@ -96,7 +97,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') { ...@@ -96,7 +97,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
return return
} }
let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${originalPath || '/'}` let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${removeTrailingSlash(originalPath)}`
if (type) { if (type) {
normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}` normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`
......
import SharedPage from '../shared-page'
// This page is compatible with Cache Components. It does not define a
// `revalidate` route segment config, and uses 'use cache' instead. The path is
// rewritten to here from /:lang(en|es)/ via rewrites in next.config.js when
// __NEXT_CACHE_COMPONENTS is set to true.
export default async function Page({ params }) {
'use cache'
return <SharedPage params={params} />
}
import Link from 'next/link'
export function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'es' }]
}
export default function LangLayout({ children }) {
return (
<>
<nav>
<Link href="/en">English</Link> | <Link href="/es">Spanish</Link>
</nav>
<main>{children}</main>
</>
)
}
import SharedPage from '../shared-page'
// This page uses the legacy `revalidate` route segment config instead of 'use
// cache'. The path is rewritten to here from /:lang(en|es)/ via rewrites in
// next.config.js when __NEXT_CACHE_COMPONENTS is not set.
export const revalidate = 900
export default SharedPage
'use client'
import { useState, useTransition } from 'react'
export function RevalidateButton({ lang }) {
const [isPending, startTransition] = useTransition()
const [result, setResult] = useState(null)
function handleRevalidate(withSlash) {
startTransition(async () => {
try {
const data = await fetch(
`/api/revalidate/?lang=${lang}&withSlash=${withSlash}`
).then((res) => res.json())
startTransition(() => {
setResult(`Revalidated at: ${data.timestamp}`)
})
} catch (e) {
startTransition(() => {
setResult(`Error: ${e}`)
})
}
})
}
return (
<div>
<button
onClick={handleRevalidate.bind(null, true)}
disabled={isPending}
id="revalidate-button-with-slash"
>
{isPending ? 'Revalidating...' : `Revalidate /${lang}/`}
</button>
<button
onClick={handleRevalidate.bind(null, false)}
disabled={isPending}
id="revalidate-button-no-slash"
>
{isPending ? 'Revalidating...' : `Revalidate /${lang} (no slash)`}
</button>
{result && <pre id="revalidate-result">{result}</pre>}
</div>
)
}
import { RevalidateButton } from './revalidate-button'
export default async function Page({ params }) {
const { lang } = await params
const generatedAt = new Date().toISOString()
return (
<div>
<h1>Revalidation Test - {lang}</h1>
<pre>
Page generated at: <span id="generated-at">{generatedAt}</span>
</pre>
<RevalidateButton lang={lang} />
</div>
)
}
import { revalidatePath } from 'next/cache'
import { NextResponse } from 'next/server'
const isCacheComponentsEnabled = !!process.env.__NEXT_CACHE_COMPONENTS
export async function GET(request) {
const lang = request.nextUrl.searchParams.get('lang') || 'en'
const withSlash = request.nextUrl.searchParams.get('withSlash') !== 'false'
// With rewrites, we need to revalidate the destination path (the actual
// page), not the source path that users visit.
let path = isCacheComponentsEnabled
? `/${lang}/cache-components`
: `/${lang}/legacy`
if (withSlash) {
path += '/'
}
revalidatePath(path)
return NextResponse.json({ timestamp: new Date().toISOString() })
}
/**
* @type {import('next').NextConfig}
*/
module.exports = { module.exports = {
trailingSlash: true, trailingSlash: true,
rewrites: async () => {
const isCacheComponentsEnabled =
process.env.__NEXT_CACHE_COMPONENTS === 'true'
return [
{
source: '/:lang(en|es)/',
destination: isCacheComponentsEnabled
? '/:lang/cache-components/'
: '/:lang/legacy/',
},
]
},
} }
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
describe('app-dir trailingSlash handling', () => { describe('app-dir trailingSlash handling', () => {
const { next, skipped } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true, buildArgs: [
'--debug-build-paths',
isCacheComponentsEnabled
? '!app/[lang]/legacy/page.js'
: '!app/[lang]/cache-components/page.js',
],
}) })
if (skipped) {
return
}
it('should redirect route when requesting it directly', async () => { it('should redirect route when requesting it directly', async () => {
const res = await next.fetch('/a', { const res = await next.fetch('/a', {
redirect: 'manual', redirect: 'manual',
...@@ -59,4 +63,45 @@ describe('app-dir trailingSlash handling', () => { ...@@ -59,4 +63,45 @@ describe('app-dir trailingSlash handling', () => {
'http://trailingslash-another.com/metadata' 'http://trailingslash-another.com/metadata'
) )
}) })
it.each([{ withSlash: true }, { withSlash: false }])(
'should revalidate a page with generated static params (withSlash=$withSlash)',
async ({ withSlash }) => {
const browser = await next.browser('/en')
const initialGeneratedAt = await browser
.elementById('generated-at')
.text()
expect(initialGeneratedAt).toBeDateString()
if (!isNextDev) {
await browser.refresh()
const refreshedGeneratedAt = await browser
.elementById('generated-at')
.text()
expect(refreshedGeneratedAt).toBe(initialGeneratedAt)
}
await browser
.elementById(
withSlash
? 'revalidate-button-with-slash'
: 'revalidate-button-no-slash'
)
.click()
expect(await browser.elementById('revalidate-result').text()).toInclude(
'Revalidated'
)
await retry(async () => {
await browser.refresh()
const generatedAt = await browser.elementById('generated-at').text()
expect(generatedAt).toBeDateString()
expect(generatedAt).not.toBe(initialGeneratedAt)
})
}
)
}) })
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