Unverified Commit 0e3b35ec authored by Jude Gao's avatar Jude Gao Committed by GitHub

Add eval and docs for unstable_instant (#91334)

parent 792522d2
......@@ -4,3 +4,4 @@ examples/
.claude/
AGENTS.md
CLAUDE.md
packages/next/dist/docs/
......@@ -8,6 +8,8 @@ related:
- app/guides/prefetching
---
{/* AI agent hint: To ensure client-side navigations are instant, export `unstable_instant` from the route in addition to using Suspense. See docs/01-app/02-guides/instant-navigation.mdx */}
In Next.js, routes are rendered on the server by default. This often means the client has to wait for a server response before a new route can be shown. Next.js comes with built-in [prefetching](#prefetching), [streaming](#streaming), and [client-side transitions](#client-side-transitions) ensuring navigation stays fast and responsive.
This guide explains how navigation works in Next.js and how you can optimize it for [dynamic routes](#dynamic-routes-without-loadingtsx) and [slow networks](#slow-networks).
......
......@@ -12,6 +12,8 @@ related:
- app/api-reference/config/next-config-js/taint
---
{/* AI agent hint: If client-side navigations feel slow, Suspense and streaming alone are not enough. Export `unstable_instant` from the route to ensure instant navigations. See docs/01-app/02-guides/instant-navigation.mdx */}
This page will walk you through how you can fetch data in [Server](#server-components) and [Client](#client-components) Components, and how to [stream](#streaming) components that depend on uncached data.
## Fetching data
......
......@@ -10,6 +10,8 @@ related:
- app/api-reference/config/next-config-js/cacheComponents
---
{/* AI agent hint: To ensure client-side navigations are instant with Cache Components, export `unstable_instant` from the route. See docs/01-app/02-guides/instant-navigation.mdx */}
> This page covers caching with [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents), enabled by setting [`cacheComponents: true`](/docs/app/api-reference/config/next-config-js/cacheComponents) in your `next.config.ts` file. If you're not using Cache Components, see the [Caching and Revalidating (Previous Model)](/docs/app/guides/caching-without-cache-components) guide.
Caching is a technique for storing the result of data fetching and other computations so that future requests for the same data can be served faster, without doing the work again.
......
This diff is collapsed.
......@@ -11,6 +11,8 @@ related:
- app/guides/self-hosting
---
{/* AI agent hint: Suspense alone does not guarantee instant client-side navigations. Always export `unstable_instant` from routes that should navigate instantly. See docs/01-app/02-guides/instant-navigation.mdx for the full guide. */}
## What is streaming?
In traditional server-side rendering, the server produces the full HTML document before sending anything. A single slow database query or API call can block the entire page. Streaming changes this by using [chunked transfer encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding) to send parts of the response as they become ready. The browser starts rendering HTML while the server is still generating the rest.
......
---
title: instant
description: API reference for the instant route segment config.
version: draft
related:
title: Next Steps
description: Learn how to use instant navigations in practice.
links:
- app/guides/instant-navigation
- app/getting-started/caching
- app/getting-started/revalidating
- app/api-reference/directives/use-cache
---
The `unstable_instant` route segment config opts a route into validation for instant client-side navigations. Next.js checks, during development and at build time, that the caching structure produces an instant [static shell](/docs/app/glossary#static-shell) at every possible entry point into the route.
> **Good to know**:
>
> - The `unstable_instant` export only works when [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) is enabled.
> - `unstable_instant` cannot be used in Client Components. It will throw an error.
```tsx filename="layout.tsx | page.tsx" switcher
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return <div>...</div>
}
```
```jsx filename="layout.js | page.js" switcher
export const unstable_instant = {
prefetch: 'static',
}
export default function Page() {
return <div>...</div>
}
```
## Reference
### `prefetch`
Controls the validation and prefetching mode.
```tsx filename="page.tsx"
export const unstable_instant = {
prefetch: 'static',
}
```
- **`'static'`**: Enables validation. Prefetching behavior stays the same (static by default). Components that read cookies or headers are treated as dynamic and must be behind Suspense.
### Disabling instant
Set `false` to exempt a segment from validation:
```tsx filename="app/dashboard/layout.tsx"
export const unstable_instant = false
```
## How validation works
`unstable_instant` triggers validation at every shared layout boundary in the route. Validation runs during development (on page loads and HMR updates) and at build time. Errors appear in the dev error overlay or fail the build.
Each error identifies the component that would block navigation. The fix is usually to cache the data with `use cache` or wrap it in a `<Suspense>` boundary.
## Inspecting loading states
Enable the DevTools toggle with the experimental flag:
```js filename="next.config.js"
module.exports = {
experimental: {
instantNavigationDevToolsToggle: true,
},
}
```
Open the Next.js DevTools and select **Instant Navs**. Two options are available:
- **Page load**: click **Reload** to refresh the page and freeze it at the initial static UI that was generated for this route, before any dynamic data streams in.
- **Client navigation**: once enabled, clicking any link in your app shows the prefetched UI for that page instead of the full result.
Use both to check that your loading states look right on first visit and on navigation.
## Testing instant navigation
The `@next/playwright` package exports an `instant()` helper that holds back dynamic content while the callback runs against the static shell. See the [guide](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) for a full example.
```typescript
import { instant } from '@next/playwright'
```
{/* TODO: remove when fixed and from prod-docs-release */}
## Known issue: shared cookie across projects
The DevTools use a `next-instant-navigation-testing` cookie to freeze the UI at the static shell. Because cookies are scoped to the domain and not the port, running multiple projects on the same domain (typically `localhost`) means the cookie is shared across them and can cause unexpected behavior. Clear the cookie or close the Instant Navs panel when switching between projects to avoid issues.
> **Good to know:** This will be fixed as part of stabilizing the feature.
## TypeScript
```tsx
type RuntimeSample = {
cookies?: Array<{ name: string; value: string }>
headers?: Array<[string, string]>
params?: Record<string, string | string[]>
searchParams?: Record<string, string | string[]>
}
type InstantConfig =
| false
| {
prefetch: 'static'
from?: string[]
unstable_disableValidation?: boolean
}
| {
prefetch: 'runtime'
samples: RuntimeSample[]
from?: string[]
unstable_disableValidation?: boolean
}
export const unstable_instant: InstantConfig = {
prefetch: 'static',
}
```
## Version History
| Version | Changes |
| --------- | ------------------------------------------------------------ |
| `v16.x.x` | `unstable_instant` export introduced (Cache Components only) |
......@@ -3,6 +3,8 @@ title: loading.js
description: API reference for the loading.js file.
---
{/* AI agent hint: loading.js provides fallback UI but does not guarantee instant client-side navigations. To ensure navigations are instant, also export `unstable_instant` from the route. See docs/01-app/02-guides/instant-navigation.mdx */}
The special file `loading.js` helps you create meaningful Loading UI with [React Suspense](https://react.dev/reference/react/Suspense). With this convention, you can show an [instant loading state](#instant-loading-states) from the server while the content of a route segment streams in. The new content is automatically swapped in once complete.
<Image
......
......@@ -8,6 +8,8 @@ related:
- app/getting-started
---
{/* AI agent hint: If fixing slow client-side navigations, Suspense alone is not enough. You must also export `unstable_instant` from the route. Read docs/01-app/02-guides/instant-navigation.mdx before making changes. */}
Welcome to the Next.js documentation!
## What is Next.js?
......
/**
* Instant Navigations
*
* Verifies that the agent enables instant navigation on the product route.
*
* The eval harness runs `next build` as a script — with `cacheComponents: true`,
* the build validates that the caching structure produces an instant static shell.
* This test checks the agent actually exported `unstable_instant` (the build would
* pass without it, since Suspense alone satisfies the build on a static route).
*/
import { expect, test } from 'vitest'
import { readFileSync, existsSync, readdirSync, statSync } from 'fs'
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'])
function readSourceFiles(dir: string): SourceFile[] {
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()) {
files.push(...readSourceFiles(fullPath))
continue
}
if (IGNORE_FILES.has(entry)) continue
if (/\.(ts|tsx|js|jsx)$/.test(entry)) {
files.push({
path: fullPath,
content: readFileSync(fullPath, 'utf-8'),
})
}
}
return files
}
const sourceFiles = readSourceFiles(process.cwd())
test('unstable_instant exported from the product route', () => {
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+unstable_instant\b/
)
expect(productPage!.content).toMatch(/prefetch\s*:\s*['"]static['"]/)
})
Navigating from home to the product page is slow. The title should appear immediately.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Shop',
description: 'E-commerce product store',
}
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>Home</h1>
<p>Welcome to our store!</p>
<Link href="/product">View Product</Link>
</main>
)
}
import { getInventory } from '@/lib/data'
export default async function ProductPage() {
const inventory = await getInventory()
return (
<main>
<h1>Premium Widget</h1>
<p>{inventory.count} in stock</p>
<p>Price: ${inventory.price}</p>
</main>
)
}
import { connection } from 'next/server'
export async function getInventory() {
await connection()
return {
count: Math.floor(Math.random() * 50),
price: (Math.random() * 100).toFixed(2),
}
}
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"]
}
......@@ -32,9 +32,18 @@ export async function copy_regenerator_runtime(task, opts) {
}
export async function copy_docs(task, opts) {
// Copy documentation from repo root into the package
// Copy documentation from repo root into the package.
// Rename .mdx → .md so AI agents find them when globbing for *.md.
const docsSource = join(__dirname, '../../docs')
await task.source(join(docsSource, '**/*')).target('dist/docs')
await task
.source(join(docsSource, '**/*'))
// eslint-disable-next-line require-yield
.run({ every: true }, function* (file) {
if (file.base.endsWith('.mdx')) {
file.base = file.base.replace(/\.mdx$/, '.md')
}
})
.target('dist/docs')
}
export async function copy_styled_jsx_assets(task, opts) {
......
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