Commit f05f9eff authored by Janka Uryga's avatar Janka Uryga

tests

parent b455670b
......@@ -11,6 +11,8 @@ describe('segment cache (CDN cache busting)', () => {
return
}
// TODO(runtime-ppr): add tests for runtime prefetches
// To debug these tests locally, run:
// node start.mjs
//
......
import { Metadata } from 'next'
import { Suspense } from 'react'
import { cookies } from 'next/headers'
export async function generateMetadata(): Promise<Metadata> {
await cookies()
return {
title: 'Runtime-prefetchable title',
}
}
async function Content() {
await cookies()
return <div id="target-page">Target page</div>
}
export default function PageWithRuntimePrefetchableTitle() {
return (
<Suspense fallback="Loading...">
<Content />
</Suspense>
)
}
......@@ -21,6 +21,25 @@ export default function Page() {
</LinkAccordion>
</li>
</ul>
<hr />
<ul>
<li>
<LinkAccordion
prefetch="unstable_forceStale"
href="/page-with-runtime-prefetchable-head"
>
Page with runtime-prefetchable head (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
prefetch="unstable_forceStale"
href="/rewrite-to-page-with-runtime-prefetchable-head"
>
Rewrite to page with runtime-prefetchable head (prefetch=true)
</LinkAccordion>
</li>
</ul>
</>
)
}
......@@ -12,6 +12,10 @@ const nextConfig = {
source: '/rewrite-to-page-with-dynamic-head',
destination: '/page-with-dynamic-head',
},
{
source: '/rewrite-to-page-with-runtime-prefetchable-head',
destination: '/page-with-runtime-prefetchable-head',
},
]
},
}
......
......@@ -9,12 +9,9 @@ describe('segment cache (metadata)', () => {
test('disabled in development', () => {})
return
}
it(
"regression: prefetch the head if it's missing even if all other data " +
'is cached',
async () => {
let act
describe("regression: prefetch the head if it's missing even if all other data is cached", () => {
it('pages with dynamic content and dynamic metadata, using a full prefetch', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p) {
act = createRouterAct(p)
......@@ -75,6 +72,71 @@ describe('segment cache (metadata)', () => {
const title = await browser.eval(() => document.title)
expect(title).toBe('Dynamic Title')
}, 'no-requests')
}
)
})
it('pages with runtime-prefetchable content and dynamic metadata, using a runtime prefetch', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p) {
act = createRouterAct(p)
},
})
// Runtime-prefetch a page.
// It only uses cookies, so this should be a complete prefetch.
await act(async () => {
const checkbox = await browser.elementByCss(
'input[data-link-accordion="/page-with-runtime-prefetchable-head"]'
)
await checkbox.click()
}, [
// Because the link is prefetched with prefetch="unstable_forceStale",
// we should be able to prefetch the title, even though it's dynamic.
{
includes: 'Runtime-prefetchable title',
},
{
includes: 'Target page',
},
])
// Now runtime-prefetch a link that rewrites to the same underlying page.
await act(async () => {
const checkbox = await browser.elementByCss(
'input[data-link-accordion="/rewrite-to-page-with-runtime-prefetchable-head"]'
)
await checkbox.click()
}, [
// TODO: Ideally, this would not prefetch the dynamic title again,
// because it was already prefetched by the previous link, and both
// links resolve to the same underlying route. This is because, unlike
// segment data, we cache routes solely by their input URL, not by the
// path of the underlying route. Similarly, we don't cache metadata
// separately from the route tree. We should probably do one or both.
{
includes: 'Runtime-prefetchable title',
},
// It should not prefetch the page content again, because it was
// already cached.
{
includes: 'Target page',
block: 'reject',
},
])
// When we navigate to the page, it should not make any additional
// network requests, because both the segment data and the head were
// fully prefetched.
await act(async () => {
const link = await browser.elementByCss(
'a[href="/rewrite-to-page-with-runtime-prefetchable-head"]'
)
await link.click()
const pageContent = await browser.elementById('target-page')
expect(await pageContent.text()).toBe('Target page')
const title = await browser.eval(() => document.title)
expect(title).toBe('Runtime-prefetchable title')
}, 'no-requests')
})
})
})
import Link from 'next/link'
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
)
}
function Header() {
return (
<header>
<Link href="/" prefetch={false}>
Home
</Link>
</header>
)
}
import { DebugLinkAccordion } from '../components/link-accordion'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
unstable_cacheLife('minutes')
return (
<main>
<h2>shared layout prefetching - layout with cookies and dynamic data</h2>
<ul>
<li>
<DebugLinkAccordion href="/shared-layout/one" prefetch={true} />
</li>
<li>
<DebugLinkAccordion
href="/shared-layout/one"
prefetch={'unstable_forceStale'}
/>
</li>
</ul>
<ul>
<li>
<DebugLinkAccordion href="/shared-layout/two" prefetch={'auto'} />
</li>
<li>
<DebugLinkAccordion href="/shared-layout/two" prefetch={true} />
</li>
<li>
<DebugLinkAccordion
href="/shared-layout/two"
prefetch={'unstable_forceStale'}
/>
</li>
</ul>
<h2>shared layout prefetching - layout with cookies</h2>
<ul>
<li>
<DebugLinkAccordion
href="/runtime-prefetchable-layout/one"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/runtime-prefetchable-layout/two"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/runtime-prefetchable-layout/two"
prefetch={'unstable_forceStale'}
/>
</li>
</ul>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../shared'
export default async function Layout({ children }) {
return (
<main>
<div>
<h2>Shared layout</h2>
<DebugRenderKind />
<p id="shared-layout-description">
This shared layout uses cookies and no uncached IO, so it should be
completely runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-layout">{`Cookie from layout: ${cookieValue}`}</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'yellow' }}>Page one</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
{/*
TODO: a runtime-prefetched layout that had no holes itself will still be considered partial
if any other segment in the response is partial, because we don't track partiality per-segment,
so if we want to test that full prefetches can reuse layouts from runtime prefetches,
the whole page needs to be dynamically prerenderable.
*/}
{/* <Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense> */}
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, uncachedIO } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Page two</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-page">Dynamic content from page two</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../shared'
import { connection } from 'next/server'
export default async function Layout({ children }) {
return (
<main>
<div>
<h2>Shared layout</h2>
<DebugRenderKind />
<p id="shared-layout-description">
This shared layout uses cookies and some uncached IO, so parts of it
should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-layout">{`Cookie from layout: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-layout">Dynamic content from layout</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, uncachedIO } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'yellow' }}>Page one</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-page">Dynamic content from page one</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, uncachedIO } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Page two</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-page">Dynamic content from page two</div>
</div>
)
}
import { unstable_cacheLife } from 'next/cache'
import { setTimeout } from 'timers/promises'
export async function uncachedIO() {
await setTimeout(500)
}
export async function cachedDelay(time: number, cacheBuster?: any) {
'use cache'
unstable_cacheLife('minutes')
console.log('cachedDelay', time, cacheBuster)
await setTimeout(time)
}
export function DebugRenderKind() {
const { workUnitAsyncStorage } =
require('next/dist/server/app-render/work-unit-async-storage.external') as typeof import('next/dist/server/app-render/work-unit-async-storage.external')
const workUnitStore = workUnitAsyncStorage.getStore()!
return (
<div>
workUnitStore.type: {workUnitStore.type}
{(() => {
switch (workUnitStore.type) {
case 'prerender':
return '(static prefetch)'
case 'prerender-runtime':
return '(runtime prefetch)'
default:
return null
}
})()}
</div>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { ComponentProps, useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
data-prefetch={getPrefetchKind(prefetch)}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
export function DebugLinkAccordion({
href,
prefetch,
}: Omit<ComponentProps<typeof LinkAccordion>, 'children'>) {
const prefetchKind = getPrefetchKind(prefetch)
return (
<LinkAccordion href={href} prefetch={prefetch} data-prefetch={prefetch}>
{href} ({prefetchKind})
</LinkAccordion>
)
}
function getPrefetchKind(prefetch: LinkProps['prefetch']) {
switch (prefetch) {
case false:
return 'disabled'
case undefined:
case null:
case 'auto':
return 'auto'
case true:
return 'runtime'
case 'unstable_forceStale':
return 'full'
default:
prefetch satisfies never
}
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { cacheComponents: true, clientSegmentCache: true },
productionBrowserSourceMaps: true,
}
export default nextConfig
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page uses a short-lived private cache (staleTime &lt;
RUNTIME_PREFETCH_DYNAMIC_STALE, which is 30s), which should not be
included in a runtime prefetch
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<CachedButShortLived />
</Suspense>
</main>
)
}
async function CachedButShortLived() {
'use cache: private'
unstable_cacheLife({
stale: 5,
// the rest of the settings don't matter for private caches,
// because they are not persisted server-side
})
await cachedDelay(500, [__filename])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
Short-lived cached content
<div id="cached-value">{Date.now()}</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page uses a short-lived public cache (expire &lt; DYNAMIC_EXPIRE,
5min), which should not be included in a static prefetch, but should be
included in a runtime prefetch, because it has a long enough stale time
(&gt; RUNTIME_PREFETCH_DYNAMIC_STALE, 30s)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache />
</Suspense>
</main>
)
}
async function ShortLivedCache() {
'use cache'
unstable_cacheLife({
stale: 60, // > RUNTIME_PREFETCH_DYNAMIC_STALE
revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE
})
await cachedDelay(500, [__filename])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
Short-lived cached content
<div id="cached-value">{Date.now()}</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page uses a short-lived public cache (expire &lt; DYNAMIC_EXPIRE,
5min), which should not be included in a static prefetch, and should
also not be included in a runtime prefetch, because it has a short
enough stale time (&lt; RUNTIME_PREFETCH_DYNAMIC_STALE, 30s)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache />
</Suspense>
</main>
)
}
async function ShortLivedCache() {
'use cache'
unstable_cacheLife({
stale: 20, // < RUNTIME_PREFETCH_DYNAMIC_STALE
revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE
})
await cachedDelay(500, [__filename])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
Short-lived cached content
<div id="cached-value">{Date.now()}</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { ErrorBoundary } from '../../../../components/error-boundary'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page errors after a cookies call, so we should only see the error
in a runtime prefetch or a navigation (and not during prerendering /
prefetching)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<ErrorBoundary>
<One />
</ErrorBoundary>
</Suspense>
</main>
)
}
async function One(): Promise<never> {
const cookieStore = await cookies()
await cachedDelay(500, ['/cookies', cookieStore.get('user-agent')?.value])
throw new Error('Kaboom')
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page performs sync IO after a cookies() call, so we should only see
the error in a runtime prefetch or a navigation (and not during
prerendering / prefetching)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<One />
</Suspense>
</main>
)
}
async function One() {
const cookieStore = await cookies()
await cachedDelay(500, ['/cookies', cookieStore.get('user-agent')?.value])
return <div id="timestamp">Timestamp: {Date.now()}</div>
}
export default async function Page() {
return (
<main>
<h1>Fully static</h1>
<p id="intro">Hello from a fully static page!</p>
<p>
{new Array({ length: 1000 })
.fill(null)
.map(() => 'Lorem ipsum dolor sit amet.')}
</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies and no uncached IO, So it should be completely
prefetchable with a runtime prefetch.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies and some uncached IO, so parts of it should be
runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
<form
action={async (formData: FormData) => {
'use server'
const cookieStore = await cookies()
const cookieValue = formData.get('cookie') as string | null
if (cookieValue) {
cookieStore.set('testCookie', cookieValue)
}
}}
>
<input type="text" name="cookie" />
<button type="submit">Update cookie</button>
</form>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<DebugRenderKind />
<p>
This page uses params and some uncached IO, so parts of it should be
runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable params={params} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({ params }: { params: Promise<Params> }) {
const { id } = await params
await cachedDelay(500, [__filename, id])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="param-value">{`Param: ${id}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
return (
<main>
<DebugRenderKind />
<p>
This page uses search params and some uncached IO, so parts of it should
be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable searchParams={searchParams} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
const { searchParam } = await searchParams
await cachedDelay(500, [__filename, searchParam])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="search-param-value">{`Search param: ${searchParam}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies (from a private cache) and no uncached IO, So it
should be completely prefetchable with a runtime prefetch.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieValue = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
</div>
)
}
async function privateCache() {
'use cache: private'
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return cookieValue
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies (from inside a private cache) and some uncached
IO, so parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
<form
action={async (formData: FormData) => {
'use server'
const cookieStore = await cookies()
const cookieValue = formData.get('cookie') as string | null
if (cookieValue) {
cookieStore.set('testCookie', cookieValue)
}
}}
>
<input type="text" name="cookie" />
<button type="submit">Update cookie</button>
</form>
</main>
)
}
async function RuntimePrefetchable() {
const cookieValue = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache() {
'use cache: private'
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return cookieValue
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses Date.now (in a private cache) and some uncached IO, so
parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const now = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="timestamp">{`Timestamp: ${now}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache() {
'use cache: private'
const now = Date.now()
await cachedDelay(500, [__filename])
return now
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<DebugRenderKind />
<p>
This page uses params (passed to a private cache) and some uncached IO,
so parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable params={params} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({ params }: { params: Promise<Params> }) {
const id = await privateCache(params)
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="param-value">{`Param: ${id}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache(params: Promise<Params>) {
'use cache: private'
const { id } = await params
await cachedDelay(500, [__filename, id])
return id
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
return (
<main>
<DebugRenderKind />
<p>
This page uses search params (passed to a private cache) and some
uncached IO, so parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable searchParams={searchParams} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
const searchParam = await privateCache(searchParams)
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="search-param-value">{`Search param: ${searchParam}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache(searchParams: Promise<AnySearchParams>) {
'use cache: private'
const { searchParam } = await searchParams
await cachedDelay(500, [__filename, searchParam])
return searchParam
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
)
}
function Header() {
return (
<header>
<Link href="/" prefetch={false}>
Home
</Link>
</header>
)
}
import { DebugLinkAccordion } from '../../components/link-accordion'
export default async function Page() {
return (
<main>
<h1>Home</h1>
<h2>directly in a page</h2>
<ul>
<li>
cookies + dynamic content
<ul>
<li>
<DebugLinkAccordion href="/in-page/cookies" prefetch={true} />
</li>
</ul>
</li>
<li>
search params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-page/search-params?searchParam=123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-page/search-params?searchParam=456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
dynamic params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-page/dynamic-params/123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-page/dynamic-params/456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
only cookies
<ul>
<li>
<DebugLinkAccordion
href="/in-page/cookies-only"
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>
<code>use cache: private</code>
</h2>
<ul>
<li>
cookies in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/cookies"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
dynamic params in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/dynamic-params/123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-private-cache/dynamic-params/456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
search params in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/search-params?searchParam=123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-private-cache/search-params?searchParam=456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
only cookies in private cache
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/cookies-only"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
Date.now() in private cache
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/date-now"
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>short-lived caches</h2>
<ul>
<li>
private, short stale
<ul>
<li>
<DebugLinkAccordion
href="/caches/private-short-stale"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/caches/private-short-stale"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
public, short expire, long enough stale
<ul>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-long-stale"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-long-stale"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
public, short expire, short stale
<ul>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-short-stale"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-short-stale"
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>misc</h2>
<ul>
<li>
<DebugLinkAccordion href="/fully-static" prefetch={true} />
</li>
</ul>
<h2>errors</h2>
<ul>
<li>
<DebugLinkAccordion
href="/errors/error-after-cookies"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/errors/sync-io-after-cookies"
prefetch={true}
/>
</li>
</ul>
</main>
)
}
import { unstable_cacheLife } from 'next/cache'
import { setTimeout } from 'timers/promises'
export async function uncachedIO() {
await setTimeout(500)
}
export async function cachedDelay(time: number, cacheBuster?: any) {
'use cache'
unstable_cacheLife('minutes')
console.log('cachedDelay', time, cacheBuster)
await setTimeout(time)
}
export function DebugRenderKind() {
const { workUnitAsyncStorage } =
require('next/dist/server/app-render/work-unit-async-storage.external') as typeof import('next/dist/server/app-render/work-unit-async-storage.external')
const workUnitStore = workUnitAsyncStorage.getStore()!
return (
<div>
workUnitStore.type: {workUnitStore.type}
{(() => {
switch (workUnitStore.type) {
case 'prerender':
return '(static prefetch)'
case 'prerender-runtime':
return '(runtime prefetch)'
default:
return null
}
})()}
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses root params and some uncached IO. Root params should
always be available in static prerenders, so a runtime prefetch should
have them too.
</p>
<StaticallyPrefetchable />
</main>
)
}
async function StaticallyPrefetchable() {
const currentLang = await lang()
await cachedDelay(500, [__filename, currentLang])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses root params (inside a private cache) and some uncached
IO. Private caches are only rendered during runtime prefetches and
navigation requests, so they won't be part of a static prefetch, but
they should be part of a runtime prefetch.
</p>
<Suspense fallback="Loading 1...">
<DynamicallyPrefetchable />
</Suspense>
</main>
)
}
async function DynamicallyPrefetchable() {
const currentLang = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache() {
'use cache: private'
const currentLang = await lang()
await cachedDelay(500, [__filename, currentLang])
return currentLang
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import Link from 'next/link'
import { lang } from 'next/root-params'
import { ReactNode } from 'react'
export default async function RootLayout({
children,
}: {
children: ReactNode
}) {
const currentLang = await lang()
return (
<html lang={currentLang}>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
)
}
async function Header() {
const currentLang = await lang()
return (
<header>
<Link href={`/with-root-param/${currentLang}`} prefetch={false}>
Home (for lang: {currentLang})
</Link>
</header>
)
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
import { lang } from 'next/root-params'
import { DebugLinkAccordion } from '../../../components/link-accordion'
export default async function Page() {
const currentLang = await lang()
const otherLang = currentLang === 'en' ? 'de' : 'en'
return (
<main>
<h1>Home - with root param ({currentLang})</h1>
<h2>directly in a page</h2>
<ul>
<li>
root params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href={`/with-root-param/${currentLang}/in-page/root-params`}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={`/with-root-param/${otherLang}/in-page/root-params`}
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>
<code>use cache: private</code>
</h2>
<ul>
<li>
root params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href={`/with-root-param/${currentLang}/in-private-cache/root-params`}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={`/with-root-param/${otherLang}/in-private-cache/root-params`}
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
</main>
)
}
'use client'
import React from 'react'
export class ErrorBoundary extends React.Component<{
children: React.ReactNode
}> {
state = { error: null }
static getDerivedStateFromError(error) {
return { error }
}
render() {
if (this.state.error) {
return (
<div id="error-boundary">
Error boundary: {this.state.error.message}
</div>
)
}
return this.props.children
}
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { ComponentProps, useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
data-prefetch={getPrefetchKind(prefetch)}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
export function DebugLinkAccordion({
href,
prefetch,
}: Omit<ComponentProps<typeof LinkAccordion>, 'children'>) {
const prefetchKind = getPrefetchKind(prefetch)
return (
<LinkAccordion href={href} prefetch={prefetch} data-prefetch={prefetch}>
{href} ({prefetchKind})
</LinkAccordion>
)
}
function getPrefetchKind(prefetch: LinkProps['prefetch']) {
switch (prefetch) {
case false:
return 'disabled'
case undefined:
case null:
case 'auto':
return 'auto'
case true:
return 'runtime'
case 'unstable_forceStale':
return 'full'
default:
prefetch satisfies never
}
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { cacheComponents: true, clientSegmentCache: true },
productionBrowserSourceMaps: true,
}
export default nextConfig
......@@ -163,10 +163,19 @@ export function createRouterAct(
const originalResponse = await page.request.fetch(request, {
maxRedirects: 0,
})
// WORKAROUND:
// intercepting responses with 'Transfer-Encoding: chunked' (used for streaming)
// seems to be problematic sometimes, making the browser error with `net::ERR_INCOMPLETE_CHUNKED_ENCODING`.
// In particular, this seems to happen when blocking a streaming navigation response. (but not always)
// Playwright buffers the whole body anyway, so we can remove the header to sidestep this.
const headers = originalResponse.headers()
delete headers['transfer-encoding']
resolve({
text: await originalResponse.text(),
body: await originalResponse.body(),
headers: originalResponse.headers(),
headers,
status: originalResponse.status(),
})
}),
......
......@@ -20,6 +20,16 @@ export default function Page() {
Page with stale time of 10 minutes
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-stale-5-minutes" prefetch={true}>
Page whose runtime prefetch has a stale time of 5 minutes
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-stale-10-minutes" prefetch={true}>
Page whose runtime prefetch has a stale time of 10 minutes
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dynamic">Page with dynamic data</LinkAccordion>
</li>
......
import { Suspense } from 'react'
import { unstable_cacheLife as cacheLife } from 'next/cache'
import { cookies } from 'next/headers'
export default function Page() {
return (
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
)
}
async function RuntimePrefetchable() {
// Prevent this content from appearing in a regular prerender,
// But allow it to be included in a runtime prefetch.
await cookies()
return (
<Suspense fallback="Loading...">
<Content />
</Suspense>
)
}
async function Content() {
'use cache'
await new Promise((resolve) => setTimeout(resolve, 0))
cacheLife({ stale: 10 * 60 })
return 'Content with stale time of 10 minutes'
}
import { Suspense } from 'react'
import { unstable_cacheLife as cacheLife } from 'next/cache'
import { cookies } from 'next/headers'
export default function Page() {
return (
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
)
}
async function RuntimePrefetchable() {
// Prevent this content from appearing in a regular prerender,
// But allow it to be included in a runtime prefetch.
await cookies()
return (
<Suspense fallback="Loading...">
<Content />
</Suspense>
)
}
async function Content() {
'use cache'
await new Promise((resolve) => setTimeout(resolve, 0))
cacheLife({ stale: 5 * 60 })
return 'Content with stale time of 5 minutes'
}
'use client'
import Link from 'next/link'
import Link, { LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({ href, children }) {
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
......@@ -14,7 +22,9 @@ export function LinkAccordion({ href, children }) {
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
......
......@@ -79,6 +79,74 @@ describe('segment cache (staleness)', () => {
)
})
it('expires runtime prefetches when their stale time has elapsed', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
await page.clock.install()
// Reveal the links to trigger a runtime prefetch
const toggle5MinutesLink = await browser.elementByCss(
'input[data-link-accordion="/runtime-stale-5-minutes"]'
)
const toggle10MinutesLink = await browser.elementByCss(
'input[data-link-accordion="/runtime-stale-10-minutes"]'
)
await act(
async () => {
await toggle5MinutesLink.click()
await browser.elementByCss('a[href="/runtime-stale-5-minutes"]')
},
{
includes: 'Content with stale time of 5 minutes',
}
)
await act(
async () => {
await toggle10MinutesLink.click()
await browser.elementByCss('a[href="/runtime-stale-10-minutes"]')
},
{
includes: 'Content with stale time of 10 minutes',
}
)
// Hide the links
await toggle5MinutesLink.click()
await toggle10MinutesLink.click()
// Fast forward 5 minutes and 1 millisecond
await page.clock.fastForward(5 * 60 * 1000 + 1)
// Reveal the links again to trigger new prefetch tasks
await act(
async () => {
await toggle5MinutesLink.click()
await browser.elementByCss('a[href="/runtime-stale-5-minutes"]')
},
// The page with a stale time of 5 minutes is requested again
// because its stale time elapsed.
{
includes: 'Content with stale time of 5 minutes',
}
)
await act(
async () => {
await toggle10MinutesLink.click()
await browser.elementByCss('a[href="/runtime-stale-10-minutes"]')
},
// The page with a stale time of 10 minutes is *not* requested again
// because it's still fresh.
'no-requests'
)
})
it('reuses dynamic data up to the staleTimes.dynamic threshold', async () => {
let page: Playwright.Page
const startDate = Date.now()
......
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