Unverified Commit 12469cdb authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

fix(adapter): preserve revalidation for metadata prerenders (#100861)

Metadata routes like `robots.ts` and `sitemap.ts` were emitted as static
files even when they had revalidation configured, so adapter deployments
could never refresh them.

Keep revalidating metadata as prerenders backed by app routes. Compute
static-file eligibility once so the two output decisions stay in sync.

Related to #100782.

<!-- NEXT_JS_LLM -->
parent 4c6a3fa4
...@@ -43,6 +43,8 @@ import { ...@@ -43,6 +43,8 @@ import {
CACHE_ONE_YEAR_SECONDS, CACHE_ONE_YEAR_SECONDS,
HTML_CONTENT_TYPE_HEADER, HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE_HEADER,
NEXT_CACHE_IMPLICIT_TAG_ID,
NEXT_CACHE_TAGS_HEADER,
NEXT_QUERY_PARAM_PREFIX, NEXT_QUERY_PARAM_PREFIX,
NEXT_RESUME_HEADER, NEXT_RESUME_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
...@@ -438,6 +440,18 @@ export interface AdapterOutputs { ...@@ -438,6 +440,18 @@ export interface AdapterOutputs {
staticFiles: Array<AdapterOutput['STATIC_FILE']> staticFiles: Array<AdapterOutput['STATIC_FILE']>
} }
// Time-based or explicit tag-based revalidation requires a runtime route,
// even when the initial response can be served without compute.
function hasRevalidation(prerender: PrerenderManifestRoute): boolean {
if (prerender.initialRevalidateSeconds !== false) {
return true
}
const tags =
prerender.initialHeaders?.[NEXT_CACHE_TAGS_HEADER]?.split(',') ?? []
return tags.some((tag) => tag && !tag.startsWith(NEXT_CACHE_IMPLICIT_TAG_ID))
}
function getPrerenderClassification( function getPrerenderClassification(
route: string, route: string,
routeType: PrerenderManifestRoute['routeType'], routeType: PrerenderManifestRoute['routeType'],
...@@ -1142,6 +1156,16 @@ export async function handleBuildComplete({ ...@@ -1142,6 +1156,16 @@ export async function handleBuildComplete({
> = {} > = {}
const appDistDir = path.join(distDir, 'server', 'app') const appDistDir = path.join(distDir, 'server', 'app')
// Decide which metadata prerenders can become static files once, so
// omitting their runtime routes agrees with emitting their responses.
const staticMetadataPrerenders = new Set(
Object.keys(prerenderManifest.routes).filter(
(pathname) =>
isStaticMetadataFile(pathname) &&
!hasRevalidation(prerenderManifest.routes[pathname])
)
)
if (appPageKeys) { if (appPageKeys) {
for (const page of orderAppPageKeysByEntry(appPageKeys)) { for (const page of orderAppPageKeysByEntry(appPageKeys)) {
if (middlewareManifest.functions.hasOwnProperty(page)) { if (middlewareManifest.functions.hasOwnProperty(page)) {
...@@ -1149,24 +1173,21 @@ export async function handleBuildComplete({ ...@@ -1149,24 +1173,21 @@ export async function handleBuildComplete({
} }
const normalizedPage = normalizeAppPath(page) const normalizedPage = normalizeAppPath(page)
// Skip static metadata routes only when they are prerendered. // Metadata that remains a prerender needs its backing runtime route.
// Dynamic metadata routes (e.g. robots/sitemap using connection())
// should remain app routes in adapter outputs.
const isStaticMetadataRoute = isStaticMetadataFile(normalizedPage)
const staticMetadataPrerenderPathname = const staticMetadataPrerenderPathname =
getStaticMetadataPrerenderPathname(normalizedPage) ?? normalizedPage getStaticMetadataPrerenderPathname(normalizedPage) ?? normalizedPage
const isPrerenderedMetadataRoute = const isEmittedAsStaticFile =
prerenderManifest.routes[staticMetadataPrerenderPathname] || staticMetadataPrerenders.has(staticMetadataPrerenderPathname) ||
config.i18n?.locales?.some((locale) => { config.i18n?.locales?.some((locale) => {
const localePathname = path.posix.join( const localePathname = path.posix.join(
'/', '/',
locale, locale,
staticMetadataPrerenderPathname.slice(1) staticMetadataPrerenderPathname.slice(1)
) )
return prerenderManifest.routes[localePathname] return staticMetadataPrerenders.has(localePathname)
}) })
if (isStaticMetadataRoute && isPrerenderedMetadataRoute) { if (isEmittedAsStaticFile) {
continue continue
} }
const pageFile = path.join(appDistDir, `${page}.js`) const pageFile = path.join(appDistDir, `${page}.js`)
...@@ -1522,9 +1543,7 @@ export async function handleBuildComplete({ ...@@ -1522,9 +1543,7 @@ export async function handleBuildComplete({
isAppPage && !dataRoute ? '.body' : '.html' isAppPage && !dataRoute ? '.body' : '.html'
) )
// Check if this is a static metadata route (e.g., /favicon.ico, /icon.png, /opengraph-image.png) if (staticMetadataPrerenders.has(route)) {
// These should be output as static files, not prerenders.
if (isStaticMetadataFile(route)) {
// For static metadata from app router, check if the .body file exists // For static metadata from app router, check if the .body file exists
const staticMetadataFilePath = getPrerenderFilePath( const staticMetadataFilePath = getPrerenderFilePath(
route, route,
......
...@@ -20,6 +20,8 @@ describe('adapter-config export', () => { ...@@ -20,6 +20,8 @@ describe('adapter-config export', () => {
'app/preferred-region/route.ts', 'app/preferred-region/route.ts',
'app/isr-route/route.ts', 'app/isr-route/route.ts',
'app/isr-route/[slug]/route.ts', 'app/isr-route/[slug]/route.ts',
'app/revalidating/sitemap.ts',
'app/tagged/sitemap.ts',
'app/edge-app/page.tsx', 'app/edge-app/page.tsx',
'pages/api/edge-pages.ts', 'pages/api/edge-pages.ts',
'pages/api/node-pages.ts', 'pages/api/node-pages.ts',
......
...@@ -22,6 +22,51 @@ describe('adapter-config', () => { ...@@ -22,6 +22,51 @@ describe('adapter-config', () => {
expect(next.cliOutput).toContain('called modify config in adapter') expect(next.cliOutput).toContain('called modify config in adapter')
}) })
it('keeps revalidating metadata as a prerender backed by an app route', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const pathname = '/docs/revalidating/sitemap.xml'
const prerender = outputs.prerenders.find(
(output) => output.pathname === pathname
)
expect(prerender).toBeDefined()
expect(prerender?.fallback?.initialRevalidate).toBe(5)
const appRoute = outputs.appRoutes.find(
(output) => output.pathname === pathname
)
expect(appRoute).toBeDefined()
expect(prerender?.parentOutputId).toBe(appRoute?.id)
expect(
outputs.staticFiles.find((output) => output.pathname === pathname)
).toBeUndefined()
})
it('keeps tagged metadata as a prerender backed by an app route', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const pathname = '/docs/tagged/sitemap.xml'
const prerender = outputs.prerenders.find(
(output) => output.pathname === pathname
)
expect(prerender).toBeDefined()
expect(prerender?.fallback?.initialRevalidate).toBe(false)
expect(
prerender?.fallback?.initialHeaders?.['x-next-cache-tags']
).toContain('adapter-config:tagged-sitemap')
const appRoute = outputs.appRoutes.find(
(output) => output.pathname === pathname
)
expect(appRoute).toBeDefined()
expect(prerender?.parentOutputId).toBe(appRoute?.id)
expect(
outputs.staticFiles.find((output) => output.pathname === pathname)
).toBeUndefined()
})
it('should call onBuildComplete with correct context', async () => { it('should call onBuildComplete with correct context', async () => {
expect(next.cliOutput).toContain('onBuildComplete called') expect(next.cliOutput).toContain('onBuildComplete called')
......
import type { MetadataRoute } from 'next'
export const revalidate = 5
export default function sitemap(): MetadataRoute.Sitemap {
return [{ url: 'https://example.com' }]
}
import type { MetadataRoute } from 'next'
import { unstable_cache } from 'next/cache'
export default unstable_cache(
async (): Promise<MetadataRoute.Sitemap> => [{ url: 'https://example.com' }],
['adapter-config:tagged-sitemap'],
{ tags: ['adapter-config:tagged-sitemap'] }
)
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