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,8 +471,6 @@ describe('accumulateMetadata', () => {
},
})
const metadataItems2: MetadataItems = [
[
function gM2() {
return {
openGraph: {
......@@ -476,7 +478,11 @@ describe('accumulateMetadata', () => {
},
// twitter is not specified, supposed to merged with openGraph but images should not be picked up
}
},
}
const metadataItems2: MetadataItems = [
[
Object.assign(gM2, { $$original: gM2 }),
// has static metadata files
{
icon: undefined,
......
......@@ -23,6 +23,7 @@ import type { ParsedUrlQuery } from 'querystring'
import type { StaticMetadata } from './types/icons'
import type { WorkStore } from '../../server/app-render/work-async-storage.external'
import type { Params } from '../../server/request/params'
import type { SearchParams } from '../../server/request/search-params'
// eslint-disable-next-line import/no-extraneous-dependencies
import 'server-only'
......@@ -58,15 +59,31 @@ import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import * as Log from '../../build/output/log'
import { createServerParamsForMetadata } from '../../server/request/params'
import type { MetadataBaseURL } from './resolvers/resolve-url'
import {
getUseCacheFunctionInfo,
isUseCacheFunction,
} from '../client-and-server-references'
import type {
UseCacheLayoutProps,
UseCachePageProps,
} from '../../server/use-cache/use-cache-wrapper'
import { createLazyResult } from '../../server/lib/lazy-result'
type StaticIcons = Pick<ResolvedIcons, 'icon' | 'apple'>
type MetadataResolver = (
parent: ResolvingMetadata
) => Metadata | Promise<Metadata>
type ViewportResolver = (
parent: ResolvingViewport
) => Viewport | Promise<Viewport>
type Resolved<T> = T extends Metadata ? ResolvedMetadata : ResolvedViewport
type InstrumentedResolver<TData> = ((
parent: Promise<Resolved<TData>>
) => TData | Promise<TData>) & {
$$original: (
props: unknown,
parent: Promise<Resolved<TData>>
) => TData | Promise<TData>
}
type MetadataResolver = InstrumentedResolver<Metadata>
type ViewportResolver = InstrumentedResolver<Viewport>
export type MetadataErrorType = 'not-found' | 'forbidden' | 'unauthorized'
......@@ -87,13 +104,17 @@ type BuildState = {
}
type LayoutProps = {
params: { [key: string]: any }
params: Promise<Params>
}
type PageProps = {
params: { [key: string]: any }
searchParams: { [key: string]: any }
params: Promise<Params>
searchParams: Promise<SearchParams>
}
type SegmentProps = LayoutProps | PageProps
type UseCacheSegmentProps = UseCacheLayoutProps | UseCachePageProps
function isFavicon(icon: IconDescriptor | undefined): boolean {
if (!icon) {
return false
......@@ -461,12 +482,15 @@ function mergeViewport({
function getDefinedViewport(
mod: any,
props: any,
props: SegmentProps,
tracingProps: { route: string }
): Viewport | ViewportResolver | null {
if (typeof mod.generateViewport === 'function') {
const { route } = tracingProps
return (parent: ResolvingViewport) =>
const segmentProps = createSegmentProps(mod.generateViewport, props)
return Object.assign(
(parent: ResolvingViewport) =>
getTracer().trace(
ResolveMetadataSpan.generateViewport,
{
......@@ -475,7 +499,9 @@ function getDefinedViewport(
'next.page': route,
},
},
() => mod.generateViewport(props, parent)
() => mod.generateViewport(segmentProps, parent)
),
{ $$original: mod.generateViewport }
)
}
return mod.viewport || null
......@@ -483,12 +509,15 @@ function getDefinedViewport(
function getDefinedMetadata(
mod: any,
props: any,
props: SegmentProps,
tracingProps: { route: string }
): Metadata | MetadataResolver | null {
if (typeof mod.generateMetadata === 'function') {
const { route } = tracingProps
return (parent: ResolvingMetadata) =>
const segmentProps = createSegmentProps(mod.generateMetadata, props)
return Object.assign(
(parent: ResolvingMetadata) =>
getTracer().trace(
ResolveMetadataSpan.generateMetadata,
{
......@@ -497,15 +526,33 @@ function getDefinedMetadata(
'next.page': route,
},
},
() => mod.generateMetadata(props, parent)
() => mod.generateMetadata(segmentProps, parent)
),
{ $$original: mod.generateMetadata }
)
}
return mod.metadata || null
}
/**
* If `fn` is a `'use cache'` function, we add special markers to the props,
* that the cache wrapper reads and removes, before passing the props to the
* user function.
*/
function createSegmentProps(
fn: Function,
props: SegmentProps
): SegmentProps | UseCacheSegmentProps {
return isUseCacheFunction(fn)
? 'searchParams' in props
? { ...props, $$isPage: true }
: { ...props, $$isLayout: true }
: props
}
async function collectStaticImagesFiles(
metadata: AppDirModules['metadata'],
props: any,
props: SegmentProps,
type: keyof NonNullable<AppDirModules['metadata']>
) {
if (!metadata?.[type]) return undefined
......@@ -522,7 +569,7 @@ async function collectStaticImagesFiles(
async function resolveStaticMetadata(
modules: AppDirModules,
props: any
props: SegmentProps
): Promise<StaticMetadata> {
const { metadata } = modules
if (!metadata) return null
......@@ -557,7 +604,7 @@ async function collectMetadata({
tree: LoaderTree
metadataItems: MetadataItems
errorMetadataItem: MetadataItems[number]
props: any
props: SegmentProps
route: string
errorConvention?: MetadataErrorType
}) {
......@@ -608,7 +655,7 @@ async function collectViewport({
tree: LoaderTree
viewportItems: ViewportItems
errorViewportItemRef: ErrorViewportItemRef
props: any
props: SegmentProps
route: string
errorConvention?: MetadataErrorType
}) {
......@@ -700,25 +747,14 @@ async function resolveMetadataItemsImpl(
}
const params = createServerParamsForMetadata(currentParams, workStore)
let layerProps: LayoutProps | PageProps
if (isPage) {
layerProps = {
params,
searchParams,
}
} else {
layerProps = {
params,
}
}
const props: SegmentProps = isPage ? { params, searchParams } : { params }
await collectMetadata({
tree,
metadataItems,
errorMetadataItem,
errorConvention,
props: layerProps,
props,
route: currentTreePrefix
// __PAGE__ shouldn't be shown in a route
.filter((s) => s !== PAGE_SEGMENT_KEY)
......@@ -963,7 +999,7 @@ function prerenderMetadata(metadataItems: MetadataItems) {
> = []
for (let i = 0; i < metadataItems.length; i++) {
const metadataExport = metadataItems[i][0]
getResult(resolversAndResults, metadataExport)
getResult<Metadata>(resolversAndResults, metadataExport)
}
return resolversAndResults
}
......@@ -977,21 +1013,54 @@ function prerenderViewport(viewportItems: ViewportItems) {
> = []
for (let i = 0; i < viewportItems.length; i++) {
const viewportExport = viewportItems[i]
getResult(resolversAndResults, viewportExport)
getResult<Viewport>(resolversAndResults, viewportExport)
}
return resolversAndResults
}
type Resolved<T> = T extends Metadata ? ResolvedMetadata : ResolvedViewport
const noop = () => {}
function getResult<T extends Metadata | Viewport>(
resolversAndResults: Array<((value: Resolved<T>) => void) | Result<T>>,
exportForResult: null | T | ((parent: Promise<Resolved<T>>) => Result<T>)
function getResult<TData extends object>(
resolversAndResults: Array<
((value: Resolved<TData>) => void) | Result<TData>
>,
exportForResult: null | TData | InstrumentedResolver<TData>
) {
if (typeof exportForResult === 'function') {
const result = exportForResult(
new Promise<Resolved<T>>((resolve) => resolversAndResults.push(resolve))
// If the function is a 'use cache' function that uses the parent data as
// the second argument, we don't want to eagerly execute it during
// metadata/viewport pre-rendering, as the parent data might also be
// computed from another 'use cache' function. To ensure that the hanging
// input abort signal handling works in this case (i.e. the depending
// function waits for the cached input to resolve while encoding its args),
// they must be called sequentially. This can be accomplished by wrapping
// the call in a lazy promise, so that the original function is only called
// when the result is actually awaited.
const useCacheFunctionInfo = getUseCacheFunctionInfo(
exportForResult.$$original
)
if (useCacheFunctionInfo && useCacheFunctionInfo.usedArgs[1]) {
const promise = new Promise<Resolved<TData>>((resolve) =>
resolversAndResults.push(resolve)
)
resolversAndResults.push(
createLazyResult(async () => exportForResult(promise))
)
} else {
let result: TData | Promise<TData>
if (useCacheFunctionInfo) {
resolversAndResults.push(noop)
// @ts-expect-error We intentionally omit the parent argument, because
// we know from the check above that the 'use cache' function does not
// use it.
result = exportForResult()
} else {
result = exportForResult(
new Promise<Resolved<TData>>((resolve) =>
resolversAndResults.push(resolve)
)
)
}
resolversAndResults.push(result)
if (result instanceof Promise) {
// since we eager execute generateMetadata and
......@@ -1004,6 +1073,7 @@ function getResult<T extends Metadata | Viewport>(
}
})
}
}
} else if (typeof exportForResult === 'object') {
resolversAndResults.push(exportForResult)
} else {
......
......@@ -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
let isPageOrLayoutSegmentFunction = 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
// 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 }] = args
const [
{ params: outerParams, searchParams: outerSearchParams },
...otherOuterArgs
] = args
const props: UseCacheInnerPageComponentProps = {
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 ({
[name]: async (
{
params: _innerParams,
searchParams: innerSearchParams,
}: UseCacheInnerPageComponentProps) =>
}: 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, $$isLayout, ...outerSlots },
...otherOuterArgs
] = args
const [{ params: outerParams, $$isLayoutComponent, ...outerSlots }] =
args
// Overwrite the props to omit $$isLayoutComponent.
args = [{ params: outerParams, ...outerSlots }]
// 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 ({
[name]: async (
{
params: _innerParams,
...innerSlots
}: Omit<UseCacheLayoutComponentProps, '$$isLayoutComponent'>) =>
originalFn.apply(null, [{ params: outerParams, ...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