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

[Cache Components] Fix caching in `generateMetadata`/`generateViewport` (#84228)

When using `'use cache'` in `generateMetadata` or `generateViewport`,
the caching did not work correctly, because we didn't apply the same
special handling for the `params` and `searchParams` props that we do
for layout and page components. This caused the following issues:

- `generateMetadata`/`generateViewport` for a page without params, or
with static params, yielded cache misses when resuming
- `generateMetadata` for a page/layout with unused params, became
dynamic when prerendering a fallback shell
- `generateMetadata` for a page with used search params, produced a
timeout error during prerendering
- `generateViewport` for a page/layout with unused params, produced a
build error (unless opting into fully dynamic rendering)

Still to be done in a follow-up: Omit unused `params` from cache keys,
and upgrade cache keys when they are used, to avoid unnecessary cache
misses when resuming.

closes NAR-321
parent c9c62856
import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info'
import {
extractInfoFromServerReferenceId,
type ServerReferenceInfo,
} from '../shared/lib/server-reference-info'
// Only contains the properties we're interested in.
export interface ServerReference {
......@@ -27,6 +30,18 @@ export function isUseCacheFunction<T>(
return type === 'use-cache'
}
export function getUseCacheFunctionInfo<T>(
value: T & Partial<ServerReference>
): ServerReferenceInfo | null {
if (!isServerReference(value)) {
return null
}
const info = extractInfoFromServerReferenceId(value.$$id)
return info.type === 'use-cache' ? info : null
}
export function isClientReference(mod: any): boolean {
const defaultExport = mod?.default || mod
return defaultExport?.$$typeof === Symbol.for('react.client.reference')
......
......@@ -46,9 +46,13 @@ function mapUrlsToStrings(obj: any) {
describe('accumulateMetadata', () => {
describe('typing', () => {
it('should support both sync and async metadata', async () => {
const generateMetadata = () => Promise.resolve({ description: 'child' })
const metadataItems: MetadataItems = [
[{ description: 'parent' }, null],
[() => Promise.resolve({ description: 'child' }), null],
[
Object.assign(generateMetadata, { $$original: generateMetadata }),
null,
],
]
const metadata = await accumulateMetadata(metadataItems)
......@@ -467,16 +471,18 @@ describe('accumulateMetadata', () => {
},
})
function gM2() {
return {
openGraph: {
images: undefined,
},
// twitter is not specified, supposed to merged with openGraph but images should not be picked up
}
}
const metadataItems2: MetadataItems = [
[
function gM2() {
return {
openGraph: {
images: undefined,
},
// twitter is not specified, supposed to merged with openGraph but images should not be picked up
}
},
Object.assign(gM2, { $$original: gM2 }),
// has static metadata files
{
icon: undefined,
......
......@@ -785,13 +785,13 @@ interface Viewport extends ViewportLayout {
colorScheme?: null | ColorSchemeEnum | undefined
}
type ResolvingViewport = Promise<Viewport>
interface ResolvedViewport extends ViewportLayout {
themeColor: null | ThemeColorDescriptor[]
colorScheme: null | ColorSchemeEnum
}
type ResolvingViewport = Promise<ResolvedViewport>
export type {
Metadata,
ResolvedMetadata,
......
......@@ -25,8 +25,8 @@ import type { Params } from '../request/params'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { OUTLET_BOUNDARY_NAME } from '../../lib/framework/boundary-constants'
import type {
UseCacheLayoutComponentProps,
UseCachePageComponentProps,
UseCacheLayoutProps,
UseCachePageProps,
} from '../use-cache/use-cache-wrapper'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import {
......@@ -793,14 +793,14 @@ async function createComponentTreeInternal(
let searchParams = createServerSearchParamsForServerPage(query, workStore)
if (isUseCacheFunction(PageComponent)) {
const UseCachePageComponent: React.ComponentType<UseCachePageComponentProps> =
const UseCachePageComponent: React.ComponentType<UseCachePageProps> =
PageComponent
pageElement = (
<UseCachePageComponent
params={params}
searchParams={searchParams}
$$isPageComponent
$$isPage
/>
)
} else {
......@@ -951,14 +951,14 @@ async function createComponentTreeInternal(
let serverSegment: React.ReactNode
if (isUseCacheFunction(SegmentComponent)) {
const UseCacheLayoutComponent: React.ComponentType<UseCacheLayoutComponentProps> =
const UseCacheLayoutComponent: React.ComponentType<UseCacheLayoutProps> =
SegmentComponent
serverSegment = (
<UseCacheLayoutComponent
{...parallelRouteProps}
params={params}
$$isLayoutComponent
$$isLayout
/>
)
} else {
......
......@@ -91,20 +91,20 @@ type CacheKeyParts =
| [buildId: string, id: string, args: unknown[]]
| [buildId: string, id: string, args: unknown[], hmrRefreshHash: string]
interface UseCacheInnerPageComponentProps {
interface UseCachePageInnerProps {
params: Promise<Params>
searchParams?: Promise<SearchParams>
}
export interface UseCachePageComponentProps {
export interface UseCachePageProps {
params: Promise<Params>
searchParams: Promise<SearchParams>
$$isPageComponent: true
$$isPage: true
}
export type UseCacheLayoutComponentProps = {
export type UseCacheLayoutProps = {
params: Promise<Params>
$$isLayoutComponent: true
$$isLayout: true
} & {
// The value type should be React.ReactNode. But such an index signature would
// be incompatible with the other two props.
......@@ -995,25 +995,29 @@ export function cache(
}
}
let isPageOrLayout = false
// For page and layout components, the cache function is overwritten,
// which allows us to apply special handling for params and searchParams.
// For pages and layouts we're using the outer params prop, and not the
// inner one that was serialized/deserialized. While it's not generally
// true for "use cache" args, in the case of `params` the inner and outer
// object are essentially equivalent, so this is safe to do (including
// fallback params that are hanging promises). It allows us to avoid
// waiting for the timeout, when prerendering a fallback shell of a cached
// page or layout that awaits params.
if (isPageComponent(args)) {
isPageOrLayout = true
const [{ params: outerParams, searchParams: outerSearchParams }] = args
const props: UseCacheInnerPageComponentProps = {
let isPageOrLayoutSegmentFunction = false
// For page and layout segment functions (i.e. the page/layout component,
// or generateMetadata/generateViewport), the cache function is
// overwritten, which allows us to apply special handling for params and
// searchParams. For pages and layouts we're using the outer params prop,
// and not the inner one that was serialized/deserialized. While it's not
// generally true for "use cache" args, in the case of `params` the inner
// and outer object are essentially equivalent, so this is safe to do
// (including fallback params that are hanging promises). It allows us to
// avoid waiting for the timeout, when prerendering a fallback shell of a
// cached page or layout that awaits params.
if (isPageSegmentFunction(args)) {
isPageOrLayoutSegmentFunction = true
const [
{ params: outerParams, searchParams: outerSearchParams },
...otherOuterArgs
] = args
const props: UseCachePageInnerProps = {
params: outerParams,
// Omit searchParams and $$isPageComponent.
// Omit searchParams and $$isPage.
}
if (isPrivate) {
......@@ -1022,13 +1026,16 @@ export function cache(
props.searchParams = outerSearchParams
}
args = [props]
args = [props, ...otherOuterArgs]
fn = {
[name]: async ({
params: _innerParams,
searchParams: innerSearchParams,
}: UseCacheInnerPageComponentProps) =>
[name]: async (
{
params: _innerParams,
searchParams: innerSearchParams,
}: UseCachePageInnerProps,
...otherInnerArgs: unknown[]
) =>
originalFn.apply(null, [
{
params: outerParams,
......@@ -1043,22 +1050,36 @@ export function cache(
// need to ensure that an error is shown.
makeErroringSearchParamsForUseCache(workStore),
},
...otherInnerArgs,
]),
}[name] as (...args: unknown[]) => Promise<unknown>
} else if (isLayoutComponent(args)) {
isPageOrLayout = true
} else if (isLayoutSegmentFunction(args)) {
isPageOrLayoutSegmentFunction = true
const [{ params: outerParams, $$isLayoutComponent, ...outerSlots }] =
args
// Overwrite the props to omit $$isLayoutComponent.
args = [{ params: outerParams, ...outerSlots }]
const [
{ params: outerParams, $$isLayout, ...outerSlots },
...otherOuterArgs
] = args
// Overwrite the props to omit $$isLayout. Note that slots are only
// passed to the layout component (if any are defined), and not to
// generateMetadata nor generateViewport. For those functions,
// outerSlots/innerSlots is an empty object, which is fine because we're
// just spreading it into the props.
args = [{ params: outerParams, ...outerSlots }, ...otherOuterArgs]
fn = {
[name]: async ({
params: _innerParams,
...innerSlots
}: Omit<UseCacheLayoutComponentProps, '$$isLayoutComponent'>) =>
originalFn.apply(null, [{ params: outerParams, ...innerSlots }]),
[name]: async (
{
params: _innerParams,
...innerSlots
}: Omit<UseCacheLayoutProps, '$$isLayout'>,
...otherInnerArgs: unknown[]
) =>
originalFn.apply(null, [
{ params: outerParams, ...innerSlots },
...otherInnerArgs,
]),
}[name] as (...args: unknown[]) => Promise<unknown>
}
......@@ -1120,14 +1141,14 @@ export function cache(
//
// fallthrough
case 'prerender':
if (!isPageOrLayout) {
// If the "use cache" function is not a page or a layout, we need to
// track dynamic access already when encoding the arguments. If
// params are passed explicitly into a "use cache" function (as
// opposed to receiving them automatically in a page or layout), we
// assume that the params are also accessed. This allows us to abort
// early, and treat the function as dynamic, instead of waiting for
// the timeout to be reached.
if (!isPageOrLayoutSegmentFunction) {
// If the "use cache" function is not a page or layout segment
// function, we need to track dynamic access already when encoding
// the arguments. If params are passed explicitly into a "use cache"
// function (as opposed to receiving them automatically in a page or
// layout), we assume that the params are also accessed. This allows
// us to abort early, and treat the function as dynamic, instead of
// waiting for the timeout to be reached.
const dynamicAccessAbortController = new AbortController()
encodedCacheKeyParts = await dynamicAccessAsyncStorage.run(
......@@ -1600,37 +1621,35 @@ export function cache(
return React.cache(cachedFn)
}
function isPageComponent(
/**
* Returns `true` if the `'use cache'` function is the page component itself,
* or `generateMetadata`/`generateViewport` in a page file.
*/
function isPageSegmentFunction(
args: any[]
): args is [UseCachePageComponentProps, undefined] {
if (args.length !== 2) {
return false
}
const [props, ref] = args
): args is [UseCachePageProps, ...unknown[]] {
const [maybeProps] = args
return (
ref === undefined && // server components receive an undefined ref arg
props !== null &&
typeof props === 'object' &&
(props as UseCachePageComponentProps).$$isPageComponent
maybeProps !== null &&
typeof maybeProps === 'object' &&
(maybeProps as UseCachePageProps).$$isPage === true
)
}
function isLayoutComponent(
/**
* Returns `true` if the `'use cache'` function is the layout component itself,
* or `generateMetadata`/`generateViewport` in a layout file.
*/
function isLayoutSegmentFunction(
args: any[]
): args is [UseCacheLayoutComponentProps, undefined] {
if (args.length !== 2) {
return false
}
const [props, ref] = args
): args is [UseCacheLayoutProps, ...unknown[]] {
const [maybeProps] = args
return (
ref === undefined && // server components receive an undefined ref arg
props !== null &&
typeof props === 'object' &&
(props as UseCacheLayoutComponentProps).$$isLayoutComponent
maybeProps !== null &&
typeof maybeProps === 'object' &&
(maybeProps as UseCacheLayoutProps).$$isLayout === true
)
}
......
import { Metadata } from 'next'
export async function generateMetadata({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}): Promise<Metadata> {
'use cache'
const title = (await searchParams).title
return { title: String(title) }
}
export default function Page() {
return null
}
import { Viewport } from 'next'
export async function generateViewport({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}): Promise<Viewport> {
'use cache'
const color = (await searchParams).color
return { themeColor: String(color) }
}
export default function Page() {
return null
}
......@@ -128,6 +128,46 @@ describe('use-cache-search-params', () => {
expect(cliOutput).not.toContain(getExpectedErrorMessage(route))
})
})
it('should show an error when searchParams are used inside of a cached generateMetadata', async () => {
const browser = await next.browser(
'/search-params-used-generate-metadata?title=foo'
)
await expect(browser).toDisplayRedbox(`
{
"description": "Route /search-params-used-generate-metadata used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/search-params-used-generate-metadata/page.tsx (9:17) @ generateMetadata
> 9 | const title = (await searchParams).title
| ^",
"stack": [
"generateMetadata app/search-params-used-generate-metadata/page.tsx (9:17)",
],
}
`)
})
it('should show an error when searchParams are used inside of a cached generateViewport', async () => {
const browser = await next.browser(
'/search-params-used-generate-viewport?color=red'
)
await expect(browser).toDisplayRedbox(`
{
"description": "Route /search-params-used-generate-viewport used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/search-params-used-generate-viewport/page.tsx (9:17) @ generateViewport
> 9 | const color = (await searchParams).color
| ^",
"stack": [
"generateViewport app/search-params-used-generate-viewport/page.tsx (9:17)",
],
}
`)
})
} else {
afterEach(async () => {
await next.stop()
......
import { Viewport } from 'next'
export async function generateViewport({
params,
}: {
params: Promise<{ color: string }>
}): Promise<Viewport> {
'use cache: remote'
// Use `eval` to side step compiler errors for using `arguments` in a 'use
// cache' function.
// eslint-disable-next-line no-eval
const unusedParentArg = eval('arguments')[1]
if (unusedParentArg !== undefined) {
throw new Error(
'Expected the unused parent argument to be omitted. Received: ' +
unusedParentArg
)
}
// We're reading params here. This makes the cache function dynamic during
// prerendering. It also requires suspense above body, so nothing will
// prerendered. The meta tag should still be cached on refreshes though.
const { color } = await params
return {
colorScheme: color === 'white' ? 'light' : 'dark',
maximumScale: 1 + Math.random(),
}
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <main>{children}</main>
}
import { Viewport } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateViewport({
params,
}: {
params: Promise<{ color: string }>
}): Promise<Viewport> {
'use cache: remote'
// Use `eval` to side step compiler errors for using `arguments` in a 'use
// cache' function.
// eslint-disable-next-line no-eval
const unusedParentArg = eval('arguments')[1]
if (unusedParentArg !== undefined) {
throw new Error(
'Expected the unused parent argument to be omitted. Received: ' +
unusedParentArg
)
}
// We're reading params here. This makes the cache function dynamic during
// prerendering. It also requires suspense above body, so nothing will
// prerendered. The meta tag should still be cached on refreshes though.
const { color } = await params
return { themeColor: color, initialScale: Math.random() }
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</p>
}
import { Metadata, ResolvingMetadata } from 'next'
export async function generateMetadata(
_: { params: Promise<{ slug: string }> },
parent: ResolvingMetadata
): Promise<Metadata> {
'use cache'
// We're not reading params here, but we do define a canonical URL, which
// leads to the pathname being read under the hood. This should make the
// function dynamic when prerendering the fallback shell, and not lead to a
// timeout error.
const { metadataBase } = await parent
return {
// We can not return a URL instance from a `'use cache'` function.
metadataBase: metadataBase?.replace('/foo', '/bar'),
}
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
import { Metadata, ResolvingMetadata } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateMetadata(
_: { params: Promise<{ slug: string }> },
parent: ResolvingMetadata
): Promise<Metadata> {
'use cache'
// We're not reading params here, but we do define a canonical URL, which
// leads to the pathname being read under the hood. This should make the
// function dynamic when prerendering the fallback shell, and not lead to a
// timeout error.
const { metadataBase } = await parent
return {
metadataBase: metadataBase?.replace('/bar', '/baz'),
alternates: { canonical: '/qux' },
}
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</p>
}
import { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://example.com/foo'),
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <main>{children}</main>
}
import { Metadata, ResolvingMetadata } from 'next'
export async function generateMetadata(
_: {},
parent: ResolvingMetadata
): Promise<Metadata> {
'use cache'
const { metadataBase } = await parent
return {
description: new Date().toISOString(),
// We can not return a URL instance from a `'use cache'` function.
metadataBase: metadataBase?.replace('/foo', '/bar'),
}
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
import { Metadata, ResolvingMetadata } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateMetadata(
_: { searchParams: Promise<Record<string, string | string[] | undefined>> },
parent: ResolvingMetadata
): Promise<Metadata> {
'use cache'
// Explicitly not reading search params here. The search params should be
// omitted from the cache key, so that we ensure a cache hit when resuming the
// partially prerendered page.
const { metadataBase } = await parent
return {
title: new Date().toISOString(),
metadataBase: metadataBase?.replace('/bar', '/baz'),
alternates: { canonical: '/qux' },
}
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</p>
}
import { Metadata } from 'next'
export async function generateMetadata(_: {
params: Promise<{ slug: string }>
}): Promise<Metadata> {
'use cache'
// Explicitly not reading params here. The description should appear in the
// partially prerendered page. TODO: When resuming the page, we should get a
// cache hit (from the RDC), but omitting unused params from cache keys (and
// upgrading cache keys when they are used) is not yet implemented.
return { description: new Date().toISOString() }
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
import { Metadata } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateMetadata(_: {
params: Promise<{ slug: string }>
}): Promise<Metadata> {
'use cache'
// Explicitly not reading params here. The title should appear in the
// partially prerendered page. TODO: When resuming the page, we should get a
// cache hit (from the RDC), but omitting unused params from cache keys (and
// upgrading cache keys when they are used) is not yet implemented.
return { title: new Date().toISOString() }
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</p>
}
import { Metadata } from 'next'
export async function generateMetadata({
params,
}: {
params: Promise<{ slug: string }>
}): Promise<Metadata> {
'use cache: remote'
// Use `eval` to side step compiler errors for using `arguments` in a 'use
// cache' function.
// eslint-disable-next-line no-eval
const unusedParentArg = eval('arguments')[1]
if (unusedParentArg !== undefined) {
throw new Error(
'Expected the unused parent argument to be omitted. Received: ' +
unusedParentArg
)
}
// We're reading params here. This makes the cache function dynamic during
// prerendering, and thus the description should be excluded from the
// partially prerendered page.
const { slug } = await params
return { description: new Date().toISOString(), category: slug }
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <main>{children}</main>
}
import { Metadata } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateMetadata({
params,
}: {
params: Promise<{ slug: string }>
}): Promise<Metadata> {
'use cache: remote'
// Use `eval` to side step compiler errors for using `arguments` in a 'use
// cache' function.
// eslint-disable-next-line no-eval
const unusedParentArg = eval('arguments')[1]
if (unusedParentArg !== undefined) {
throw new Error(
'Expected the unused parent argument to be omitted. Received: ' +
unusedParentArg
)
}
// We're reading params here. This makes the cache function dynamic during
// prerendering, and thus the title should be excluded from the partially
// prerendered page.
const { slug } = await params
return { title: new Date().toISOString(), keywords: [slug] }
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</p>
}
import { Viewport } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateViewport({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}): Promise<Viewport> {
'use cache'
// Explicitly not reading search params here. The search params should be
// omitted from the cache key, so that we ensure a cache hit when resuming the
// partially prerendered page.
return { initialScale: Math.random() }
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</p>
}
import { Viewport } from 'next'
export async function generateViewport({
params,
}: {
params: Promise<{ color: string }>
}): Promise<Viewport> {
'use cache'
// Explicitly not reading params here. The meta tag should appear in the
// partially prerendered page. TODO: When resuming the page, we should get a
// cache hit (from the RDC), but omitting unused params from cache keys (and
// upgrading cache keys when they are used) is not yet implemented.
return { maximumScale: 1 + Math.random() }
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <main>{children}</main>
}
import { Viewport } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateViewport({
params,
}: {
params: Promise<{ color: string }>
}): Promise<Viewport> {
'use cache'
// Explicitly not reading params here. The meta tag should appear in the
// partially prerendered page. TODO: When resuming the page, we should get a
// cache hit (from the RDC), but omitting unused params from cache keys (and
// upgrading cache keys when they are used) is not yet implemented.
return { initialScale: Math.random() }
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dynamic />
</Suspense>
)
}
async function Dynamic() {
await connection()
return <p>Dynamic</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