Unverified Commit 2521b8ad authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] Instant validation in Dev (#89077)

This PR implements the initial version of dev-time validation for
`export const instant = ...`

```tsx
export const instant = { prefetch: 'static' }
```
```tsx
export const instant = { prefetch: 'runtime', ... }
```
```tsx
export const instant = false
```
(the config is currently expected to be named `unstable_instant`, but
i'll be shortening it to `instant` below.)

When a segment specifies an instant config with `prefetch: 'static'` or
`prefetch: 'runtime'`, we'll validate that all (prefetched) navigations
into that segment will render instant UI, i.e. that the navigation won't
block. On the other hand, if a segment is allowed to block, it must be
marked with `export const instant = false`.

Note that our existing static shell validation is a special case of
this, but for now, we're keeping both. A future PR will reimplement
static shell validation as a special case of instant validation.

Like static shell validation, these validations currently run in dev
whenever we render the full page (i.e. no segments are omitted). This
means it'll happen on an initial load (or refresh) and HMR.

### Implementation notes

#### Validation approach

The goal is to simulate what the browser would display for a prefetched
client navigation. We do this by re-assembling the segments extracted
from the original stream for the page.
- The outer (shared) segments should already fully resolved (i.e. in the
Dynamic stage), to represent the fact that the browser loaded them
before
- The new segments are either in Static or Runtime stage, depending on
how each segment would have been prefetched.

Similar to static shell validation, we then perform a Fizz prerender on
the combined payload, abort it, and track the locations of `onError`
calls. The difference here is that unlike static shell validation, we
require a Suspense boundary *inside* the new subtree. This is detected
by adding a `InstantValidationBoundary` around the new subtree when we
construct the payload, and checking if there's a suspense below that in
the component stack.

Currently, for each `instant` config we find, we take each of its parent
layouts as a possible navigation parent (unless it's marked as
blocking). So if we have a page with parent layouts like this:
```
/layout.tsx
/foo/layout.tsx
/foo/bar/layout.tsx
/foo/bar/page.tsx <- `export const instant = { prefetch: 'static' }`
```
Then we'll check for navigations where each of `/layout.tsx`,
`/foo/layout.tsx` and `/foo/bar/layout.tsx` is a fully resolved shared
parent.

If a validation fails, we do a "discriminated error message" flow
analogous to static shell validation. Static segments are replaced with
Runtime segments to see if the error goes away, which lets us determine
if the hole is caused by runtime or dynamic data.

#### Building the combined payload

First, we need to separate the full stream into segments. The process is
similar to `collectSegmentData` -- we need to deserialize the payload
from the stream and then re-serialize each segment separately. The
complexity here comes from the fact that the full stream is separated
into stages, and we need each segment to be in staged form as well. This
lets us pick and choose which stage the segment is in to simulate what
we'd show for a static or runtime prefetch.

The other complex part is the "late release trick" (as implemented in
`createNodeStreamWithLateRelease`). This was already done for static
shell validation, but it's more complex here.

Debug info for dynamic holes is usually delayed until a further stage.
So, in the static stage we only see an unresolved promise (or lazy
reference), and then in the runtime stage we get the debugInfo telling
us that it was caused by `await cookies()`. To ensure that this debug
info is available for purposes on error reporting, we do a "late
release" -- before we abort, we advance the each segment to the dynamic
stage, which won't cause any new content to render, but will provide
Fizz with debug info and thus give us precise error locations in
`onError`. If you see `releaseSignal`, that's what it's for.

#### `instant` on layouts

We support specifying `instant` on layouts. The validation principle is
the same, but note that in the current mode (validating a single page in
dev) we can't enforce that *all* navigations into that layout satisfy
the constraint, we can only check if that's satisfied for the current
page.

#### Blocking segments

A segment can be marked as blocking with
```tsx
export const instant = false
```
This is meant to signal that this segment deliberately does not have
instant UI.

Currently, this is affects validation as follows:

If there's no `instant` config in parent segments, skip validating all
navigations where this layout would be new (because we know it'd block),
i.e. only validate navigations where it's a shared parent. Children of
this segment can still have `instant` configs of their own, and those
will be validated. This allows structures where a layout is blocking,
but once it's loaded, navigations within it should have instant UI.

If there is an `instant` config in a parent segment, the validation of
that parent is *not* skipped. The reasoning here is that if a layout
asserts that navigations into it should have static UI, then a child
with `instant = false` should not violate that. This essentially
requires that the child have a `loading.js` or that the layout has to
wrap the slot with Suspense.

Note that `instant = false` can also be used to opt segements out of
static shell validation without requiring a Suspense above body.

### Limitations and planned follow-ups

- `instant` configs in parallel routes (i.e. `@slot`) are not currently
validated.
- `expectUnableToVerify` is not implemented yet, i.e. there's no way to
say "this cannot be validated using SSR". The shared segments are not
expected to suspend. For now, `export const instant = { prefetch: ...,
unstable_disableValidation: true }` can be used to bypass a segment if
validating it causes problems.
- static shell validation is a special case of instant validation, but
is not currently implemented as such.
- we should be able to validate during client navigations, not just
full-page loads and HMR, but we currently can't because we don't have
all the segments when we do that, so we can't assemble a proper combined
payload.
parent 469e513c
......@@ -29,3 +29,11 @@ export const unstable_instant = {
],
}
```
#### Indicating that there is no instant UI
This does not disable prefetching.
```tsx filename="app/[slug]/page.tsx"
export const unstable_instant = false
```
......@@ -988,5 +988,12 @@
"987": "Invalid \\`deploymentId\\` configuration: must be a string. See https://nextjs.org/docs/messages/deploymentid-not-a-string",
"988": "Invalid \\`deploymentId\\` configuration: contains invalid characters. Only alphanumeric characters, hyphens, and underscores are allowed. See https://nextjs.org/docs/messages/deploymentid-invalid-characters",
"989": "Loaded static props were from an outdated deployment, forcing a hard reload",
"990": "Page \"%s\" cannot use \\`export const unstable_instant = ...\\` without enabling \\`cacheComponents\\`."
"990": "Page \"%s\" cannot use \\`export const unstable_instant = ...\\` without enabling \\`cacheComponents\\`.",
"991": "A page must have a root layout",
"992": "Got unexpected empty seed data during instant validation",
"993": "createNodeStreamWithLateRelease cannot be used in the edge runtime",
"994": "InitialRSCPayload does not match the expected shape during instant validation.",
"995": "Missing segment data: %s",
"996": "Unexpected state while traversing route tree: %s",
"997": "%s: \\`unstable_instant\\` with mode 'runtime' is not supported in root layouts."
}
......@@ -25,7 +25,7 @@ const InstantConfigStaticSchema = z
.object({
prefetch: z.literal('static'),
from: z.array(z.string()).optional(),
expectUnableToVerify: z.boolean().optional(),
unstable_disableValidation: z.boolean().optional(),
})
.strict()
......@@ -34,16 +34,19 @@ const InstantConfigRuntimeSchema = z
prefetch: z.literal('runtime'),
samples: z.array(RuntimeSampleSchema).min(1),
from: z.array(z.string()).optional(),
expectUnableToVerify: z.boolean().optional(),
unstable_disableValidation: z.boolean().optional(),
})
.strict()
const InstantConfigSchema = z.discriminatedUnion('prefetch', [
InstantConfigStaticSchema,
InstantConfigRuntimeSchema,
const InstantConfigSchema = z.union([
z.discriminatedUnion('prefetch', [
InstantConfigStaticSchema,
InstantConfigRuntimeSchema,
]),
z.literal(false),
])
export type InstantConfig = InstantConfigStatic | InstantConfigRuntime
export type InstantConfig = InstantConfigStatic | InstantConfigRuntime | false
export type InstantConfigForTypeCheckInternal =
| __GenericInstantConfig
| InstantConfig
......@@ -57,20 +60,20 @@ interface __GenericInstantConfig {
prefetch: string
samples?: Array<WideRuntimeSample>
from?: string[]
expectUnableToVerify?: boolean
unstable_disableValidation?: boolean
}
interface InstantConfigStatic {
prefetch: 'static'
from?: string[]
expectUnableToVerify?: boolean
unstable_disableValidation?: boolean
}
interface InstantConfigRuntime {
prefetch: 'runtime'
samples: Array<RuntimeSample>
from?: string[]
expectUnableToVerify?: boolean
unstable_disableValidation?: boolean
}
type WideRuntimeSample = {
......@@ -175,7 +178,7 @@ export function parseAppSegmentConfig(
case 'unstable_instant': {
return {
// @TODO replace this link with a link to the docs when they are written
message: `Invalid unstable_instant value ${JSON.stringify(ctx.data)} on "${route}", must be an object with \`prefetch: "static"\` or \`prefetch: "runtime"\`. Read more at https://nextjs.org/docs/messages/invalid-instant-configuration`,
message: `Invalid unstable_instant value ${JSON.stringify(ctx.data)} on "${route}", must be an object with \`prefetch: "static"\` or \`prefetch: "runtime"\`, or \`false\`. Read more at https://nextjs.org/docs/messages/invalid-instant-configuration`,
}
}
default:
......
......@@ -229,7 +229,10 @@ async function createComponentTreeInternal(
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
/** Whether this segment should use a runtime prefetch instead of a static prefetch. */
const hasRuntimePrefetch = instantConfig?.prefetch === 'runtime'
const hasRuntimePrefetch =
instantConfig && typeof instantConfig === 'object'
? instantConfig.prefetch === 'runtime'
: false
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
......
export type DebugChannelPair = {
serverSide: DebugChannelServer
clientSide: DebugChannelClient
}
export type DebugChannelServer = {
readable?: ReadableStream<Uint8Array>
writable: WritableStream<Uint8Array>
}
export type DebugChannelClient = {
readable: ReadableStream<Uint8Array>
writable?: WritableStream<Uint8Array>
}
export function createDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
}
let readableController: ReadableStreamDefaultController | undefined
let clientSideReadable = new ReadableStream<Uint8Array>({
start(controller) {
readableController = controller
},
})
return {
serverSide: {
writable: new WritableStream<Uint8Array>({
write(chunk) {
readableController?.enqueue(chunk)
},
close() {
readableController?.close()
},
abort(err) {
readableController?.error(err)
},
}),
},
clientSide: { readable: clientSideReadable },
}
}
......@@ -49,6 +49,7 @@ import {
import { scheduleOnNextTick } from '../../lib/scheduler'
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { InvariantError } from '../../shared/lib/invariant-error'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'
const hasPostpone = typeof React.unstable_postpone === 'function'
......@@ -709,6 +710,10 @@ const hasViewportRegex = new RegExp(
)
const hasOutletRegex = new RegExp(`\\n\\s+at ${OUTLET_BOUNDARY_NAME}[\\n\\s]`)
const hasPrefetchValidationBoundaryRegex = new RegExp(
`\\n\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\n\\s]`
)
export function trackAllowedDynamicAccess(
workStore: WorkStore,
componentStack: string,
......@@ -758,6 +763,93 @@ export function trackAllowedDynamicAccess(
}
}
export enum DynamicHoleKind {
/** We know that this hole is caused by runtime data. */
Runtime = 1,
/** We know that this hole is caused by dynamic data. */
Dynamic = 2,
}
export function trackDynamicHoleInNavigation(
workStore: WorkStore,
componentStack: string,
dynamicValidation: DynamicValidationState,
clientDynamic: DynamicTrackingState,
kind: DynamicHoleKind
) {
if (hasOutletRegex.test(componentStack)) {
// We don't need to track that this is dynamic. It is only so when something else is also dynamic.
return
}
if (hasMetadataRegex.test(componentStack)) {
const usageDescription =
kind === DynamicHoleKind.Runtime
? `Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed inside \`generateMetadata\` or you have file-based metadata such as icons that depend on dynamic params segments.`
: `Uncached data or \`connection()\` was accessed inside \`generateMetadata\`.`
const message = `Route "${workStore.route}": ${usageDescription} Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`
const error = createErrorWithComponentOrOwnerStack(message, componentStack)
dynamicValidation.dynamicMetadata = error
return
}
if (hasViewportRegex.test(componentStack)) {
const usageDescription =
kind === DynamicHoleKind.Runtime
? `Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed inside \`generateViewport\`.`
: `Uncached data or \`connection()\` was accessed inside \`generateViewport\`.`
const message = `Route "${workStore.route}": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`
const error = createErrorWithComponentOrOwnerStack(message, componentStack)
dynamicValidation.dynamicErrors.push(error)
return
}
// Check if we have a Suspense above the hole, but below the validation boundary.
// If we do, then this dynamic usage wouldn't block a navigation to this subtree.
// Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.
//
// Note that in the component stack, children come before parents.
//
// Valid:
// ...
// at Suspense
// ...
// at __next_prefetch_validation_boundary__
//
// Invalid:
// ...
// at __next_prefetch_validation_boundary__
// ...
// at Suspense
//
const suspenseLocation = hasSuspenseRegex.exec(componentStack)
if (suspenseLocation) {
const boundaryLocation =
hasPrefetchValidationBoundaryRegex.exec(componentStack)
if (boundaryLocation) {
if (suspenseLocation.index < boundaryLocation.index) {
dynamicValidation.hasAllowedDynamic = true
return
}
}
}
if (clientDynamic.syncDynamicErrorWithStack) {
// This task was the task that called the sync error.
dynamicValidation.dynamicErrors.push(
clientDynamic.syncDynamicErrorWithStack
)
return
}
const usageDescription =
kind === DynamicHoleKind.Runtime
? `Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed outside of \`<Suspense>\`.`
: `Uncached data or \`connection()\` was accessed outside of \`<Suspense>\`.`
const message = `Route "${workStore.route}": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`
const error = createErrorWithComponentOrOwnerStack(message, componentStack)
dynamicValidation.dynamicErrors.push(error)
return
}
export function trackDynamicHoleInRuntimeShell(
workStore: WorkStore,
componentStack: string,
......@@ -799,12 +891,12 @@ export function trackDynamicHoleInRuntimeShell(
clientDynamic.syncDynamicErrorWithStack
)
return
} else {
const message = `Route "${workStore.route}": Uncached data or \`connection()\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`
const error = createErrorWithComponentOrOwnerStack(message, componentStack)
dynamicValidation.dynamicErrors.push(error)
return
}
const message = `Route "${workStore.route}": Uncached data or \`connection()\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`
const error = createErrorWithComponentOrOwnerStack(message, componentStack)
dynamicValidation.dynamicErrors.push(error)
return
}
export function trackDynamicHoleInStaticShell(
......@@ -971,9 +1063,10 @@ export function throwIfDisallowedDynamic(
export function getStaticShellDisallowedDynamicReasons(
workStore: WorkStore,
prelude: PreludeState,
dynamicValidation: DynamicValidationState
dynamicValidation: DynamicValidationState,
configAllowsBlocking: boolean
): Array<Error> {
if (dynamicValidation.hasSuspenseAboveBody) {
if (configAllowsBlocking || dynamicValidation.hasSuspenseAboveBody) {
// This route has opted into allowing fully dynamic rendering
// by including a Suspense boundary above the body. In this case
// a lack of a shell is not considered disallowed so we simply return
......@@ -1013,6 +1106,50 @@ export function getStaticShellDisallowedDynamicReasons(
return []
}
export function getNavigationDisallowedDynamicReasons(
workStore: WorkStore,
prelude: PreludeState,
dynamicValidation: DynamicValidationState
): Array<Error> {
// NOTE: We don't care about Suspense above body here
// TODO: Need to make sure the logic here actually makes sense
if (prelude !== PreludeState.Full) {
// We didn't have any sync bailouts but there may be user code which
// blocked the root. We would have captured these during the prerender
// and can log them here and then terminate the build/validating render
const dynamicErrors = dynamicValidation.dynamicErrors
if (dynamicErrors.length > 0) {
return dynamicErrors
}
if (prelude === PreludeState.Empty) {
// If we ever get this far then we messed up the tracking of invalid dynamic.
// We still adhere to the constraint that you must produce a shell but invite the
// user to report this as a bug in Next.js.
return [
new InvariantError(
`Route "${workStore.route}" did not produce a static shell and Next.js was unable to determine a reason.`
),
]
}
} else {
const dynamicErrors = dynamicValidation.dynamicErrors
if (dynamicErrors.length > 0) {
return dynamicErrors
}
if (
dynamicValidation.hasAllowedDynamic === false &&
dynamicValidation.dynamicMetadata
) {
return [dynamicValidation.dynamicMetadata]
}
}
// We had a non-empty prelude and there are no dynamic holes
return []
}
export function delayUntilRuntimeStage<T>(
prerenderStore: PrerenderStoreModernRuntime,
result: Promise<T>
......
......@@ -42,6 +42,11 @@ export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint'
export { collectSegmentData } from './collect-segment-data'
export const InstantValidation =
process.env.NODE_ENV === 'development' && process.env.NEXT_RUNTIME !== 'edge'
? (require('./instant-validation/instant-validation') as typeof import('./instant-validation/instant-validation'))
: undefined
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { patchFetch as _patchFetch } from '../lib/patch-fetch'
......
export const INSTANT_VALIDATION_BOUNDARY_NAME =
'__next_instant_validation_boundary__'
'use client'
import type { ReactNode } from 'react'
import { INSTANT_VALIDATION_BOUNDARY_NAME } from './boundary-constants'
// We use a namespace object to allow us to recover the name of the function
// at runtime even when production bundling/minification is used.
const NameSpace = {
[INSTANT_VALIDATION_BOUNDARY_NAME]: function ({
children,
}: {
children: ReactNode
}) {
return children
},
}
export const InstantValidationBoundary =
// We use slice(0) to trick the bundler into not inlining/minifying the function
// so it retains the name inferred from the namespace object
NameSpace[
INSTANT_VALIDATION_BOUNDARY_NAME.slice(
0
) as typeof INSTANT_VALIDATION_BOUNDARY_NAME
]
import { getLayoutOrPageModule } from '../../lib/app-dir-module'
import type { LoaderTree } from '../../lib/app-dir-module'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
export async function anySegmentHasRuntimePrefetchEnabled(
tree: LoaderTree
): Promise<boolean> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
const hasRuntimePrefetch =
instantConfig && typeof instantConfig === 'object'
? instantConfig.prefetch === 'runtime'
: false
if (hasRuntimePrefetch) {
return true
}
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const hasChildRuntimePrefetch =
await anySegmentHasRuntimePrefetchEnabled(parallelRoute)
if (hasChildRuntimePrefetch) {
return true
}
}
return false
}
export async function isPageAllowedToBlock(tree: LoaderTree): Promise<boolean> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
// If we encounter a non-false instant config before a instant=false,
// the page isn't allowed to block. The config expresses a requirement for
// instant UI, so we should make sure that a static shell exists.
// (even if it'd use runtime prefetching for client navs)
if (instantConfig !== undefined) {
if (typeof instantConfig === 'object') {
return false
} else if (instantConfig === false) {
return true
}
}
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const subtreeIsBlocking = await isPageAllowedToBlock(parallelRoute)
if (subtreeIsBlocking) {
return true
}
}
return false
}
type FoundSegmentWithConfig = {
path: string[]
config: NonNullable<AppSegmentConfig['unstable_instant']>
}
export async function anySegmentNeedsInstantValidation(
rootTree: LoaderTree
): Promise<boolean> {
const segments = await findSegmentsWithInstantConfig(rootTree)
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
// (If there's only `false`, there's no need to run validation).
// If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
let needsValidation = false
for (const { config } of segments) {
if (typeof config === 'object') {
if (config.unstable_disableValidation) {
return false
}
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
}
}
return needsValidation
}
export async function findSegmentsWithInstantConfig(
rootTree: LoaderTree
): Promise<FoundSegmentWithConfig[]> {
const results: FoundSegmentWithConfig[] = []
async function visit(tree: LoaderTree, path: string[]): Promise<void> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
if (instantConfig !== undefined) {
results.push({
path,
config: instantConfig,
})
}
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const childTree = parallelRoutes[parallelRouteKey]
await visit(childTree, [...path, parallelRouteKey])
}
}
await visit(rootTree, [])
return results
}
import type { Readable } from 'node:stream'
import { InvariantError } from '../../../shared/lib/invariant-error'
/**
* When we abort a staged render, we can still provide react with more chunks from later phases
* to use for their debug info. This will not cause more contents to be rendered.
*/
export function createNodeStreamWithLateRelease(
partialChunks: Array<Uint8Array>,
allChunks: Array<Uint8Array>,
releaseSignal: AbortSignal
): Readable {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'createNodeStreamWithLateRelease cannot be used in the edge runtime'
)
} else {
const { Readable } = require('node:stream') as typeof import('node:stream')
let nextIndex = 0
const readable = new Readable({
read() {
while (nextIndex < partialChunks.length) {
this.push(partialChunks[nextIndex])
nextIndex++
}
},
})
releaseSignal.addEventListener(
'abort',
() => {
// Flush any remaining chunks from the original set
while (nextIndex < partialChunks.length) {
readable.push(partialChunks[nextIndex])
nextIndex++
}
// Flush all chunks since we're now aborted and can't schedule
// any new work but these chunks might unblock debugInfo
while (nextIndex < allChunks.length) {
readable.push(allChunks[nextIndex])
nextIndex++
}
setImmediate(() => {
readable.push(null)
})
},
{ once: true }
)
return readable
}
}
export function createNodeStreamFromChunks(
chunks: Array<Uint8Array>,
signal?: AbortSignal
): Readable {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'createNodeStreamFromChunks cannot be used in the edge runtime'
)
} else {
const { Readable } = require('node:stream') as typeof import('node:stream')
// If there's a signal, delay closing until it fires
if (signal) {
signal.addEventListener(
'abort',
() => {
readable.push(null)
},
{ once: true }
)
}
let nextIndex = 0
const readable = new Readable({
read() {
while (nextIndex < chunks.length) {
this.push(chunks[nextIndex])
nextIndex++
}
if (!signal) {
this.push(null)
}
},
})
return readable
}
}
......@@ -4,6 +4,7 @@ import { isReactLargeShellError } from './react-large-shell-error'
export enum Phase {
ProspectiveRender = 'the prospective render',
SegmentCollection = 'segment collection',
InstantValidation = 'instant validation',
}
export function printDebugThrownValueForProspectiveRender(
......
import { getLayoutOrPageModule } from '../lib/app-dir-module'
import type { LoaderTree } from '../lib/app-dir-module'
import { parseLoaderTree } from '../../shared/lib/router/utils/parse-loader-tree'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
export async function anySegmentHasRuntimePrefetchEnabled(
tree: LoaderTree
): Promise<boolean> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
/** Whether this segment should use a runtime prefetch instead of a static prefetch. */
const hasRuntimePrefetch = instantConfig?.prefetch === 'runtime'
if (hasRuntimePrefetch) {
return true
}
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const hasChildRuntimePrefetch =
await anySegmentHasRuntimePrefetchEnabled(parallelRoute)
if (hasChildRuntimePrefetch) {
return true
}
}
return false
}
......@@ -149,7 +149,7 @@ const API_DOCS: Record<
unstable_instant: {
description: `Specifies the default prefetching behavior for this segment. This configuration is currently under development and will change.`,
link: '(docs coming soon)',
type: 'object',
type: 'object | false',
// TODO: ideally, we'd validate the config object somehow, but this is difficult to do
// with the way this plugin is currently structured.
// For now, since we don't provide an `options` here, we won't do any validation in
......
......@@ -169,6 +169,7 @@ declare module 'react-server-dom-webpack/server.edge' {
onError?: (error: unknown) => void
signal?: AbortSignal
debugChannel?: { readable?: ReadableStream; writable?: WritableStream }
startTime?: number
}
): ReadableStream<Uint8Array>
......
export const unstable_instant = { prefetch: 'static' }
export default async function Layout({ children }) {
return (
<div>
<p>
This is a layout with{' '}
<code>{`unstable_instant = { prefetch: 'static' }`}</code>.
</p>
<hr />
{children}
</div>
)
}
import { connection } from 'next/server'
export const unstable_instant = false
export default async function Page() {
await connection()
return (
<main>
<p>
This is a blocking page. It is configured with{' '}
<code>unstable_instant = false</code>, but it's located under a layout
with <code>{`unstable_instant = { prefetch: 'static' }`}</code>.
Ideally, we'd honor the static assertion and require that a static shell
is produced.
</p>
</main>
)
}
export default async function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
productionBrowserSourceMaps: true,
experimental: {
prerenderEarlyExit: false,
reactDebugChannel: process.env.REACT_DEBUG_CHANNEL ? true : false,
},
typescript: {
ignoreBuildErrors: true,
},
}
export default nextConfig
import { connection } from 'next/server'
export const unstable_instant = false
export default async function Layout({ children }) {
await connection()
return (
<html>
<body>
<p>
This is a blocking layout. It is configured with{' '}
<code>unstable_instant = false</code>, so it should not be required to
produce a static shell.
</p>
<hr />
{children}
</body>
</html>
)
}
export default async function Page() {
return (
<main>
<p>This is a static page below a blocking layout.</p>
</main>
)
}
import { connection } from 'next/server'
export const unstable_instant = false
export default async function Page() {
await connection()
return (
<main>
<p>
This is a blocking page. It is configured with{' '}
<code>unstable_instant = false</code>, so it should not be required to
produce a static shell.
</p>
</main>
)
}
export default async function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { connection } from 'next/server'
export const unstable_instant = false
export default async function RootLayout({ children }) {
await connection()
return (
<html>
<body>
<p>
This is a blocking root layout. It is configured with{' '}
<code>unstable_instant = false</code>, so it should not be required to
produce a static shell.
</p>
<hr />
{children}
</body>
</html>
)
}
export default async function Page() {
return (
<main>
<p>This is a static page below a blocking root layout.</p>
</main>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
productionBrowserSourceMaps: true,
experimental: {
prerenderEarlyExit: false,
reactDebugChannel: process.env.REACT_DEBUG_CHANNEL ? true : false,
},
typescript: {
ignoreBuildErrors: true,
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { waitForNoErrorToast } from 'next-test-utils'
import { join } from 'node:path'
describe('instant validation - opting out of static shells', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: join(__dirname, 'fixtures', 'valid'),
skipDeployment: true,
})
if (skipped) return
// NOTE: if something's wrong in build, we'll fail before any tests run.
// Visiting the pages is mostly just a sanity check.
it('does not require a static shell if a root layouts is configured as blocking', async () => {
const browser = await next.browser('/blocking-root-layout')
await browser.elementByCss('main')
if (isNextDev) await waitForNoErrorToast(browser)
})
it('does not require a static shell if a layout is configured as blocking', async () => {
const browser = await next.browser('/blocking-layout')
await browser.elementByCss('main')
if (isNextDev) await waitForNoErrorToast(browser)
})
it('does not require a static shell if a page is configured as blocking', async () => {
const browser = await next.browser('/blocking-page')
await browser.elementByCss('main')
if (isNextDev) await waitForNoErrorToast(browser)
})
})
describe.each([
{ debugChannelEnabled: true, description: 'with debug channel' },
{ debugChannelEnabled: false, description: 'without debug channel' },
])('instant validation - $description', ({ debugChannelEnabled }) => {
describe('requires a static shell if a below a static layout page is configured as blocking', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: join(__dirname, 'fixtures', 'invalid-blocking-page-below-static'),
skipStart: true,
skipDeployment: true,
env: {
REACT_DEBUG_CHANNEL: debugChannelEnabled ? '1' : '',
},
})
if (skipped) return
if (isNextDev) {
beforeAll(() => next.start())
it('errors in dev', async () => {
const browser = await next.browser('/blocking-page-below-static')
await browser.elementByCss('main')
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Data that blocks navigation was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. Uncached data such as fetch(...), cached data with a low expire time, or connection() are all examples of data that only resolve on navigation.
To fix this, you can either:
Provide a fallback UI using <Suspense> around this component. This allows Next.js to stream its contents to the user as soon as it's ready, without blocking the rest of the app.
or
Move the asynchronous await into a Cache Component ("use cache"). This allows Next.js to statically prerender the component as part of the HTML document, so it's instantly visible to the user.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/blocking-page-below-static/page.tsx (6:19) @ Page
> 6 | await connection()
| ^",
"stack": [
"Page app/blocking-page-below-static/page.tsx (6:19)",
],
}
`)
})
} else {
let didBuildError = false
beforeAll(async () => {
try {
await next.start()
} catch (err) {
didBuildError = true
}
})
it('errors during build', () => {
expect(didBuildError).toBe(true)
expect(next.cliOutput).toContain(
'Uncached data was accessed outside of <Suspense>'
)
})
}
})
})
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>
<a href="/">Home</a>
</header>
)
}
import { DebugLinkMPA } from '../../components/debug-link'
import { cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
cacheLife('minutes')
return (
<main>
<h2>Runtime</h2>
<ul>
<li>
<DebugLinkMPA href="/runtime/suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/runtime/no-suspense-around-params/123" />
</li>
<li>
<DebugLinkMPA href="/runtime/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/runtime/missing-suspense-around-dynamic-layout" />
</li>
<li>
<DebugLinkMPA href="/runtime/suspense-too-high" />
</li>
<li>
<DebugLinkMPA href="/runtime/invalid-blocking-inside-runtime" />
</li>
<li>
<DebugLinkMPA href="/runtime/invalid-sync-io" />
</li>
<li>
<DebugLinkMPA href="/runtime/valid-blocking-inside-runtime" />
</li>
</ul>
<h2>Static</h2>
<ul>
<li>
<DebugLinkMPA href="/static/suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-params/123" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-dynamic-layout" />
</li>
<li>
<DebugLinkMPA href="/static/suspense-too-high" />
</li>
<li>
<DebugLinkMPA href="/static/blocking-layout" />
</li>
<li>
<DebugLinkMPA href="/static/blocking-layout/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/invalid-only-loading-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-runtime" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route/foo" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route/bar" />
</li>
<li>
<DebugLinkMPA href="/static/invalid-blocking-inside-static" />
</li>
<li>
<DebugLinkMPA href="/static/valid-blocked-children" />
</li>
<li>
<DebugLinkMPA href="/static/valid-blocking-inside-static" />
</li>
</ul>
<h2>Disable Validation</h2>
<ul>
<li>
<DebugLinkMPA href="/disable-validation/in-layout" />
</li>
<li>
<DebugLinkMPA href="/disable-validation/in-page" />
</li>
<li>
<DebugLinkMPA href="/disable-validation/in-page-with-outer" />
</li>
</ul>
</main>
)
}
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>
<a href="/">Home</a>
</header>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export default function Layout({ children }) {
return (
<Suspense fallback={<div>Loading...</div>}>
<p>
The layout blocks children on dynamic content, but shows a fallback, so
it's still instant when navigating from the root
</p>
<Dynamic />
<hr />
{children}
</Suspense>
)
}
async function Dynamic() {
await connection()
return 'Dynamic content from layout'
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<main>
<p>
The page blocks on dynamic content, but shows a fallback, so it's
instant
</p>
<Dynamic />
</main>
</Suspense>
)
}
async function Dynamic() {
await connection()
return 'Dynamic content from page'
}
import { Suspense } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function StaticLayout({ children }) {
return (
<div>
<p>The layout wraps children with Suspense.</p>
<hr />
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</div>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = false
export default async function BlockingPage() {
await cookies()
return (
<main>
<p>
The page is configured as blocking, but the parent layout has an
assertion, so we'll still perform a validation. This should pass because
the parent layout wraps a suspense around children.
</p>
</main>
)
}
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
unstable_disableValidation: true,
}
export default function Layout({ children }) {
return <>{children}</>
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return (
<main>
<p>
This page is beneath a layout that opted into runtime prefetching, and
is missing a suspense boundary around dynamic content, so it should fail
validation. However, the parent layout opted out of validation using{' '}
<code>unstable_disableValidation</code>, so we shouldn't error.
</p>
</main>
)
}
export const unstable_instant = {
prefetch: 'static',
}
export default function Layout({ children }) {
return <>{children}</>
}
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
unstable_disableValidation: true,
}
export default async function Page() {
await connection()
return (
<main>
<p>
This page opted into runtime prefetching, and is missing a suspense
boundary around dynamic content, so it should fail validation. However,
it opted out of validation using <code>unstable_disableValidation</code>
, so we shouldn't error.
</p>
</main>
)
}
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
unstable_disableValidation: true,
}
export default async function Page() {
await connection()
return (
<main>
<p>
This page opted into runtime prefetching, and is missing a suspense
boundary around dynamic content, so it should fail validation. However,
it opted out of validation using <code>unstable_disableValidation</code>
, so we shouldn't error.
</p>
</main>
)
}
import { ReactNode, Suspense } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
// We're mostly interested in checking client navigations,
// so to avoid having to give each test case a valid static shell,
// we put a Suspense above the body.
<Suspense fallback={<div>Root suspense boundary...</div>}>
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
</Suspense>
)
}
function Header() {
return (
<header>
<a href="/">Home</a>
</header>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function RuntimeLayout({ children }) {
await cookies()
return (
<div>
<p>The layout does not wrap children with Suspense.</p>
<hr />
{children}
</div>
)
}
import { connection } from 'next/server'
export const unstable_instant = false
export default async function BlockingPage() {
await connection()
return (
<main>
<p>
The page is configured as blocking, but the parent layout has an
assertion, so we'll still perform a validation. This should faild
because the parent layout doesn't have a suspense around children.
</p>
</main>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
await cookies()
const now = Date.now()
return (
<main>
<p>This page uses sync IO after awaiting cookies(): {now}</p>
</main>
)
}
import { connection } from 'next/server'
import { ReactNode } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Layout({ children }: { children: ReactNode }) {
await connection()
return (
<div>
<p>
This is a layout that uses dynamic data without a suspense, so it should
error the runtime prefetch assertion
</p>
<hr />
{children}
</div>
)
}
export default async function Page() {
return (
<main>
<p>The page itself is static</p>
</main>
)
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
await cookies()
return (
<main>
<div>
<p>
Dynamic content needs a Suspense boundary, but it's missing here, so
we should error:
</p>
<Dynamic />
</div>
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page({
params,
}: {
params: Promise<{ param: string }>
}) {
return (
<main>
<div>
<p>Params don't need a suspense boundary when runtime-prefetched:</p>
<Runtime params={params} />
</div>
<div>
<p>But dynamic content does:</p>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
</main>
)
}
async function Runtime({ params }: { params: Promise<{ param: string }> }) {
const { param } = await params
return <div id="runtime-content">Param value: {param}</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
return (
<main>
<div>
<p>Runtime content doesn't need a suspense boundary:</p>
<Runtime />
</div>
<div>
<p>But dynamic content does:</p>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
</main>
)
}
async function Runtime() {
await cookies()
return <div id="runtime-content">Runtime content from page</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
import { ReactNode, Suspense } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
// TODO: technically, we could consider this is valid,
// because this layout isn't shared with anything else,
// so we'll always prefetch it together with the page and not have a blocking nav.
return <Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Page() {
await cookies()
return (
<main>
<div>
<p>
Dynamic content needs a Suspense boundary, and there is one above this
segment so the static shell is fine. but it's missing a Suspense here,
so this segment would block, and we should error:
</p>
<Dynamic />
</div>
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function RuntimeLayout({ children }) {
await cookies()
return (
<div>
<p>The layout wraps children with Suspense.</p>
<hr />
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</div>
)
}
import { connection } from 'next/server'
export const unstable_instant = false
export default async function BlockingPage() {
await connection()
return (
<main>
<p>
The page is configured as blocking, but the parent layout has an
assertion, so we'll still perform a validation. This should pass because
the parent layout wraps a suspense around children.
</p>
</main>
)
}
import { connection } from 'next/server'
import { ReactNode } from 'react'
export const unstable_instant = false
export default async function Layout({ children }: { children: ReactNode }) {
await connection()
return (
<>
<div>This layout blocks the children</div>
<hr />
{children}
</>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
await cookies()
return (
<main>
This is a page that uses runtime data without a suspense, so it should
error the static prefetch assertion even if nested under a
allowed-blocking layout
</main>
)
}
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>This is a static page below a blocking layout</p>
</main>
)
}
export const unstable_instant = { prefetch: 'static' }
export default function StaticLayout({ children }) {
return (
<div>
<p>The layout does not wrap children with Suspense.</p>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = false
export default async function BlockingPage() {
await cookies()
return (
<main>
<p>
The page is configured as blocking, but the parent layout has an
assertion, so we'll still perform a validation. This should fail because
the parent layout does not wrap a suspense around children.
</p>
</main>
)
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>
This page doesn't wrap runtime/dynamic components in suspense, so
despite having a loading.tsx (which is equivalent to a suspense boundary
in a parent layout), it shouldn't pass validation, because a
self-navigation would block.
</p>
<div>
<Runtime />
</div>
<div>
<Dynamic />
</div>
</main>
)
}
async function Runtime() {
await cookies()
return <div id="runtime-content">Runtime content from page</div>
}
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default async function Layout({ children }: { children: ReactNode }) {
await cookies()
return (
<div>
<p>
This is a layout that uses runtime data without a suspense, so it should
error the static prefetch assertion
</p>
<hr />
{children}
</div>
)
}
export default async function Page() {
return (
<main>
<p>The page itself is static</p>
</main>
)
}
import { connection } from 'next/server'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
await connection()
return (
<main>
<p>
For a statically prefetchable page, Dynamic content needs a Suspense
boundary, but it's missing here, so we should error
</p>
</main>
)
}
export const unstable_instant = { prefetch: 'static' }
export default async function Page({
params,
}: {
params: Promise<{ param: string }>
}) {
return (
<main>
<p>Params need a suspense boundary when statically prefetched.</p>
<Runtime params={params} />
</main>
)
}
async function Runtime({ params }: { params: Promise<{ param: string }> }) {
const { param } = await params
return <div id="runtime-content">Param value: {param}</div>
}
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
await cookies()
return (
<main>
<p>
For a statically prefetchable page, Runtime content needs a Suspense
boundary, but it's missing here, so we should error
</p>
</main>
)
}
import { cookies } from 'next/headers'
export default async function DefaultSlot() {
await cookies()
return (
<p style={{ color: 'green' }}>
This is a default parallel slot that awaits cookies() without Suspense
</p>
)
}
import { cookies } from 'next/headers'
export default async function FooSlot() {
await cookies()
return (
<p style={{ color: 'tomato' }}>
This is a different parallel layout slot that awaits cookies() without
Suspense
</p>
)
}
export const unstable_instant = { prefetch: 'static' }
export default function SlotLayout({ children }) {
return (
<div>
<em>This is a layout inside the slot</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export default async function IndexSlot() {
await cookies()
return (
<p style={{ color: 'blue' }}>
This is a parallel layout slot that awaits cookies() without Suspense
</p>
)
}
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>This is an even different static page</p>
</main>
)
}
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>This is a different static page</p>
</main>
)
}
import { ReactNode } from 'react'
export default async function Layout({
children,
slot,
}: {
children: ReactNode
slot: ReactNode
}) {
return (
<>
<div style={{ border: '1px solid blue', padding: '1em' }}>{slot}</div>
{children}
</>
)
}
import Link from 'next/link'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>This is a static page</p>
<Link href="./missing-suspense-in-parallel-route/foo">./foo</Link>
</main>
)
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>
This page wraps all runtime/dynamic components in suspense, so it
wouldn't block a navigation and should pass validation.
</p>
<div>
<p>Runtime content with a suspense boundary</p>
<Suspense fallback={<div>Loading...</div>}>
<Runtime />
</Suspense>
</div>
<div>
<p>Dynamic content with a suspense boundary</p>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
</main>
)
}
async function Runtime() {
await cookies()
return <div id="runtime-content">Runtime content from page</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content from page</div>
}
import { ReactNode, Suspense } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
// TODO: technically, we could consider this is valid,
// because this layout isn't shared with anything else,
// so we'll always prefetch it together with the page and not have a blocking nav.
return (
<div>
<p>this layout adds a suspense boundary around children:</p>
<div style={{ padding: '1em', border: '1px solid blue' }}>
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</div>
</div>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
await cookies()
return (
<main>
<p>This page blocks when navigating inside the parent layout</p>
</main>
)
}
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
export function LinkToSelfWithSearch({
name,
value,
}: {
name: string
value: string | null
}) {
const pathname = usePathname()
let href: string
if (value === null) {
href = pathname
} else {
href = pathname + '?' + new URLSearchParams([[name, value]])
}
return <Link href={href}>{href}</Link>
}
import { cacheLife } from 'next/cache'
import { setTimeout } from 'timers/promises'
export async function uncachedIO() {
await setTimeout(0)
}
export async function cachedDelay(key: any) {
'use cache'
cacheLife('minutes')
await setTimeout(1)
}
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 { ComponentProps } from 'react'
export function DebugLinkMPA({
href,
...props
}: Omit<ComponentProps<'a'>, 'children'>) {
return (
<a href={href} {...props}>
{href}
</a>
)
}
This diff is collapsed.
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
productionBrowserSourceMaps: true,
experimental: {
reactDebugChannel: process.env.REACT_DEBUG_CHANNEL ? true : false,
},
typescript: {
ignoreBuildErrors: true,
},
}
export default nextConfig
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