Unverified Commit 9486750f authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

[evals] Cover focused Cache Components and Partial Prefetching cases (#97813)

## Summary

- update existing evals for synchronous I/O, instant shell validation,
and Cache Components configuration instead of adding duplicate fixtures
- add focused Partial Prefetching coverage for URL-data inclusion, the
prefetch stage, and the navigation stage
- retain focused Cache Components coverage for session isolation and
URL-dependent shells
- rebase onto current `canary` so the Partial Prefetching evals can use
the public `unstable_prefetch()` and `unstable_navigation()` API
references

## Coverage

The latest results use Claude Sonnet 4.6 for the coding agent and Claude
Haiku 4.5 for the agentic judge. The Partial Prefetching cases have been
rerun after the new API references landed, and the corrected Cache
Components criteria have also been rerun.

| Eval | Scenario | Baseline | Bundled docs |
| --- | --- | ---: | ---: |
| `agent-035-connection-dynamic` | Adopt Cache Components while keeping
synchronous request-time values fresh and stable navigation in the shell
| 5/5 | 5/5 |
| `agent-040-instant` | Follow default validation and keep a stable
product title ahead of live inventory | 4/4 | 4/4 |
| `agent-042-enable-ppr` | Translate legacy route configuration while
preserving hourly and request-specific behavior | 4/4 | 4/4 |
| `agent-048-prefetch-url-data` | Include cached URL-specific category
content in a selected per-link prefetch | 3/6 | 6/6 |
| `agent-049-prefetch-stage` | Exclude cached content from the App Shell
but include it in a selected prefetch | 1/5 | 5/5 |
| `agent-051-prefetch-until-navigation` | Prefetch a selected title
while deferring the rest until navigation | 0/5 | 5/5 |
| `agent-052-cache-components-session-isolation` | Reuse shared data
without placing member-specific request data in a public cache | 5/5 |
5/5 |
| `agent-053-cache-components-url-shell` | Keep URL data below a useful
shell and include every output-changing value in the cache key | 3/5 |
5/5 |

After the public API references landed, the prefetch-stage and
navigation-stage evals show the intended documentation signal. Baseline
Sonnet passed 1/5 criteria for `unstable_prefetch()` and 0/5 for
`unstable_navigation()`. With the canonical bundled-docs instruction,
Sonnet found the new references and passed all 5/5 criteria in both
cases. After clarifying that the URL-data navigation must not block and
linking the general navigation docs to the optimizing-prefetching guide,
the URL-data case improved from 3/6 without docs to 6/6 with bundled
docs.

## Result interpretation

- `agent-048` now passes 6/6 with bundled docs. The scoped documentation
link led the agent to the URL-data prefetch pattern instead of a
blocking render. Baseline Sonnet added `prefetch={true}` but relied on
the previous full-payload behavior and missed both the Partial
Prefetching configuration and cached URL data, resulting in 3/6.
- The low baseline scores for `agent-049` and `agent-051` are the
intended signal. Without the new references, the agents did not discover
the prefetch and navigation stages. With bundled docs, both cases pass
5/5.
- `agent-053` is also an intended documentation signal: the baseline hid
the useful shell behind a broad fallback, while bundled docs preserved
the shell and passed 5/5.
- `agent-035` now passes 5/5 in both conditions after removing an
unnecessary requirement for visible loading UI in one small metadata
region. `agent-052` also passes 5/5 in both conditions after removing
two failures for an omitted explicit `cacheLife()`, because the default
cache profile still applies, and clarifying for the judge that an
uncached component reading `cookies()` or `headers()` remains
request-specific without another opt-out marker.

## Overlap decisions

- `agent-035` now carries the synchronous-I/O adoption case, so the
duplicate `agent-051` fixture was removed.
- `agent-042` now carries the route-configuration migration case, so the
duplicate `agent-048` fixture was removed.
- `agent-034` remains focused on correct async `cookies()` and
`headers()` usage. `agent-052` tests the separate risk of leaking
request-specific values through a public cache.
- `agent-040` tests one meaningful shell under default validation.
`agent-041` still tests independent streaming across several dashboard
sections.
- `agent-048` intentionally brings cached URL-specific content into a
selected prefetch. `agent-053` tests the opposite shared-shell
requirement during Cache Components adoption.

## Verification

- Dry fixture generation passes for all eight cases in the table.
- `pnpm build-all`
- `agent-049-prefetch-stage`: baseline 1/5, bundled docs 5/5
- `agent-051-prefetch-until-navigation`: baseline 0/5, bundled docs 5/5
- `agent-035-connection-dynamic`: baseline 5/5, bundled docs 5/5
- `agent-048-prefetch-url-data`: baseline 3/6, bundled docs 6/6
- `agent-052-cache-components-session-isolation`: baseline 5/5, bundled
docs 5/5
- `pnpm exec tsc -p
evals/evals/agent-035-connection-dynamic/tsconfig.json --noEmit`
- `pnpm exec tsc -p evals/evals/agent-042-enable-ppr/tsconfig.json
--noEmit`

<!-- NEXT_JS_LLM -->
parent a8905ddf
...@@ -5,6 +5,7 @@ related: ...@@ -5,6 +5,7 @@ related:
links: links:
- app/api-reference/components/link - app/api-reference/components/link
- app/api-reference/file-conventions/loading - app/api-reference/file-conventions/loading
- app/guides/optimizing-prefetching
- app/guides/prefetching - app/guides/prefetching
--- ---
...@@ -95,7 +96,7 @@ By skipping or partially prefetching dynamic routes, Next.js avoids unnecessary ...@@ -95,7 +96,7 @@ By skipping or partially prefetching dynamic routes, Next.js avoids unnecessary
height="748" height="748"
/> />
> **Good to know:** See the [Prefetching guide](/docs/app/guides/prefetching) for the full behavior, including how to control prefetching per link and how it changes when you adopt [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching). > **Good to know:** See the [Prefetching guide](/docs/app/guides/prefetching) for the full behavior, including how to control prefetching per link and how it changes when you adopt [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching). To include URL-dependent content in a link's prefetch, see [Optimizing prefetching](/docs/app/guides/optimizing-prefetching).
To improve the navigation experience to dynamic routes, you can use [streaming](#streaming). To improve the navigation experience to dynamic routes, you can use [streaming](#streaming).
......
/** /** Cache Components: synchronous request-time I/O in shared UI. */
* connection() for Dynamic Rendering
*
* Tests whether the agent uses connection() from next/server to force dynamic
* rendering instead of the deprecated unstable_noStore().
*
* Tricky because agents use unstable_noStore(), force-dynamic segment config,
* or unrelated Dynamic APIs instead of the stable connection() function.
*/
import { expect, test } from 'vitest' import { expect, test } from 'vitest'
import { readFileSync, existsSync, readdirSync } from 'fs' import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path' import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
function readAppFiles(): string {
const appDir = join(process.cwd(), 'app') const IGNORE_DIRS = new Set(['.git', '.next', 'node_modules', 'dist', 'build'])
if (!existsSync(appDir)) return ''
const entries = readdirSync(appDir, { recursive: true }) as string[] function readSource(dir: string): string[] {
const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts')) if (!existsSync(dir)) return []
return files.map((f) => readFileSync(join(appDir, f), 'utf-8')).join('\n') return readdirSync(dir).flatMap((entry) => {
if (IGNORE_DIRS.has(entry)) return []
const path = join(dir, entry)
if (statSync(path).isDirectory()) return readSource(path)
if (entry === 'EVAL.ts' || !/\.(ts|tsx|js|jsx)$/.test(entry)) return []
return readFileSync(path, 'utf8')
})
} }
test('Component imports connection from next/server', () => { const source = readSource(process.cwd()).join('\n')
const content = readAppFiles() const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf8')
// Should import connection from next/server test('enables Cache Components without opt-outs', () => {
expect(content).toMatch(/import.*connection.*from\s+['"]next\/server['"]/) expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/)
}) })
test('Component uses await connection()', () => { test('uses an explicit synchronous I/O boundary', () => {
const content = readAppFiles() expect(source).toMatch(/\b(?:io|connection)\s*\(/)
expect(source).toMatch(/<Suspense[\s>]/)
// connection() returns a Promise and must be awaited
expect(content).toMatch(/await\s+connection\s*\(\s*\)/)
}) })
test('Component is async', () => { test('keeps the operations frame useful while metadata loads', async () => {
const content = readAppFiles() await expect(environment).toSatisfyCriterion(
`The stable Operations navigation and page frame must remain outside the Suspense boundary used for request metadata. Accept equivalent component and file organization.`
// Component must be async to use await )
expect(content).toMatch(/async\s+function|export\s+default\s+async/)
}) })
test('Component uses Date for timestamp', () => { test('keeps request metadata fresh', async () => {
const content = readAppFiles() await expect(environment).toSatisfyCriterion(
`The request identifier, current time, and sampling value must remain request-specific. Render them in a focused async child that awaits io() or connection() before calling randomUUID, new Date or Date.now, and Math.random. Prefer io() unless the implementation specifically needs to wait for a real user request. Accept equivalent component and file organization.`
// Should use Date for generating timestamp )
expect(content).toMatch(/new\s+Date\s*\(|Date\.now\s*\(/)
}) })
test('Does NOT use unstable_noStore (deprecated)', () => { test('does not reuse request metadata', async () => {
const content = readAppFiles() await expect(environment).toSatisfyCriterion(
`The request identifier, current time, and sampling value must not be cached, evaluated at module scope, or replaced with static values. Reject any solution that can reuse those values across requests. Accept equivalent component and file organization.`
// Should NOT use deprecated unstable_noStore )
expect(content).not.toMatch(/unstable_noStore/)
})
test('Does NOT use force-dynamic segment config as primary approach', () => {
const content = readAppFiles()
// Should use connection() as the primary approach instead of segment config
const hasForceDynamic =
content.includes("dynamic = 'force-dynamic'") ||
content.includes('dynamic = "force-dynamic"')
const hasConnection = /connection\s*\(\s*\)/.test(content)
// Enforce that connection() is the primary dynamic approach
// If force-dynamic is used, it cannot be the only dynamic mechanism
// When connection() is available/used, force-dynamic should not be redundantly added
if (hasForceDynamic && !hasConnection) {
// force-dynamic is being used as the sole dynamic mechanism (wrong)
expect.fail(
'force-dynamic segment config should not be the primary approach - use connection() instead'
)
}
}) })
Create a server component that displays the current server timestamp on each request. The timestamp should be different on every page load (not prerendered at build time). Use Next.js's recommended approach for opting out of static prerendering when you need dynamic data without using cookies/headers. Enable Cache Components for this operations console. The navigation must stay immediately useful, while the request identifier, current time, and sampling value must still be generated per request. Finish with a production build and do not leave routes opted out.
import type { Metadata } from 'next' import type { ReactNode } from 'react'
import { RequestMetadata } from '@/components/request-metadata'
export const metadata: Metadata = { export default function RootLayout({ children }: { children: ReactNode }) {
title: 'Random Number',
description: 'Display a random number on each request',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return ( return (
<html lang="en"> <html lang="en">
<body>{children}</body> <body>
<nav>Operations</nav>
<RequestMetadata />
{children}
</body>
</html> </html>
) )
} }
export default function Home() { export default function HomePage() {
return ( return (
<main> <main>
<h1>Random Number Generator</h1> <h1>Deployment health</h1>
<p>Please implement a random number that changes on each request.</p> <p>All systems operational</p>
</main> </main>
) )
} }
import { randomUUID } from 'node:crypto'
export function RequestMetadata() {
const generatedAt = new Date().toISOString()
const sample = Math.random()
const requestId = randomUUID()
return (
<aside>
Request {requestId} generated at {generatedAt} (sample {sample})
</aside>
)
}
...@@ -23,5 +23,5 @@ ...@@ -23,5 +23,5 @@
"target": "ES2017" "target": "ES2017"
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules", "EVAL.ts"]
} }
/** /**
* Instant Navigations * Instant Validation
* *
* Verifies that the agent enables instant navigation on the product route. * Starts with a non-instant navigation and verifies that the agent follows the
* * framework's default validation feedback to produce a meaningful Cache
* The eval harness runs `next build` as a script — with `cacheComponents: true`, * Components shell: the stable title is available immediately while live
* the build validates that the caching structure produces an instant static shell. * inventory streams behind a Suspense boundary.
* This test checks the agent actually exported `instant` (the build would
* pass without it, since Suspense alone satisfies the build on a static route).
*/ */
import { expect, test } from 'vitest' import { expect, test } from 'vitest'
import { readFileSync, existsSync, readdirSync, statSync } from 'fs' import { environment } from '@vercel/agent-eval/eval'
import { join } from 'path'
type SourceFile = { path: string; content: string }
const IGNORE_DIRS = new Set([
'.git',
'.next',
'node_modules',
'dist',
'build',
'coverage',
])
const IGNORE_FILES = new Set(['EVAL.ts', 'PROMPT.md']) test('keeps the product title in the static shell', async () => {
await expect(environment).toSatisfyCriterion(
`The product title "Premium Widget" must render in the product page's static shell. It must remain outside the Suspense boundary and async work used for the live inventory, so the title is available before the inventory resolves.
function readSourceFiles(dir: string): SourceFile[] { Accept equivalent component and file organization. Reject solutions where the page awaits the inventory before returning or places the title behind the inventory boundary.`
if (!existsSync(dir)) return [] )
})
const files: SourceFile[] = []
for (const entry of readdirSync(dir)) {
if (IGNORE_DIRS.has(entry)) continue
const fullPath = join(dir, entry)
const stats = statSync(fullPath)
if (stats.isDirectory()) { test('streams inventory behind a meaningful fallback', async () => {
files.push(...readSourceFiles(fullPath)) await expect(environment).toSatisfyCriterion(
continue `The inventory count and price must render from an async child beneath a Suspense boundary with a visible, meaningful fallback. The product page must be able to return its title and fallback without waiting for getInventory().
}
if (IGNORE_FILES.has(entry)) continue Accept equivalent component and file organization. Reject a null or empty fallback, or a solution where the page awaits inventory before returning.`
)
})
if (/\.(ts|tsx|js|jsx)$/.test(entry)) { test('keeps inventory live and uncached', async () => {
files.push({ await expect(environment).toSatisfyCriterion(
path: fullPath, `The randomized inventory must remain request-time data. Preserve the runtime boundary in getInventory(), such as connection(), and do not cache the inventory or replace its count and price with static values.
content: readFileSync(fullPath, 'utf-8'),
})
}
}
return files Accept equivalent component and file organization. Reject any solution that makes the randomized inventory reusable across requests.`
} )
})
const sourceFiles = readSourceFiles(process.cwd()) test('keeps default instant validation enabled', async () => {
await expect(environment).toSatisfyCriterion(
`The solution must keep the framework's default instant validation enabled and solve the static-shell problem directly. It must not add instant = false, disable Cache Components, or use Partial Prefetching as a substitute for a valid product shell.
test('instant exported from the product route', () => { Accept equivalent component and file organization.`
const productPage = sourceFiles.find(
(f) => f.path.includes('product') && /page\.(tsx?|jsx?)$/.test(f.path)
) )
expect(productPage).toBeDefined()
expect(productPage!.content).toMatch(/export\s+(const|var|let)\s+instant\b/)
expect(productPage!.content).toMatch(/prefetch\s*:\s*['"]static['"]/)
}) })
Navigating from home to the product page is slow. The title should appear immediately. Navigating from home to the product page is slow. Make the product title appear immediately while the live inventory loads.
...@@ -23,5 +23,5 @@ ...@@ -23,5 +23,5 @@
"target": "ES2017" "target": "ES2017"
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules", "EVAL.ts"]
} }
/** /**
* Enable PPR * Cache Components: route config semantics
* *
* Tests whether the agent knows that partial pre-rendering is enabled via * Verifies that adoption translates legacy configuration instead of deleting
* `cacheComponents: true` in next.config.ts, NOT the old * behavior or silencing validation.
* `experimental: { ppr: true }` flag.
*
* Tricky because most training data and older docs reference the experimental
* flag. The current way to enable PPR in Next.js 16 is `cacheComponents: true`.
*/ */
import { expect, test } from 'vitest' import { expect, test } from 'vitest'
import { readFileSync } from 'fs' import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path' import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set(['.git', '.next', 'node_modules', 'dist', 'build'])
function readSource(dir: string): string[] {
if (!existsSync(dir)) return []
return readdirSync(dir).flatMap((entry) => {
if (IGNORE_DIRS.has(entry)) return []
const path = join(dir, entry)
if (statSync(path).isDirectory()) return readSource(path)
if (entry === 'EVAL.ts' || !/\.(ts|tsx|js|jsx)$/.test(entry)) return []
return readFileSync(path, 'utf8')
})
}
test('Enables PPR via cacheComponents in next.config', () => { const source = readSource(process.cwd()).join('\n')
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8') const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf8')
test('enables the current Cache Components config only', () => {
expect(config).toMatch(/cacheComponents\s*:\s*true/) expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(config).not.toMatch(/dynamicIO\s*:/)
expect(config).not.toMatch(/useCache\s*:/)
}) })
test('Does not use the old experimental.ppr flag', () => { test('removes route opt-outs and incompatible segment config', () => {
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8') expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/)
expect(source).not.toMatch(
/export\s+(?:const|var|let)\s+(?:dynamic|revalidate|fetchCache)\s*=/
)
})
// Strip comments to avoid false positives from explanatory comments test('preserves the hourly newsroom feed', async () => {
const stripped = config await expect(environment).toSatisfyCriterion(
.replace(/\/\*[\s\S]*?\*\//g, '') `The newsroom feed must remain cached with an explicit approximately-hourly cache lifetime. A focused data-level cache is valid, and a page-level cache is also valid because the Newsroom page contains only the feed and stable framing with the same lifetime. Reject solutions that remove or materially change the feed's hourly refresh behavior.`
.replace(/\/\/.*$/gm, '') )
})
expect(stripped).not.toMatch(/ppr\s*:\s*true/) test('keeps editor preview request-specific', async () => {
await expect(environment).toSatisfyCriterion(
`The editor preview must still read its cookie at request time outside every public cache. Place the request-specific preview below Suspense or equivalent meaningful loading UI while leaving useful stable preview framing in the static shell. Reject solutions that cache the cookie value, hide the entire preview page behind one fallback, or remove the request-specific behavior.`
)
}) })
Enable partial pre-rendering for this app. Move this publishing app to Cache Components in one branch. Keep the newsroom feed on its hourly refresh policy and keep editor preview request-specific. Finish with a production build without leaving routes opted out.
async function getProducts() {
const res = await fetch('https://api.example.com/products')
return res.json()
}
export async function ProductList() {
const products = await getProducts()
return (
<ul>
{products.map((p: { id: string; name: string; price: number }) => (
<li key={p.id}>
{p.name} - ${p.price}
</li>
))}
</ul>
)
}
async function getRecommendations() {
const res = await fetch('https://api.example.com/recommendations')
return res.json()
}
export async function Recommendations() {
const items = await getRecommendations()
return (
<div>
<h2>Recommended for you</h2>
<ul>
{items.map((item: { id: string; name: string }) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
)
}
import type { Metadata } from 'next' import Link from 'next/link'
import type { ReactNode } from 'react'
export const metadata: Metadata = { export default function RootLayout({ children }: { children: ReactNode }) {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return ( return (
<html lang="en"> <html lang="en">
<body>{children}</body> <body>
<nav>
<Link href="/news">Newsroom</Link>{' '}
<Link href="/preview">Editor preview</Link>
</nav>
{children}
</body>
</html> </html>
) )
} }
export const revalidate = 3600
async function getStories() {
await new Promise((resolve) => setTimeout(resolve, 80))
return ['City council approves new park', 'Night market opens Friday']
}
export default async function NewsPage() {
const stories = await getStories()
return (
<main>
<h1>Newsroom</h1>
{stories.map((story) => (
<article key={story}>{story}</article>
))}
</main>
)
}
import { Suspense } from 'react' export default function HomePage() {
import { ProductList } from './ProductList' return <h1>Northstar Publishing</h1>
import { Recommendations } from './Recommendations'
export default function Page() {
return (
<main>
<h1>Store</h1>
<Suspense fallback={<p>Loading products...</p>}>
<ProductList />
</Suspense>
<Suspense fallback={<p>Loading recommendations...</p>}>
<Recommendations />
</Suspense>
</main>
)
} }
import { cookies } from 'next/headers'
export const dynamic = 'force-dynamic'
export default async function PreviewPage() {
const draft = (await cookies()).get('draft-title')?.value ?? 'Untitled draft'
return (
<main>
<h1>Editor preview</h1>
<p>{draft}</p>
</main>
)
}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
const nextConfig: NextConfig = {} const nextConfig: NextConfig = {
experimental: {
// @ts-expect-error -- legacy config retained for the migration exercise
dynamicIO: true,
},
}
export default nextConfig export default nextConfig
...@@ -23,5 +23,5 @@ ...@@ -23,5 +23,5 @@
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules", "EVAL.ts"]
} }
/**
* Prefetch URL data
*
* Verifies the basic Partial Prefetching inclusion case: the agent caches data
* that depends on searchParams and makes it available in a per-link prefetch.
*/
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set([
'.git',
'.next',
'node_modules',
'dist',
'build',
'coverage',
])
const IGNORE_FILES = new Set(['EVAL.ts', 'PROMPT.md'])
function stripComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
}
function readSourceFiles(dir: string): string[] {
if (!existsSync(dir)) return []
const files: string[] = []
for (const entry of readdirSync(dir)) {
if (IGNORE_DIRS.has(entry)) continue
const fullPath = join(dir, entry)
const stats = statSync(fullPath)
if (stats.isDirectory()) {
files.push(...readSourceFiles(fullPath))
} else if (!IGNORE_FILES.has(entry) && /\.(ts|tsx|js|jsx)$/.test(entry)) {
files.push(stripComments(readFileSync(fullPath, 'utf-8')))
}
}
return files
}
const source = readSourceFiles(process.cwd()).join('\n---FILE---\n')
const config = stripComments(
readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')
)
test('enables Partial Prefetching globally or for the catalog route', () => {
expect(
/partialPrefetching\s*:\s*true/.test(config) ||
/export\s+const\s+prefetch\s*=\s*['"]partial['"]/.test(source)
).toBe(true)
})
test('preserves the category URL structure', () => {
expect(source).toMatch(/\/catalog\?category=/)
expect(source).toMatch(/\bsearchParams\b/)
})
test('opts the category links into per-link prefetching', () => {
expect(source).toMatch(/<Link\b[^>]*\bprefetch(?:\s*=\s*\{true\})?(?:\s|>)/)
})
test('caches the category data', () => {
expect(source).toMatch(/['"]use cache['"]/)
})
test('does not use a navigation-stage boundary', () => {
expect(source).not.toMatch(/\bunstable_navigation\b/)
})
test('prefetches the selected category and cached products', async () => {
await expect(environment).toSatisfyCriterion(
`The implementation must make the selected category heading and its cached products available from the completed per-link prefetch before navigation.
A correct solution preserves the existing /catalog?category=... URLs, enables Partial Prefetching globally or on the catalog route, and opts the category Links into per-link prefetching with prefetch={true} or the equivalent bare prefetch prop. The catalog route reads the category from searchParams beneath Suspense and renders both the matching heading and getProducts(category) result in the prefetched result. The category data must use a use cache scope, with either the default cache profile or an explicit cacheLife(); searchParams must remain outside that cache scope. Keep the Suspense boundary: the shared App Shell uses its fallback, while a completed per-link prefetch can resolve the cached content inside it before navigation.
This is the basic URL-data inclusion case. Do not use unstable_navigation(), unstable_prefetch(), connection(), or an uncached request boundary to defer the category content. Reject solutions that only prefetch the reusable Catalog shell while leaving the selected heading or product list behind the loading fallback.`
)
})
Keep the existing `/catalog?category=...` URLs. Prepare each category link's URL-specific heading and products before the click so selecting it can navigate immediately without showing the loading state. Do not make the click wait for a full server render.
import { Suspense } from 'react'
import { getProducts } from '@/lib/data'
type CatalogSearchParams = Promise<{ category?: string }>
export default function CatalogPage({
searchParams,
}: {
searchParams: CatalogSearchParams
}) {
return (
<main>
<h1>Catalog</h1>
<Suspense fallback={<p>Loading category...</p>}>
<CategoryResults searchParams={searchParams} />
</Suspense>
</main>
)
}
async function CategoryResults({
searchParams,
}: {
searchParams: CatalogSearchParams
}) {
const { category = 'featured' } = await searchParams
const products = await getProducts(category)
return (
<section>
<h2>{category === 'sale' ? 'Products on sale' : 'Featured products'}</h2>
<ul>
{products.map((product) => (
<li key={product}>{product}</li>
))}
</ul>
</section>
)
}
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Product catalog',
description: 'Browse products by category',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
const categories = [
{ slug: 'featured', label: 'Featured products' },
{ slug: 'sale', label: 'Products on sale' },
]
export default function Home() {
return (
<main>
<h1>Shop by category</h1>
<ul>
{categories.map((category) => (
<li key={category.slug}>
<Link href={`/catalog?category=${category.slug}`}>
{category.label}
</Link>
</li>
))}
</ul>
</main>
)
}
const productsByCategory: Record<string, string[]> = {
featured: ['Desk Lamp', 'Wool Blanket'],
sale: ['Canvas Tote', 'Travel Mug'],
}
export async function getProducts(category: string) {
await new Promise((resolve) => setTimeout(resolve, 800))
return productsByCategory[category] ?? []
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@vitejs/plugin-react": "^4.4.1",
"typescript": "^5",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.1.3"
}
}
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
},
"target": "ES2017"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
/**
* Prefetch stage
*
* Verifies that the agent removes cached content from the reusable App Shell
* while keeping it available to a selected per-link prefetch.
*/
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set([
'.git',
'.next',
'node_modules',
'dist',
'build',
'coverage',
])
const IGNORE_FILES = new Set(['EVAL.ts', 'PROMPT.md'])
function stripComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
}
function readSourceFiles(dir: string): string[] {
if (!existsSync(dir)) return []
const files: string[] = []
for (const entry of readdirSync(dir)) {
if (IGNORE_DIRS.has(entry)) continue
const fullPath = join(dir, entry)
const stats = statSync(fullPath)
if (stats.isDirectory()) {
files.push(...readSourceFiles(fullPath))
} else if (!IGNORE_FILES.has(entry) && /\.(ts|tsx|js|jsx)$/.test(entry)) {
files.push(stripComments(readFileSync(fullPath, 'utf-8')))
}
}
return files
}
const source = readSourceFiles(process.cwd()).join('\n---FILE---\n')
const config = stripComments(
readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')
)
test('enables Partial Prefetching globally or for the product route', () => {
expect(
/partialPrefetching\s*:\s*true/.test(config) ||
/export\s+const\s+prefetch\s*=\s*['"]partial['"]/.test(source)
).toBe(true)
})
test('opts the featured product link into per-link prefetching', () => {
expect(source).toMatch(/<Link\b[^>]*\bprefetch(?:\s*=\s*\{true\})?(?:\s|>)/)
})
test('uses the prefetch cache stage', () => {
const prefetchImport = source.match(
/\bunstable_prefetch(?:\s+as\s+([A-Za-z_$][\w$]*))?/
)
expect(prefetchImport).not.toBeNull()
const localName = prefetchImport?.[1] ?? 'unstable_prefetch'
expect(source).toMatch(new RegExp(`await\\s+${localName}\\s*\\(`))
})
test('keeps stable product content in the reusable shell', async () => {
await expect(environment).toSatisfyCriterion(
`The product title and description must remain in the reusable product App Shell. The related-products section must remain outside that shell, beneath its own Suspense boundary. Reject solutions that put the whole product page behind the prefetch stage or move related products into the App Shell. Accept equivalent component and file organization.`
)
})
test('includes related products only in the selected prefetch', async () => {
await expect(environment).toSatisfyCriterion(
`The related-products section must be available before navigation from the featured-product Link without joining the default product App Shell.
Render related products through an async component that awaits unstable_prefetch() before calling the cached getRelatedProducts() function. The unstable_prefetch() call must be outside every use cache scope, while the existing cached data function stays below it.
Reject solutions that replace the stage with connection() or unstable_navigation(), make the related-products data uncached, or defer it until after navigation. Accept equivalent component and file organization.`
)
})
Keep related products out of the default product-page prefetch, but have them ready immediately when navigating from the featured-product link.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Featured product',
description: 'Shop our featured product',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<main>
<h1>Featured product</h1>
<Link href="/product">View Premium Widget</Link>
</main>
)
}
import { getRelatedProducts } from '@/lib/data'
export default async function ProductPage() {
const relatedProducts = await getRelatedProducts()
return (
<main>
<h1>Premium Widget</h1>
<p>A durable widget for everyday projects.</p>
<section>
<h2>Related products</h2>
<ul>
{relatedProducts.map((product) => (
<li key={product}>{product}</li>
))}
</ul>
</section>
</main>
)
}
import { cacheLife } from 'next/cache'
export async function getRelatedProducts() {
'use cache'
cacheLife('hours')
return ['Compact Widget', 'Widget Carry Case']
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@vitejs/plugin-react": "^4.4.1",
"typescript": "^5",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.1.3"
}
}
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
},
"target": "ES2017"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
/**
* Prefetch until navigation
*
* Verifies that the agent uses Partial Prefetching to include a selected
* project's title in a per-link prefetch while deferring the rest of the
* project page until navigation.
*/
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set([
'.git',
'.next',
'node_modules',
'dist',
'build',
'coverage',
])
const IGNORE_FILES = new Set(['EVAL.ts', 'PROMPT.md'])
function stripComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
}
function readSourceFiles(dir: string): string[] {
if (!existsSync(dir)) return []
const files: string[] = []
for (const entry of readdirSync(dir)) {
if (IGNORE_DIRS.has(entry)) continue
const fullPath = join(dir, entry)
const stats = statSync(fullPath)
if (stats.isDirectory()) {
files.push(...readSourceFiles(fullPath))
} else if (!IGNORE_FILES.has(entry) && /\.(ts|tsx|js|jsx)$/.test(entry)) {
files.push(stripComments(readFileSync(fullPath, 'utf-8')))
}
}
return files
}
const source = readSourceFiles(process.cwd()).join('\n---FILE---\n')
const config = stripComments(
readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')
)
test('enables Partial Prefetching globally or for the project route', () => {
expect(
/partialPrefetching\s*:\s*true/.test(config) ||
/export\s+const\s+prefetch\s*=\s*['"]partial['"]/.test(source)
).toBe(true)
})
test('opts the project link into per-link prefetching', () => {
expect(source).toMatch(/<Link\b[^>]*\bprefetch(?:\s*=\s*\{true\})?(?:\s|>)/)
})
test('uses the navigation cache stage', () => {
const navigationImport = source.match(
/\bunstable_navigation(?:\s+as\s+([A-Za-z_$][\w$]*))?/
)
expect(navigationImport).not.toBeNull()
const localName = navigationImport?.[1] ?? 'unstable_navigation'
expect(source).toMatch(new RegExp(`await\\s+${localName}\\s*\\(`))
})
test('includes the project title in the selected prefetch', async () => {
await expect(environment).toSatisfyCriterion(
`The selected project's title must be available before the click from the dashboard's per-link prefetch. Keep the params-dependent title inside Suspense so the reusable App Shell can show a fallback while the selected prefetch resolves the title. The title must render before the nested boundary that waits for navigation.
Accept equivalent component and file organization. Reject solutions that leave the title behind the reusable shell fallback, put it behind unstable_navigation(), disable prefetching, or prefetch the entire page.`
)
})
test('waits until navigation for project details', async () => {
await expect(environment).toSatisfyCriterion(
`Project activity, deployments, description, and other detail content must not join the prefetch. Render those details inside a nested Suspense boundary through an async component that awaits unstable_navigation() before loading or rendering them.
The unstable_navigation() call must remain outside every use cache scope; cached data functions may be called after it. Reject solutions that fetch project details before reaching unstable_navigation(), replace it with connection() or an uncached fetch, or prefetch the entire page. Accept equivalent component and file organization.`
)
})
When navigating from the dashboard to a project, I want the project's title to appear instantly, but I don't want to prefetch the rest of the project page.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Projects',
description: 'Project dashboard',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
const projects = [
{ slug: 'acme', name: 'Acme Storefront' },
{ slug: 'orbit', name: 'Orbit Analytics' },
]
export default function Dashboard() {
return (
<main>
<h1>Projects</h1>
<ul>
{projects.map((project) => (
<li key={project.slug}>
<Link href={`/projects/${project.slug}`}>{project.name}</Link>
</li>
))}
</ul>
</main>
)
}
import { Suspense } from 'react'
import { getProjectDetails, getProjectTitle } from '@/lib/data'
export default function ProjectPage({ params }: PageProps<'/projects/[slug]'>) {
return (
<Suspense fallback={<h1>Loading project...</h1>}>
<Project params={params} />
</Suspense>
)
}
async function Project({
params,
}: Pick<PageProps<'/projects/[slug]'>, 'params'>) {
const { slug } = await params
const [title, details] = await Promise.all([
getProjectTitle(slug),
getProjectDetails(slug),
])
return (
<main>
<h1>{title}</h1>
<p>{details.description}</p>
<h2>Recent activity</h2>
<ul>
{details.activity.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</main>
)
}
const projects: Record<
string,
{ title: string; description: string; activity: string[] }
> = {
acme: {
title: 'Acme Storefront',
description: 'Commerce storefront and checkout.',
activity: ['Production deployment', 'Checkout updated', 'Domain verified'],
},
orbit: {
title: 'Orbit Analytics',
description: 'Product analytics and reporting.',
activity: ['Report published', 'Data source added', 'Team invited'],
},
}
export async function getProjectTitle(slug: string) {
'use cache'
return projects[slug]?.title ?? 'Unknown project'
}
export async function getProjectDetails(slug: string) {
'use cache'
await new Promise((resolve) => setTimeout(resolve, 800))
return (
projects[slug] ?? {
title: 'Unknown project',
description: 'This project could not be found.',
activity: [],
}
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@vitejs/plugin-react": "^4.4.1",
"typescript": "^5",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.1.3"
}
}
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
},
"target": "ES2017"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
/** Cache Components: request isolation and reusable data. */
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set(['.git', '.next', 'node_modules', 'dist', 'build'])
function readSource(dir: string): string[] {
if (!existsSync(dir)) return []
return readdirSync(dir).flatMap((entry) => {
if (IGNORE_DIRS.has(entry)) return []
const path = join(dir, entry)
if (statSync(path).isDirectory()) return readSource(path)
if (entry === 'EVAL.ts' || !/\.(ts|tsx|js|jsx)$/.test(entry)) return []
return readFileSync(path, 'utf8')
})
}
const source = readSource(process.cwd()).join('\n')
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf8')
test('enables Cache Components without opt-outs', () => {
expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/)
})
test('introduces a reusable cache', () => {
expect(source).toMatch(/['"]use cache['"]/)
})
test('keeps a useful dashboard frame in the shell', async () => {
await expect(environment).toSatisfyCriterion(
`The dashboard must keep a useful stable frame, such as the Workspace heading, outside the Suspense boundary used for request-specific member content. The boundary must provide visible, meaningful loading UI rather than a null or empty fallback. Accept equivalent component and file organization.`
)
})
test('keeps member data isolated per request', async () => {
await expect(environment).toSatisfyCriterion(
`Member name, team cookie, and request-region header must be read at request time in the suspended subtree and must not be captured by a public cache. No page or broad request-specific component may be publicly cached. A component that directly calls cookies() or headers() without a use cache directive remains request-specific and needs no additional cache opt-out. Reject any solution that can reuse one member's values for another member. Accept equivalent component and file organization.`
)
})
test('caches only the shared project totals', async () => {
await expect(environment).toSatisfyCriterion(
`Shared project totals must be cached in a focused reusable data function. The cache must not include member name, cookies, headers, or other request-specific values. Accept equivalent component and file organization.`
)
})
Enable Cache Components for this workspace dashboard. Members must continue seeing their own name, team, and request region, while the shared project totals stay reusable. Keep a useful dashboard frame visible while request-specific content loads, and finish with a production build without route opt-outs.
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import { cookies, headers } from 'next/headers'
import { getProjectTotals } from '@/lib/projects'
export default async function DashboardPage() {
const cookieStore = await cookies()
const requestHeaders = await headers()
const member = cookieStore.get('member')?.value ?? 'Guest'
const team = cookieStore.get('team')?.value ?? 'Community'
const region = requestHeaders.get('x-region') ?? 'global'
const totals = await getProjectTotals()
return (
<main>
<h1>Workspace</h1>
<p>Welcome, {member}</p>
<p>Team: {team}</p>
<p>Region: {region}</p>
<p>{totals.active} active projects</p>
</main>
)
}
export async function getProjectTotals() {
await new Promise((resolve) => setTimeout(resolve, 120))
return { active: 12, archived: 4 }
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5",
"vitest": "^3.1.3",
"@vitejs/plugin-react": "^4.4.1",
"vite-tsconfig-paths": "^5.1.4"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
/** Cache Components: URL data and shell boundaries. */
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set(['.git', '.next', 'node_modules', 'dist', 'build'])
function readSource(dir: string): string[] {
if (!existsSync(dir)) return []
return readdirSync(dir).flatMap((entry) => {
if (IGNORE_DIRS.has(entry)) return []
const path = join(dir, entry)
if (statSync(path).isDirectory()) return readSource(path)
if (entry === 'EVAL.ts' || !/\.(ts|tsx|js|jsx)$/.test(entry)) return []
return readFileSync(path, 'utf8')
})
}
const source = readSource(process.cwd()).join('\n')
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf8')
test('enables Cache Components without opt-outs', () => {
expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(source).not.toMatch(/export\s+(?:const|var|let)\s+instant\s*=\s*false/)
})
test('keeps a useful shop frame in the static shell', async () => {
await expect(environment).toSatisfyCriterion(
`The product page must return useful route-independent shop framing before awaiting params or searchParams. The solution must not hide the entire page behind one null, empty, or generic Suspense boundary. Accept equivalent component and file organization.`
)
})
test('resolves URL data below meaningful boundaries', async () => {
await expect(environment).toSatisfyCriterion(
`The product page must forward the params and searchParams promises into one or more children below meaningful Suspense fallbacks, where the product slug and currency are resolved. Reject solutions that await either URL promise before returning the useful shop frame. Accept equivalent component and file organization.`
)
})
test('keys reusable product details by every input', async () => {
await expect(environment).toSatisfyCriterion(
`Product lookup must be cached in a focused reusable data function. Every value that can change its output, including the product slug and currency, must be passed into the cached function so it participates in the cache key. Reject broad page caching or a cache that can return one product or currency for another. Accept equivalent component and file organization.`
)
})
test('streams related products independently', async () => {
await expect(environment).toSatisfyCriterion(
`Related products must remain behind their own meaningful Suspense boundary so they can stream independently after the primary product details. Reject solutions that block the primary details on related products or combine the whole page under one fallback. Accept equivalent component and file organization.`
)
})
Enable Cache Components for this shop. Product URLs and their currency query must keep rendering the correct details, and product details should stay reusable across requests. Keep the shop frame useful while data loads, and let related products stream afterward. Finish with a production build without route opt-outs.
import Link from 'next/link'
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<nav>
<Link href="/">Signal Shop</Link>
</nav>
{children}
</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<main>
<h1>Signal Shop</h1>
<Link href="/products/lamp?currency=EUR">Brass lamp</Link>
</main>
)
}
import { notFound } from 'next/navigation'
import { getProduct, getRelatedProducts } from '@/lib/products'
export default async function ProductPage({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ currency?: string }>
}) {
const { slug } = await params
const { currency = 'USD' } = await searchParams
const product = await getProduct(slug, currency)
if (!product) notFound()
const related = await getRelatedProducts(slug)
return (
<main>
<p>Signal Shop collection</p>
<h1>{product.name}</h1>
<p>{product.price}</p>
<section>
<h2>Related products</h2>
{related.map((item) => (
<p key={item.slug}>{item.name}</p>
))}
</section>
</main>
)
}
const products = {
lamp: { slug: 'lamp', name: 'Brass lamp', usd: 120 },
vase: { slug: 'vase', name: 'Stone vase', usd: 80 },
}
export async function getProduct(slug: string, currency: string) {
await new Promise((resolve) => setTimeout(resolve, 120))
const product = products[slug as keyof typeof products]
if (!product) return null
const rate = currency === 'EUR' ? 0.92 : 1
return { ...product, price: `${currency} ${(product.usd * rate).toFixed(2)}` }
}
export async function getRelatedProducts(slug: string) {
await new Promise((resolve) => setTimeout(resolve, 420))
return Object.values(products).filter((product) => product.slug !== slug)
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5",
"vitest": "^3.1.3",
"@vitejs/plugin-react": "^4.4.1",
"vite-tsconfig-paths": "^5.1.4"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
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