Unverified Commit ed5d085f authored by Josh Story's avatar Josh Story Committed by GitHub

[Cache Components] Error for Sync IO in Server Components during Static Prerender (#82500)

Currently we error if you cannot produce a shell unless you have a
Suspense boundary above the root. This is fine for normal IO but sync IO
like Math.random() and new Date() have much more significant bad
consequences for prerendering. Instead of treating these errors as
another flavor of "must have a shell" validation we should instead treat
them like they must be guarded behind something else dynamic like `await
connection()`.

In addition to unconditionally erroring for Sync IO in Server Components
when prerendering this change also removes the Sync IO warning for
runtime prefetches. This is because at the moment there is no way to
debug these errors in dev. In the future we will add validation for
prefetches and need to add back in some ability to warn for these cases
but until then we will leave this case as a silent deopt.
parent 8dd5f486
--- ---
title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or another web or node crypto API that generates random values synchronously in a Server Component title: Cannot access `crypto.getRandomValue()`, `crypto.randomUUID()`, or another web or node crypto API that generates random values synchronously before other uncached data or Request data in a Server Component
--- ---
## Why This Error Occurred ## Why This Error Occurred
An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` API was called outside of a `"use cache"` scope and without first calling `await connection()`. Random values that are produced synchronously must either be inside a `"use cache"` scope or be preceded with `await connection()` to explicitly communicate to Next.js whether the random values produced can be reused across many requests (cached) or if they must be unique per Request (`await connection()`). An API that produces a random value synchronously from the Web Crypto API or from Node's `crypto` package was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or Request data through Next.js APIs like `cookies()`, `headers()`, `connection()` and `searchParams`. Accessing random values synchronously in this way interferes with the prerendering and prefetching capabilities of Next.js.
If the API used has an async version you can also switch to that instead of using `await connection()`.
## Possible Ways to Fix It ## Possible Ways to Fix It
If the random crypto value is appropriate to be prerendered and prefetched consider moving it into a Cache Component or Cache Function with the `"use cache"` directive.
If the random crypto value is intended to be generated on every user request consider whether an async API exists that achieves the same result. If not consider whether you can move the random crypto value generation later, behind other existing uncached data or Request data access. If there is no way to do this you can always precede the random crypto value generation with Request data access by using `await connection()`.
### Cache the token value ### Cache the token value
If you are generating a token to talk to a database that itself should be cached move the token generation inside the `"use cache"`. If you are generating a token to talk to a database that itself should be cached move the token generation inside the `"use cache"`.
......
--- ---
title: Cannot infer intended usage of current time with `Date.now()`, `Date()`, or `new Date()` in a Server Component title: Cannot access `Date.now()`, `Date()`, or `new Date()` before other uncached data or Request data in a Server Component
--- ---
## Why This Error Occurred ## Why This Error Occurred
Reading the current time in a Server Component can be ambiguous. Sometimes you intend to capture the time when something was cached, other times you intend to capture the time of a user Request. You might also be trying to measure runtime performance to track elapsed time. `Date.now()`, `Date()`, or `new Date()` was used in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or Request data through built-in APIs like `cookies()`, `headers()`, `connection()` and `searchParams`. Accessing the current time in this way interferes with the prerendering and prefetching capabilities of Next.js.
Depending on your use case you might use alternative time APIs like `performance.now()`, you might cache the time read with `"use cache"`, or you might communicate that the time must be evaluated on each request by guarding it with `await connection()` or moving it into a Client Component.
## Possible Ways to Fix It ## Possible Ways to Fix It
If the current time is being used for diagnostic purposes such as logging or performance tracking consider using `performance.now()` instead.
If the current time is appropriate to be prerendered and prefetched consider moving it into a Cache Component or Cache Function with the `"use cache"` directive.
If the current time is intended to be accessed dynamically on every user request first consider whether it is more appropriate to access it in a Client Component, which can often be the case when reading the time for display purposes. If a Client Component isn't the right choice then consider whether you can move the current time access later, behind other existing uncached data or Request data access. If there is no way to do this you can always precede the current time access with Request data access by using `await connection()`.
> **Note**: Sometimes the place that accesses the current time is inside 3rd party code. While you can't easily convert the time access to `performance.now()` the other strategies can be applied in your own project code regardless of how deeply the time is read.
### Performance use case ### Performance use case
If you are using the current time for performance tracking with elapsed time use `performance.now()`. If you are using the current time for performance tracking with elapsed time use `performance.now()`.
...@@ -40,6 +46,7 @@ export default async function Page() { ...@@ -40,6 +46,7 @@ export default async function Page() {
``` ```
> **Note**: If you need report an absolute time to an observability tool you can also use `performance.timeOrigin + performance.now()`. > **Note**: If you need report an absolute time to an observability tool you can also use `performance.timeOrigin + performance.now()`.
> **Note**: It is essential that the values provided by `performance.now()` do not influence the rendered output of your Component and should never be passed into Cache Functions as arguments or props.
### Cacheable use cases ### Cacheable use cases
...@@ -214,6 +221,8 @@ async function DynamicBanner() { ...@@ -214,6 +221,8 @@ async function DynamicBanner() {
} }
``` ```
> **Note**: This example illustrates using `await connection()`, but you could alternatively move where a uncached fetch happens or read cookies before as well.
## Useful Links ## Useful Links
- [`Date.now` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) - [`Date.now` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now)
......
--- ---
title: Cannot infer intended usage of `Math.random()` in a Server Component title: Cannot access `Math.random()` before other uncached data or Request data in a Server Component
--- ---
## Why This Error Occurred ## Why This Error Occurred
A Server Component is calling `Math.random()` without specifying whether it should be cached or whether it should be evaluated on each user Request. If you want this random value to be included in the prerendered HTML for this page you must cache it using `"use cache"`. If you want this random value to be unique per Request you must precede it with `await connection()` so Next.js knows to exclude it from the prerendered HTML. `Math.random()` was called in a Server Component before accessing other uncached data through APIs like `fetch()` and native database drivers, or Request data through built-in APIs like `cookies()`, `headers()`, `connection()` and `searchParams`. Accessing random values in this way interferes with the prerendering and prefetching capabilities of Next.js.
## Possible Ways to Fix It ## Possible Ways to Fix It
If the random value is appropriate to be prerendered and prefetched consider moving it into a Cache Component or Cache Function with the `"use cache"` directive.
If the random value is intended to be generated on every user request consider whether you can move the random value generation later, behind other existing uncached data or Request data access. If there is no way to do this you can always precede the random value generation with Request data access by using `await connection()`.
If the random value is being used as a unique identifier for diagnostic purposes such as logging or tracking consider using an alternate method of id generation that does not rely on random number generation such as incrementing an integer.
> **Note**: Sometimes the place that generates a random value synchronously is inside 3rd party code. While you can't easily replace the `Math.random()` call directly, the other strategies can be applied in your own project code regardless of how deep random generation is.
### Cache the random value ### Cache the random value
If your random value is cacheable, move the `Math.random()` call to a `"use cache"` function. For instance, imagine you have a product page and you want to randomize the product order periodically but you are fine with the random order being re-used for different users. If your random value is cacheable, move the `Math.random()` call to a `"use cache"` function. For instance, imagine you have a product page and you want to randomize the product order periodically but you are fine with the random order being re-used for different users.
......
...@@ -138,7 +138,6 @@ import { ...@@ -138,7 +138,6 @@ import {
consumeDynamicAccess, consumeDynamicAccess,
type DynamicAccess, type DynamicAccess,
logDisallowedDynamicError, logDisallowedDynamicError,
warnOnSyncDynamicError,
} from './dynamic-rendering' } from './dynamic-rendering'
import { import {
getClientComponentLoaderMetrics, getClientComponentLoaderMetrics,
...@@ -909,8 +908,6 @@ async function finalRuntimeServerPrerender( ...@@ -909,8 +908,6 @@ async function finalRuntimeServerPrerender(
} }
) )
warnOnSyncDynamicError(serverDynamicTracking)
return { return {
result, result,
// TODO(runtime-ppr): do we need to produce a digest map here? // TODO(runtime-ppr): do we need to produce a digest map here?
......
...@@ -341,21 +341,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -341,21 +341,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
) )
} }
/**
* Use this function when dynamically prerendering with dynamicIO.
* We don't want to error, because it's better to return something
* (and we've already aborted the render at the point where the sync dynamic error occured),
* but we should log an error server-side.
* @internal
*/
export function warnOnSyncDynamicError(dynamicTracking: DynamicTrackingState) {
if (dynamicTracking.syncDynamicErrorWithStack) {
// the server did something sync dynamic, likely
// leading to an early termination of the prerender.
console.error(dynamicTracking.syncDynamicErrorWithStack)
}
}
// For now these implementations are the same so we just reexport // For now these implementations are the same so we just reexport
export const trackSynchronousRequestDataAccessInDev = export const trackSynchronousRequestDataAccessInDev =
trackSynchronousPlatformIOAccessInDev trackSynchronousPlatformIOAccessInDev
...@@ -778,6 +763,14 @@ export function throwIfDisallowedDynamic( ...@@ -778,6 +763,14 @@ export function throwIfDisallowedDynamic(
dynamicValidation: DynamicValidationState, dynamicValidation: DynamicValidationState,
serverDynamic: DynamicTrackingState serverDynamic: DynamicTrackingState
): void { ): void {
if (serverDynamic.syncDynamicErrorWithStack) {
logDisallowedDynamicError(
workStore,
serverDynamic.syncDynamicErrorWithStack
)
throw new StaticGenBailoutError()
}
if (prelude !== PreludeState.Full) { if (prelude !== PreludeState.Full) {
if (dynamicValidation.hasSuspenseAboveBody) { if (dynamicValidation.hasSuspenseAboveBody) {
// This route has opted into allowing fully dynamic rendering // This route has opted into allowing fully dynamic rendering
...@@ -786,17 +779,6 @@ export function throwIfDisallowedDynamic( ...@@ -786,17 +779,6 @@ export function throwIfDisallowedDynamic(
return return
} }
if (serverDynamic.syncDynamicErrorWithStack) {
// There is no shell and the server did something sync dynamic likely
// leading to an early termination of the prerender before the shell
// could be completed. We terminate the build/validating render.
logDisallowedDynamicError(
workStore,
serverDynamic.syncDynamicErrorWithStack
)
throw new StaticGenBailoutError()
}
// We didn't have any sync bailouts but there may be user code which // 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 // blocked the root. We would have captured these during the prerender
// and can log them here and then terminate the build/validating render // and can log them here and then terminate the build/validating render
......
...@@ -30,13 +30,13 @@ export function io(expression: string, type: ApiType) { ...@@ -30,13 +30,13 @@ export function io(expression: string, type: ApiType) {
let message: string let message: string
switch (type) { switch (type) {
case 'time': case 'time':
message = `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time` message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
break break
case 'random': case 'random':
message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random` message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
break break
case 'crypto': case 'crypto':
message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto` message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random cryptographic values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break break
default: default:
throw new InvariantError( throw new InvariantError(
......
...@@ -22,7 +22,7 @@ describe('Cache Components Dev Errors', () => { ...@@ -22,7 +22,7 @@ describe('Cache Components Dev Errors', () => {
// soft-navigating to the page (see test below). // soft-navigating to the page (see test below).
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
{ {
"description": "Route "/error" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random", "description": "Route "/error" used \`Math.random()\` before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Console Error", "label": "Console Error",
"source": "app/error/page.tsx (2:23) @ Page "source": "app/error/page.tsx (2:23) @ Page
...@@ -52,7 +52,7 @@ describe('Cache Components Dev Errors', () => { ...@@ -52,7 +52,7 @@ describe('Cache Components Dev Errors', () => {
// TODO: React should not include the anon stack in the Owner Stack. // TODO: React should not include the anon stack in the Owner Stack.
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
{ {
"description": "Route "/error" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random", "description": "Route "/error" used \`Math.random()\` before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Console Error", "label": "Console Error",
"source": "app/error/page.tsx (2:23) @ Page "source": "app/error/page.tsx (2:23) @ Page
......
This source diff could not be displayed because it is too large. You can view the blob instead.
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page accesses the current time `Date.now()` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<DateReadingComponent />
</Suspense>
</>
)
}
async function DateReadingComponent() {
await new Promise((r) => process.nextTick(r))
return <div>{Date.now()}</div>
}
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page accesses the current time `Date()` in a Server Component which
is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<DateReadingComponent />
</Suspense>
</>
)
}
async function DateReadingComponent() {
await new Promise((r) => process.nextTick(r))
return <div>{Date()}</div>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page accesses the current time `new Date()` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<DateReadingComponent />
</Suspense>
</>
)
}
async function DateReadingComponent() {
await new Promise((r) => process.nextTick(r))
return <div>{new Date().toString()}</div>
}
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { Suspense } from 'react'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() { export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = crypto.generateKeyPairSync('rsa', keyGenOptions)
const second = crypto.generateKeyPairSync('rsa', keyGenOptions)
return ( return (
<div> <>
<dl> <p>
<dt> This page uses Node's `crypto.generateKeyPairSync()` in a Server
[first] require('node:crypto').generateKeyPairSync(type, options) Component which is an error unless preceded by something else dynamic
</dt> </p>
<dd id="first">{first.publicKey}</dd> <Suspense fallback="loading...">
<dt> <SyncIOComponent />
[second] require('node:crypto').generateKeyPairSync(type, options) </Suspense>
</dt> </>
<dd id="second">{second.publicKey}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
) )
} }
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = crypto.generateKeyPairSync('rsa', keyGenOptions)
return <div>{first.publicKey}</div>
}
const keyGenOptions = { const keyGenOptions = {
modulusLength: 512, modulusLength: 512,
publicKeyEncoding: { publicKeyEncoding: {
......
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { Suspense } from 'react'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() { export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto .generateKeySync()` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r)) await new Promise((r) => process.nextTick(r))
const first = crypto const first = crypto
.generateKeySync('hmac', { .generateKeySync('hmac', {
length: 512, length: 512,
}) })
.export() .export()
const second = crypto return <div>{first.toString('hex')}</div>
.generateKeySync('hmac', {
length: 512,
})
.export()
return (
<div>
<dl>
<dt>[first] require('node:crypto').generateKeySync(type, options)</dt>
<dd id="first">{first.toString('hex')}</dd>
<dt>[second] require('node:crypto').generateKeySync(type, options)</dt>
<dd id="second">{second.toString('hex')}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
} }
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { Suspense } from 'react'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() { export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = new Uint8Array(crypto.generatePrimeSync(128))
const second = new Uint8Array(crypto.generatePrimeSync(128))
return ( return (
<div> <>
<dl> <p>
<dt>[first] require('node:crypto').generatePrimeSync(size)</dt> This page uses Node's `crypto.generatePrimeSync()` in a Server Component
<dd id="first">{first.toString()}</dd> which is an error unless preceded by something else dynamic
<dt>[second] require('node:crypto').generatePrimeSync(size)</dt> </p>
<dd id="second">{second.toString()}</dd> <Suspense fallback="loading...">
</dl> <SyncIOComponent />
<span id="page"> </Suspense>
<SentinelValue /> </>
</span>
</div>
) )
} }
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = new Uint8Array(crypto.generatePrimeSync(128))
return <div>{first.toString()}</div>
}
import crypto from 'node:crypto'
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto.getRandomValues()` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = new Uint8Array(8)
crypto.getRandomValues(first)
return <div>{first.toString()}</div>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import crypto from 'node:crypto'
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto.randomBytes()` in a Server Component which
is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomBytes(8)
return <div>{first.toString()}</div>
}
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { Suspense } from 'react'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() { export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto.randomFillSync()` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r)) await new Promise((r) => process.nextTick(r))
const first = new Uint8Array(16) const first = new Uint8Array(16)
const second = new Uint8Array(16)
crypto.randomFillSync(first, 4, 8) crypto.randomFillSync(first, 4, 8)
crypto.randomFillSync(second, 4, 8) return <div>{first.toString()}</div>
return (
<div>
<dl>
<dt>[first] require('node:crypto').randomFillSync(buffer)</dt>
<dd id="first">{first.toString()}</dd>
<dt>[second] require('node:crypto').randomBytes(buffer)</dt>
<dd id="second">{second.toString()}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
} }
import crypto from 'node:crypto'
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto.randomInt(x, y)` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomInt(128, 256)
return <div>{first}</div>
}
import crypto from 'node:crypto'
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto.randomInt(x)` in a Server Component which
is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomInt(128)
return <div>{first}</div>
}
import crypto from 'node:crypto'
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses Node's `crypto.randomInt(x)` in a Server Component which
is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomUUID()
return <div>{first}</div>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page produces a random number `Math.random()` in a Server Component
which is an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
return <div>{Math.random()}</div>
}
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses `crypto.getRandomValue()` in a Server Component which is
an error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
const buffer = new Uint8Array(8)
crypto.getRandomValues(buffer)
return <div>{buffer.toString()}</div>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { Suspense } from 'react'
export default async function Page() {
return (
<>
<p>
This page uses `crypto.randomUUID()` in a Server Component which is an
error unless preceded by something else dynamic
</p>
<Suspense fallback="loading...">
<SyncIOComponent />
</Suspense>
</>
)
}
async function SyncIOComponent() {
await new Promise((r) => process.nextTick(r))
return <div>{crypto.randomUUID()}</div>
}
...@@ -81,6 +81,7 @@ describe(`Request Promises`, () => { ...@@ -81,6 +81,7 @@ describe(`Request Promises`, () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname + '/fixtures/reject-hanging-promises-dynamic', files: __dirname + '/fixtures/reject-hanging-promises-dynamic',
skipStart: true, skipStart: true,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -95,9 +96,7 @@ describe(`Request Promises`, () => { ...@@ -95,9 +96,7 @@ describe(`Request Promises`, () => {
it('should reject request APIs after the prerender is interrupted with synchronously dynamic APIs', async () => { it('should reject request APIs after the prerender is interrupted with synchronously dynamic APIs', async () => {
try { try {
await next.start() await next.start()
} catch { } catch {}
throw new Error('expected build not to fail for fully static project')
}
const expectError = createExpectError(next.cliOutput) const expectError = createExpectError(next.cliOutput)
expectError( expectError(
......
import { cookies, headers, draftMode } from 'next/headers' import { cookies, headers, draftMode } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
export function generateStaticParams() {
return [{ slug: 'one' }]
}
export default async function Page(props: { export default async function Page(props: {
params: Promise<{}> params: Promise<{}>
searchParams: Promise<{}> searchParams: Promise<{}>
......
import { cookies, headers, draftMode } from 'next/headers' import { cookies, headers, draftMode } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
export function generateStaticParams() {
return [{ slug: 'one' }]
}
export default async function Page(props: { export default async function Page(props: {
params: Promise<{}> params: Promise<{}>
searchParams: Promise<{}> searchParams: Promise<{}>
......
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const date = Date()
return (
<div>
<label>Date()</label>
<span id="value">{date}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const newDate = new Date()
return (
<div>
<label>new Date()</label>
<span id="value">{newDate.toString()}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const now = Date.now()
return (
<div>
<label>now</label>
<span id="value">{now}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import crypto from 'node:crypto'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = new Uint8Array(8)
const second = new Uint8Array(8)
await crypto.getRandomValues(first)
await crypto.getRandomValues(second)
return (
<div>
<dl>
<dt>[first] require('node:crypto').getRandomValues()</dt>
<dd id="first">{first.toString()}</dd>
<dt>[second] require('node:crypto').getRandomValues()</dt>
<dd id="second">{second.toString()}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import crypto from 'node:crypto'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomBytes(8, undefined) as unknown as Buffer
const second = crypto.randomBytes(8)
return (
<div>
<dl>
<dt>[first] require('node:crypto').randomBytes(size)</dt>
<dd id="first">{first.toString('hex')}</dd>
<dt>[second] require('node:crypto').randomUUID(size)</dt>
<dd id="second">{second.toString('hex')}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import crypto from 'node:crypto'
import { SentinelValue } from '../../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomInt(128, 256)
const second = crypto.randomInt(128, 256, undefined) as undefined as number
return (
<div>
<dl>
<dt>[first] require('node:crypto').randomInt(min, max)</dt>
<dd id="first">{first}</dd>
<dt>[second] require('node:crypto').randomInt(min, max)</dt>
<dd id="second">{second}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import crypto from 'node:crypto'
import { SentinelValue } from '../../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomInt(128)
let second = crypto.randomInt(128)
while (first === second) {
// Ensure that the second value is different from the first
second = crypto.randomInt(128)
}
return (
<div>
<dl>
<dt>[first] require('node:crypto').randomInt(max)</dt>
<dd id="first">{first}</dd>
<dt>[second] require('node:crypto').randomInt(max)</dt>
<dd id="second">{second}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import crypto from 'node:crypto'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomUUID()
const second = crypto.randomUUID()
return (
<div>
<dl>
<dt>[first] require('node:crypto').randomUUID()</dt>
<dd id="first">{first.toString()}</dd>
<dt>[second] require('node:crypto').randomUUID()</dt>
<dd id="second">{second.toString()}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const random = Math.random()
return (
<div>
<label>random</label>
<span id="value">{random}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = new Uint8Array(8)
const second = new Uint8Array(8)
await crypto.getRandomValues(first)
await crypto.getRandomValues(second)
return (
<div>
<dl>
<dt>[first] crypto.getRandomValues()</dt>
<dd id="first">{first.toString()}</dd>
<dt>[second] crypto.getRandomValues()</dt>
<dd id="second">{second.toString()}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
await new Promise((r) => process.nextTick(r))
const first = crypto.randomUUID()
const second = crypto.randomUUID()
return (
<div>
<dl>
<dt>[first] crypto.randomUUID()</dt>
<dd id="first">{first.toString()}</dd>
<dt>[second] crypto.randomUUID()</dt>
<dd id="second">{second.toString()}</dd>
</dl>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
...@@ -29,19 +29,6 @@ describe('cache-components', () => { ...@@ -29,19 +29,6 @@ describe('cache-components', () => {
} }
}) })
it('should not prerender pages with uncached `Date.now()` calls', async () => {
let $ = await next.render$('/date/now/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toMatch(/^\d+$/)
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toMatch(/^\d+$/)
}
})
it('should prerender pages with cached `Date()` calls', async () => { it('should prerender pages with cached `Date()` calls', async () => {
let $ = await next.render$('/date/date/cached', {}) let $ = await next.render$('/date/date/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -55,19 +42,6 @@ describe('cache-components', () => { ...@@ -55,19 +42,6 @@ describe('cache-components', () => {
} }
}) })
it('should not prerender pages with uncached `Date()` calls', async () => {
let $ = await next.render$('/date/date/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should prerender pages with cached `new Date()` calls', async () => { it('should prerender pages with cached `new Date()` calls', async () => {
let $ = await next.render$('/date/new-date/cached', {}) let $ = await next.render$('/date/new-date/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -81,19 +55,6 @@ describe('cache-components', () => { ...@@ -81,19 +55,6 @@ describe('cache-components', () => {
} }
}) })
it('should not prerender pages with uncached `new Date()` calls', async () => {
let $ = await next.render$('/date/new-date/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should prerender pages with cached static Date instances like `new Date(0)`', async () => { it('should prerender pages with cached static Date instances like `new Date(0)`', async () => {
let $ = await next.render$('/date/static-date/cached', {}) let $ = await next.render$('/date/static-date/cached', {})
if (isNextDev) { if (isNextDev) {
......
...@@ -28,19 +28,6 @@ describe('cache-components', () => { ...@@ -28,19 +28,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').getRandomValues(...)` calls", async () => {
let $ = await next.render$('/node-crypto/get-random-values/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').randomUUID()` calls", async () => { it("should prerender pages with cached `require('node:crypto').randomUUID()` calls", async () => {
let $ = await next.render$('/node-crypto/random-uuid/cached', {}) let $ = await next.render$('/node-crypto/random-uuid/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -54,19 +41,6 @@ describe('cache-components', () => { ...@@ -54,19 +41,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').randomUUID()` calls", async () => {
let $ = await next.render$('/node-crypto/random-uuid/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').randomBytes(size)` calls", async () => { it("should prerender pages with cached `require('node:crypto').randomBytes(size)` calls", async () => {
let $ = await next.render$('/node-crypto/random-bytes/cached', {}) let $ = await next.render$('/node-crypto/random-bytes/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -80,19 +54,6 @@ describe('cache-components', () => { ...@@ -80,19 +54,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').randomBytes(size)` calls", async () => {
let $ = await next.render$('/node-crypto/random-bytes/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').randomFillSync(buffer)` calls", async () => { it("should prerender pages with cached `require('node:crypto').randomFillSync(buffer)` calls", async () => {
let $ = await next.render$('/node-crypto/random-fill-sync/cached', {}) let $ = await next.render$('/node-crypto/random-fill-sync/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -106,19 +67,6 @@ describe('cache-components', () => { ...@@ -106,19 +67,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').randomFillSync(buffer)` calls", async () => {
let $ = await next.render$('/node-crypto/random-fill-sync/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').randomInt(max)` calls", async () => { it("should prerender pages with cached `require('node:crypto').randomInt(max)` calls", async () => {
let $ = await next.render$('/node-crypto/random-int/up-to/cached', {}) let $ = await next.render$('/node-crypto/random-int/up-to/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -132,19 +80,6 @@ describe('cache-components', () => { ...@@ -132,19 +80,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').randomInt(max)` calls", async () => {
let $ = await next.render$('/node-crypto/random-int/up-to/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').randomInt(min, max)` calls", async () => { it("should prerender pages with cached `require('node:crypto').randomInt(min, max)` calls", async () => {
let $ = await next.render$('/node-crypto/random-int/between/cached', {}) let $ = await next.render$('/node-crypto/random-int/between/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -158,19 +93,6 @@ describe('cache-components', () => { ...@@ -158,19 +93,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').randomInt(min, max)` calls", async () => {
let $ = await next.render$('/node-crypto/random-int/between/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').generatePrimeSync(size, options)` calls", async () => { it("should prerender pages with cached `require('node:crypto').generatePrimeSync(size, options)` calls", async () => {
let $ = await next.render$('/node-crypto/generate-prime-sync/cached', {}) let $ = await next.render$('/node-crypto/generate-prime-sync/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -184,19 +106,6 @@ describe('cache-components', () => { ...@@ -184,19 +106,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').generatePrimeSync(size, options)` calls", async () => {
let $ = await next.render$('/node-crypto/generate-prime-sync/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').generateKeyPairSync(type, options)` calls", async () => { it("should prerender pages with cached `require('node:crypto').generateKeyPairSync(type, options)` calls", async () => {
let $ = await next.render$('/node-crypto/generate-key-pair-sync/cached', {}) let $ = await next.render$('/node-crypto/generate-key-pair-sync/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -210,22 +119,6 @@ describe('cache-components', () => { ...@@ -210,22 +119,6 @@ describe('cache-components', () => {
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').generateKeyPairSync(type, options)` calls", async () => {
let $ = await next.render$(
'/node-crypto/generate-key-pair-sync/uncached',
{}
)
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it("should prerender pages with cached `require('node:crypto').generateKeySync(type, options)` calls", async () => { it("should prerender pages with cached `require('node:crypto').generateKeySync(type, options)` calls", async () => {
let $ = await next.render$('/node-crypto/generate-key-sync/cached', {}) let $ = await next.render$('/node-crypto/generate-key-sync/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -238,17 +131,4 @@ describe('cache-components', () => { ...@@ -238,17 +131,4 @@ describe('cache-components', () => {
expect($('#first').text()).not.toEqual($('#second').text()) expect($('#first').text()).not.toEqual($('#second').text())
} }
}) })
it("should not prerender pages with uncached `require('node:crypto').generateKeySync(type, options)` calls", async () => {
let $ = await next.render$('/node-crypto/generate-key-sync/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
}) })
...@@ -25,15 +25,4 @@ describe('cache-components', () => { ...@@ -25,15 +25,4 @@ describe('cache-components', () => {
expect($('#page').text()).toBe('at buildtime') expect($('#page').text()).toBe('at buildtime')
} }
}) })
it('should not prerender pages with uncached Math.random() calls', async () => {
let $ = await next.render$('/random/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
}
})
}) })
...@@ -28,19 +28,6 @@ describe('cache-components', () => { ...@@ -28,19 +28,6 @@ describe('cache-components', () => {
} }
}) })
it('should not prerender pages with uncached `crypto.getRandomValues(...)` calls', async () => {
let $ = await next.render$('/web-crypto/get-random-values/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
it('should prerender pages with cached `crypto.randomUUID()` calls', async () => { it('should prerender pages with cached `crypto.randomUUID()` calls', async () => {
let $ = await next.render$('/web-crypto/random-uuid/cached', {}) let $ = await next.render$('/web-crypto/random-uuid/cached', {})
if (isNextDev) { if (isNextDev) {
...@@ -53,17 +40,4 @@ describe('cache-components', () => { ...@@ -53,17 +40,4 @@ describe('cache-components', () => {
expect($('#first').text()).not.toEqual($('#second').text()) expect($('#first').text()).not.toEqual($('#second').text())
} }
}) })
it('should not prerender pages with uncached `crypto.randomUUID()` calls', async () => {
let $ = await next.render$('/web-crypto/random-uuid/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#first').text()).not.toEqual($('#second').text())
}
})
}) })
export default async function Page() {
if (typeof process !== 'undefined') {
// we delay the random calls to avoid triggering dynamic in other component trees
await new Promise((r) => process.nextTick(r))
}
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
...@@ -25,11 +25,6 @@ describe('Node Extensions', () => { ...@@ -25,11 +25,6 @@ describe('Node Extensions', () => {
it('should not error when accessing pages that use Math.random() in App Router', async () => { it('should not error when accessing pages that use Math.random() in App Router', async () => {
let res, $ let res, $
res = await next.fetch('/app/prerendered/uncached')
expect(res.status).toBe(200)
$ = await next.render$('/app/prerendered/uncached')
expect($('li').length).toBe(2)
res = await next.fetch('/app/prerendered/unstable-cache') res = await next.fetch('/app/prerendered/unstable-cache')
expect(res.status).toBe(200) expect(res.status).toBe(200)
$ = await next.render$('/app/prerendered/unstable-cache') $ = await next.render$('/app/prerendered/unstable-cache')
......
...@@ -1008,7 +1008,7 @@ describe('<Link prefetch={true}> (runtime prefetch)', () => { ...@@ -1008,7 +1008,7 @@ describe('<Link prefetch={true}> (runtime prefetch)', () => {
path: '/errors/sync-io-after-runtime-api/quickly-expiring-public-cache', path: '/errors/sync-io-after-runtime-api/quickly-expiring-public-cache',
}, },
])( ])(
'aborts the prerender and logs an error $description', 'aborts the prerender without logging an error $description',
async ({ path }) => { async ({ path }) => {
// In a runtime prefetch, we might encounter sync IO usages that weren't caught during build, // In a runtime prefetch, we might encounter sync IO usages that weren't caught during build,
// because they were hidden behind e.g. a cookies() call. // because they were hidden behind e.g. a cookies() call.
...@@ -1047,9 +1047,7 @@ describe('<Link prefetch={true}> (runtime prefetch)', () => { ...@@ -1047,9 +1047,7 @@ describe('<Link prefetch={true}> (runtime prefetch)', () => {
]) ])
if (!isNextDeploy) { if (!isNextDeploy) {
expect(getCliOutput()).toMatch( expect(getCliOutput()).not.toMatch(`Date.now()`)
/Error: Route ".*?" used `Date\.now\(\)` instead of using `performance` or without explicitly calling `await connection\(\)` beforehand\./
)
} }
// Navigate to the page // Navigate to the page
......
...@@ -6,6 +6,8 @@ export async function generateMetadata(): Promise<Metadata> { ...@@ -6,6 +6,8 @@ export async function generateMetadata(): Promise<Metadata> {
// TODO: Deduping with nested caches requires #78703. // TODO: Deduping with nested caches requires #78703.
// 'use cache' // 'use cache'
await connection()
return { return {
description: new Date().toISOString(), description: new Date().toISOString(),
title: await getCachedData(), title: await getCachedData(),
......
...@@ -222,7 +222,7 @@ describe('build-output-prerender', () => { ...@@ -222,7 +222,7 @@ describe('build-output-prerender', () => {
6 | 6 |
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/client" in your browser to investigate the error. To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/client" in your browser to investigate the error.
Error occurred prerendering page "/client". Read more: https://nextjs.org/docs/messages/prerender-error Error occurred prerendering page "/client". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Route "/server" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random Error: Route "/server" used \`Math.random()\` before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random
at Page (bundler:///app/server/page.tsx:13:27) at Page (bundler:///app/server/page.tsx:13:27)
11 | await cachedDelay() 11 | await cachedDelay()
12 | 12 |
......
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