Unverified Commit 1f462140 authored by Josh Story's avatar Josh Story Committed by GitHub

[dynamicIO] refine error messaging for sync API access (#71467)

Temporarily removing the dev warnings. I've moved these to be errors in
the build side. In a follow up PR I will use prerendering during dev to
trigger these errors and report them as dev errors as well.

This also updates how we track sync dynamic errors. The main goal is to
have a stack trace of the sync function and separately report all the
component stacks that might contain this function call. It's not
fool-proof b/c the sync api may be called in a way that is not observed
by SSR. The whole debugging story here will improve dramatically with
owner stacks but that is currently experimental only in React.

The plan for future updates is to add a prospective render for SSR so we
can flush out module scope issues like calling Math.random while lazy
initializing a module. This is asserted for RSC in this change (see new
tests) but won't wouldn't pass for SSR b/c we only do single pass
prerendering at the moment.

After that I will add in the prerender-while-render in dev and utilize
the prerender errors to power dev as well.
parent 5c404e90
---
title: Cannot access Request information synchronously with `cookies()`, `headers()`, or `draftMode()`
---
#### Why This Error Occurred
In Next.js 15 global functions that provide access to Request Header information such as `cookies()`, `headers()`, and `draftMode()` are each now `async` and return a `Promise` rather than the associated object directly.
To support migrating to the async APIs Next.js 15 still supports accessing properties of the underlying object directly on the returned Promise. However when `dynamicIO` is enabled it is an error to do so.
#### Possible Ways to Fix It
If you haven't already followed the Next.js 15 upgrade guide which includes running a codemod to auto-convert to the necessary async form of these APIs start there.
[Next 15 Upgrade Guide](https://nextjs.org/docs/app/building-your-application/upgrading/version-15#async-request-apis-breaking-change)
If you have already run the codemod on your project look for instances of the string `@next-codemod-error` to see where the codemod was unable to convert to the async form. You will have to refactor your code manually here to make it compatible with the new result type.
Before:
```jsx filename=".../token-utils.js"
// This function is sync and the codemod won't make it async
// because it doesn't know about every callsite that uses it.
export function getToken() {
// @next-codemod-error ...
return cookies().get('token')
}
```
```jsx filename="app/page.js"
import { getToken } from '.../token-utils'
export default function Page() {
const token = getToken();
validateToken(token)
return ...
}
```
After:
```jsx filename=".../token-utils.js"
export async function Page() {
return (await cookies()).get(token)
}
```
```jsx filename="app/page.js"
import { getToken } from '.../token-utils'
export default async function Page() {
const token = await getToken();
validateToken(token)
return ...
}
```
If you do not find instances of this string then it is possible the synchronous use of Request Header data is inside a 3rd party library. You should identify which library is using this function and see if it has published a Next 15 compatible version that adheres to the new Promise return type.
as a last resort you can add `await connection()` before calling the 3rd party function which uses this API. This will inform Next.js that everything after this await should be excluded from prerendering. This will continue to work until we remove support for synchronously access Request data which is expected to happen in the next major version.
Before:
```jsx filename="app/page.js"
import { getDataFrom3rdParty } from '3rdparty'
export default function Page() {
// Imagine this function access Request data synchronously
// on the inside even if it has an async external interface
const token = await getDataFrom3rdParty();
return ...
}
```
After:
```jsx filename="app/page.js"
import { connection } from 'next/server'
export default async function Page() {
await connection()
// Everything from here down will be excluded from prerendering
const token = await getDataFrom3rdParty();
validateToken(token)
return ...
}
```
Note that with `await connection()` and `dynamicIO` it is still required that there is a Suspense boundary somewhere above the component that uses `await connection()`. If you do not have any Suspense boundary parent you will need to add one where is appropriate to describe a fallback UI.
### Useful Links
- [`headers` function](https://nextjs.org/docs/app/api-reference/functions/headers)
- [`cookies` function](https://nextjs.org/docs/app/api-reference/functions/cookies)
- [`draftMode` function](https://nextjs.org/docs/app/api-reference/functions/draft-mode)
- [`connection` function](https://nextjs.org/docs/app/api-reference/functions/connection)
- [`Suspense` React API](https://react.dev/reference/react/Suspense)
---
title: Cannot access Request information synchronously with Page or Layout or Route `params` or Page `searchParams`
---
#### Why This Error Occurred
In Next.js 15 `params` passed into Page and Layout components and `searchParams` passed into Page components are now Promises.
To support migrating to the async `params` and `searchParams` Next.js 15 still supports accessing param and searchParam values directly on the Promise object. However when `dynamicIO` is enabled it is an error to do so.
#### Possible Ways to Fix It
If you haven't already followed the Next.js 15 upgrade guide which includes running a codemod to auto-convert to the necessary async form of `params` and `searchParams` start there.
[Next 15 Upgrade Guide](https://nextjs.org/docs/app/building-your-application/upgrading/version-15#async-request-apis-breaking-change)
If you have already run the codemod on your project look for instances of the string `@next-codemod-error` to see where the codemod was unable to convert to the async form. You will have to refactor your code manually here to make it compatible with the new result type.
Before:
```jsx filename=".../some-file.js"
// This component ends up being the Page component even though it is defined outside of
// page.js due to how it is reexported in page.js
export default function ComponentThatWillBeExportedAsPage({ params, searchParams }) {
const { slug } = params;
const { page } = searchParams
return <RenderList slug={slug} page={page}>
}
```
```jsx filename="app/page.js"
// the codemod cannot find the actual Page component so the Page may still have remaining
// synchronous access to params and searchParams
// @next-codemod-error
export * from '.../some-file'
```
After:
```jsx filename=".../some-file.js"
// This component ends up being the Page component even though it is defined outside of
// page.js due to how it is reexported in page.js
export default async function ComponentThatWillBeExportedAsPage({ params, searchParams }) {
const { slug } = await params;
const { page } = await searchParams
return <RenderList slug={slug} page={page}>
}
```
```jsx filename="app/page.js"
export * from '.../some-file'
```
It is unexpected that you would run the codemod and not successfully convert all instances of `params` and `searchParams` to async or have a marker string to help you locate unconverted cases. If you do find yourself in this situation please report this to [Next.js on Github](https://github.com/vercel/next.js/issues).
- [`page.js` file convention](https://nextjs.org/docs/app/api-reference/file-conventions/page)
- [`layout.js` file convention](https://nextjs.org/docs/app/api-reference/file-conventions/layout)
- [`route.js` file convention](https://nextjs.org/docs/app/api-reference/file-conventions/route)
---
title: Cannot access Request information synchronously in route.js without awaiting connection first
---
#### Why This Error Occurred
When `dyanmicIO` is enabled Next.js treats most access to Request information as explicitly dynamic. However routes have a Request object and you can read values like the current pathname from that object synchronously. If you need to access Request information in a route handler you should first call `await connection()` to inform Next.js that everything after this point is explicitly dynamic.
This is only needed in `GET` handlers because `GET` is the only handler Next.js will attempt to prerender.
#### Possible Ways to Fix It
Look for access of the Request object in your route.js and add `await connection()` before you access any properties of the Request.
Before:
```jsx filename="app/.../route.js"
export default function GET(request) {
const requestHeaders = request.headers
return ...
}
```
After:
```jsx filename="app/.../route.js"
import { connection } from 'next/server'
export default async function GET(request) {
await connection()
const requestHeaders = request.headers
return ...
}
```
It is unexpected that you would run the codemod and not successfully convert all instances of `params` and `searchParams` to async or have a marker string to help you locate unconverted cases. If you do find yourself in this situation please report this to [Next.js on Github](https://github.com/vercel/next.js/issues).
- [`connection` function](https://nextjs.org/docs/app/api-reference/functions/connection)
- [`route.js` file convention](https://nextjs.org/docs/app/api-reference/file-conventions/route)
......@@ -2208,10 +2208,9 @@ async function prerenderToStream(
const componentStack: string | undefined = (errorInfo as any)
.componentStack
if (typeof componentStack === 'string' && err instanceof Error) {
if (typeof componentStack === 'string') {
trackAllowedDynamicAccess(
workStore.route,
err,
componentStack,
dynamicTracking
)
......@@ -2543,10 +2542,9 @@ async function prerenderToStream(
const componentStack: string | undefined = (errorInfo as any)
.componentStack
if (typeof componentStack === 'string' && err instanceof Error) {
if (typeof componentStack === 'string') {
trackAllowedDynamicAccess(
workStore.route,
err,
componentStack,
dynamicTracking
)
......
......@@ -3,52 +3,39 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
type DevCategories = 'time' | 'random' | 'crypto'
type ApiType = 'time' | 'random' | 'crypto'
export function io(expression: string, devAPICategory: DevCategories) {
export function io(expression: string, type: ApiType) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
if (workUnitStore.type === 'prerender') {
const workStore = workAsyncStorage.getStore()
if (workStore) {
let message: string
switch (type) {
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`
break
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`
break
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`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
const errorWithStack = new Error(message)
abortOnSynchronousPlatformIOAccess(
workStore.route,
expression,
errorWithStack,
workUnitStore
)
}
} else if (
process.env.NODE_ENV === 'development' &&
workUnitStore.type === 'request' &&
workUnitStore.environment === 'Prerender'
) {
const workStore = workAsyncStorage.getStore()
const route = workStore ? workStore.route : ''
switch (devAPICategory) {
case 'time': {
const errorToLog = new Error(
`Route "${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`
)
console.error(errorToLog)
break
}
case 'random': {
const errorToLog = new Error(
`Route ${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`
)
console.error(errorToLog)
break
}
case 'crypto': {
const errorToLog = new Error(
`Route ${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`
)
console.error(errorToLog)
break
}
default:
throw new InvariantError('Unknown devAPICategory in io function.')
}
}
}
}
......@@ -167,9 +167,11 @@ function makeDynamicallyTrackedExoticCookies(
[Symbol.iterator]: {
value: function () {
const expression = 'cookies()[Symbol.iterator]()'
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -177,9 +179,11 @@ function makeDynamicallyTrackedExoticCookies(
size: {
get() {
const expression = `cookies().size`
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -192,9 +196,11 @@ function makeDynamicallyTrackedExoticCookies(
} else {
expression = `cookies().get(${describeNameArg(arguments[0])})`
}
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -207,9 +213,11 @@ function makeDynamicallyTrackedExoticCookies(
} else {
expression = `cookies().getAll(${describeNameArg(arguments[0])})`
}
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -222,9 +230,11 @@ function makeDynamicallyTrackedExoticCookies(
} else {
expression = `cookies().has(${describeNameArg(arguments[0])})`
}
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -242,9 +252,11 @@ function makeDynamicallyTrackedExoticCookies(
expression = `cookies().set(...)`
}
}
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -259,9 +271,11 @@ function makeDynamicallyTrackedExoticCookies(
} else {
expression = `cookies().delete(${describeNameArg(arguments[0])}, ...)`
}
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -269,9 +283,11 @@ function makeDynamicallyTrackedExoticCookies(
clear: {
value: function clear() {
const expression = 'cookies().clear()'
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -279,9 +295,11 @@ function makeDynamicallyTrackedExoticCookies(
toString: {
value: function toString() {
const expression = 'cookies().toString()'
const error = createSyncCookiesError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -563,3 +581,9 @@ function polyfilledResponseCookiesClear(
type CookieExtensions = {
[K in keyof ReadonlyRequestCookies | 'clear']: unknown
}
function createSyncCookiesError(route: string, expression: string) {
return new Error(
`Route "${route}" used ${expression}. \`cookies()\` now returns a Promise and should be \`awaited\` before using it's value. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
)
}
......@@ -4,8 +4,13 @@ import type { DraftModeProvider } from '../async-storage/draft-mode-provider'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering'
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
} from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { DynamicServerError } from '../../client/components/hooks-server-context'
/**
* In this version of Next.js `draftMode()` returns a Promise however you can still reference the properties of the underlying draftMode object
......@@ -170,25 +175,15 @@ class DraftMode {
return false
}
public enable() {
const store = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (store) {
// We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
trackDynamicDataAccessed(store, workUnitStore, 'draftMode().enable()')
}
// We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
trackDynamicDraftMode('draftMode().enable()')
if (this._provider !== null) {
this._provider.enable()
}
}
public disable() {
const store = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (store) {
// We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
trackDynamicDataAccessed(store, workUnitStore, 'draftMode().disable()')
}
trackDynamicDraftMode('draftMode().disable()')
if (this._provider !== null) {
this._provider.disable()
}
......@@ -210,3 +205,68 @@ const warnForSyncAccess = process.env.__NEXT_DISABLE_SYNC_DYNAMIC_API_WARNINGS
`Learn more: https://nextjs.org/docs/messages/draft-mode-sync-access`
)
})
function trackDynamicDraftMode(expression: string) {
const store = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (store) {
// We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
}
if (store.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
if (workUnitStore) {
if (workUnitStore.type === 'prerender') {
// dynamicIO Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
)
abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
} else if (workUnitStore.type === 'prerender-ppr') {
// PPR Prerender
postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
// legacy Prerender
workUnitStore.revalidate = 0
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
} else if (
process.env.NODE_ENV === 'development' &&
workUnitStore &&
workUnitStore.type === 'request'
) {
workUnitStore.usedDynamic = true
}
}
}
}
......@@ -149,9 +149,11 @@ function makeDynamicallyTrackedExoticHeaders(
append: {
value: function append() {
const expression = `headers().append(${describeNameArg(arguments[0])}, ...)`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -159,9 +161,11 @@ function makeDynamicallyTrackedExoticHeaders(
delete: {
value: function _delete() {
const expression = `headers().delete(${describeNameArg(arguments[0])})`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -169,9 +173,11 @@ function makeDynamicallyTrackedExoticHeaders(
get: {
value: function get() {
const expression = `headers().get(${describeNameArg(arguments[0])})`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -179,9 +185,11 @@ function makeDynamicallyTrackedExoticHeaders(
has: {
value: function has() {
const expression = `headers().has(${describeNameArg(arguments[0])})`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -189,9 +197,11 @@ function makeDynamicallyTrackedExoticHeaders(
set: {
value: function set() {
const expression = `headers().set(${describeNameArg(arguments[0])}, ...)`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -199,9 +209,11 @@ function makeDynamicallyTrackedExoticHeaders(
getSetCookie: {
value: function getSetCookie() {
const expression = `headers().getSetCookie()`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -209,9 +221,11 @@ function makeDynamicallyTrackedExoticHeaders(
forEach: {
value: function forEach() {
const expression = `headers().forEach(...)`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -219,9 +233,11 @@ function makeDynamicallyTrackedExoticHeaders(
keys: {
value: function keys() {
const expression = `headers().keys()`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -229,9 +245,11 @@ function makeDynamicallyTrackedExoticHeaders(
values: {
value: function values() {
const expression = `headers().values()`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -239,9 +257,11 @@ function makeDynamicallyTrackedExoticHeaders(
entries: {
value: function entries() {
const expression = `headers().entries()`
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -249,9 +269,11 @@ function makeDynamicallyTrackedExoticHeaders(
[Symbol.iterator]: {
value: function () {
const expression = 'headers()[Symbol.iterator]()'
const error = createSyncHeadersError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -463,3 +485,9 @@ const warnForSyncAccess = process.env.__NEXT_DISABLE_SYNC_DYNAMIC_API_WARNINGS
type HeadersExtensions = {
[K in keyof ReadonlyHeaders]: unknown
}
function createSyncHeadersError(route: string, expression: string) {
return new Error(
`Route "${route}" used ${expression}. \`headers()\` now returns a Promise and should be \`awaited\` before using it's value. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
)
}
......@@ -208,9 +208,13 @@ function makeAbortingExoticParams(
Object.defineProperty(promise, prop, {
get() {
const expression = describeStringPropertyAccess('params', prop)
const error = new Error(
`Route "${route}" used ${expression}. \`params\` is now a Promise and should be \`awaited\` before accessing param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params`
)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......
......@@ -222,9 +222,11 @@ function makeAbortingExoticSearchParams(
'searchParams',
prop
)
const error = createSyncSearchParamsError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
}
......@@ -242,9 +244,11 @@ function makeAbortingExoticSearchParams(
'searchParams',
prop
)
const error = createSyncSearchParamsError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
}
......@@ -253,9 +257,11 @@ function makeAbortingExoticSearchParams(
ownKeys() {
const expression =
'`{...searchParams}`, `Object.keys(searchParams)`, or similar'
const error = createSyncSearchParamsError(route, expression)
abortAndThrowOnSynchronousRequestDataAccess(
route,
expression,
error,
prerenderStore
)
},
......@@ -725,3 +731,9 @@ function describeListOfPropertyNames(properties: Array<string>) {
}
}
}
function createSyncSearchParamsError(route: string, expression: string) {
return new Error(
`Route "${route}" used ${expression}. \`searchParams\` is now a Promise and should be \`awaited\` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params`
)
}
......@@ -5,6 +5,7 @@ import type { NextRequest } from '../../web/spec-extension/request'
import type { PrerenderManifest } from '../../../build'
import type { NextURL } from '../../web/next-url'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import type { WorkUnitStore } from '../../app-render/work-unit-async-storage.external'
import {
RouteModule,
......@@ -56,7 +57,8 @@ import { cleanURL } from './helpers/clean-url'
import { StaticGenBailoutError } from '../../../client/components/static-generation-bailout'
import { isStaticGenEnabled } from './helpers/is-static-gen-enabled'
import {
trackDynamicDataAccessed,
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
createDynamicTrackingState,
getFirstDynamicReason,
isPrerenderInterruptedError,
......@@ -928,7 +930,7 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) {
case 'toString':
case 'origin': {
const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataAccessed(workStore, workUnitStore, `nextUrl.${prop}`)
trackDynamic(workStore, workUnitStore, `nextUrl.${prop}`)
return ReflectAdapter.get(target, prop, receiver)
}
case 'clone':
......@@ -964,7 +966,7 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) {
case 'arrayBuffer':
case 'formData': {
const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataAccessed(workStore, workUnitStore, `request.${prop}`)
trackDynamic(workStore, workUnitStore, `request.${prop}`)
// The receiver arg is intentionally the same as the target to fix an issue with
// edge runtime, where attempting to access internal slots with the wrong `this` context
// results in an error.
......@@ -1085,3 +1087,66 @@ function createDynamicIOError(route: string) {
`Route ${route} couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/dynamic-io`
)
}
export function trackDynamic(
store: WorkStore,
workUnitStore: undefined | WorkUnitStore,
expression: string
): void {
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
}
if (store.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
if (workUnitStore) {
if (workUnitStore.type === 'prerender') {
// dynamicIO Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`
)
abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
} else if (workUnitStore.type === 'prerender-ppr') {
// PPR Prerender
postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
// legacy Prerender
workUnitStore.revalidate = 0
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
} else if (
process.env.NODE_ENV === 'development' &&
workUnitStore &&
workUnitStore.type === 'request'
) {
workUnitStore.usedDynamic = true
}
}
}
import { trackDynamicDataAccessed } from '../../app-render/dynamic-rendering'
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
} from '../../app-render/dynamic-rendering'
import { isDynamicRoute } from '../../../shared/lib/router/utils'
import {
NEXT_CACHE_IMPLICIT_TAG_ID,
......@@ -6,6 +9,7 @@ import {
} from '../../../lib/constants'
import { workAsyncStorage } from '../../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'
import { DynamicServerError } from '../../../client/components/hooks-server-context'
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
......@@ -65,11 +69,44 @@ function revalidate(tag: string, expression: string) {
`Route ${store.route} used "${expression}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
}
// a route that makes use of revalidation APIs should be considered dynamic
// as otherwise it would be impossible to revalidate
trackDynamicDataAccessed(store, workUnitStore, expression)
if (workUnitStore.type === 'prerender') {
// dynamicIO Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`.`
)
abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
} else if (workUnitStore.type === 'prerender-ppr') {
// PPR Prerender
postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
// legacy Prerender
workUnitStore.revalidate = 0
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
} else if (
process.env.NODE_ENV === 'development' &&
workUnitStore &&
workUnitStore.type === 'request'
) {
workUnitStore.usedDynamic = true
}
}
if (!store.revalidatedTags) {
store.revalidatedTags = []
......
import { nextTestSetup } from 'e2e-utils'
describe('dynamic-requests warnings', () => {
// I am temporarily deactivating these tests. We turned off the dev time warning but will reintroduce it when we add in dev-time prerendering.
// The tests will likely have to change but I'd like to keep the fixture and assertions as a starting point.
describe.skip('dynamic-requests warnings', () => {
const { next } = nextTestSetup({
files: __dirname,
})
......
import { nextTestSetup } from 'e2e-utils'
describe('Lazy Module Init', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname + '/fixtures/lazy-module-init',
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
it('does not run in dev', () => {})
return
}
it('should build statically even if module scope uses sync APIs like current time and random', async () => {
try {
await next.start()
} catch {
throw new Error('expected build not to fail for fully static project')
}
expect(next.cliOutput).toContain('○ / ')
const $ = await next.render$('/')
expect($('#id').text().length).toBeGreaterThan(0)
})
})
......@@ -123,23 +123,16 @@ function runTests(options: { withMinification: boolean }) {
}
const expectError = createExpectError(next.cliOutput)
if (WITH_PPR) {
expectError(
'Error: Route / used a synchronous Dynamic API: `Math.random()`. This particular component may have been dynamic anyway or it may have just not finished before the synchronous Dynamic API was invoked.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
} else {
expectError(
'Error: Route / used a synchronous Dynamic API: `Math.random()`, which caused this component to not finish rendering before the prerender completed and no fallback UI was defined.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
}
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / used `Math.random()` while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.'
'Error: Route "/" 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'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `Math.random()` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
})
})
......
......@@ -124,14 +124,15 @@ function runTests(options: { withMinification: boolean }) {
const expectError = createExpectError(next.cliOutput)
expectError(
'Error: Route / used a synchronous Dynamic API: `searchParams.foo`, which caused this component to not finish rendering before the prerender completed and no fallback UI was defined.',
'Error: Route "/" used `searchParams.foo`. `searchParams` is now a Promise and should be `awaited` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `searchParams.foo` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / used `searchParams.foo` while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.'
)
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
})
})
......@@ -217,23 +218,16 @@ function runTests(options: { withMinification: boolean }) {
}
const expectError = createExpectError(next.cliOutput)
if (WITH_PPR) {
expectError(
'Error: Route / used a synchronous Dynamic API: `searchParams.foo`. This particular component may have been dynamic anyway or it may have just not finished before the synchronous Dynamic API was invoked.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
} else {
expectError(
'Error: Route / used a synchronous Dynamic API: `searchParams.foo`, which caused this component to not finish rendering before the prerender completed and no fallback UI was defined.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
}
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / used `searchParams.foo` while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI.'
'Error: Route "/" used `searchParams.foo`. `searchParams` is now a Promise and should be `awaited` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `searchParams.foo` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
})
})
......@@ -319,23 +313,16 @@ function runTests(options: { withMinification: boolean }) {
}
const expectError = createExpectError(next.cliOutput)
if (WITH_PPR) {
expectError(
"Error: Route / used a synchronous Dynamic API: cookies().get('token'). This particular component may have been dynamic anyway or it may have just not finished before the synchronous Dynamic API was invoked.",
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
} else {
expectError(
"Error: Route / used a synchronous Dynamic API: cookies().get('token'), which caused this component to not finish rendering before the prerender completed and no fallback UI was defined.",
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
}
expectError('Error occurred prerendering page "/"')
expectError(
"Error: Route / used cookies().get('token') while prerendering which caused some part of the page to be dynamic without a Suspense boundary above it defining a fallback UI."
"Error: Route \"/\" used cookies().get('token'). `cookies()` now returns a Promise and should be `awaited` before using it's value. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers"
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where cookies().get(\'token\') was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"')
expectError('Route "/" could not be prerendered.')
expectError('exiting the build.')
})
})
......
......@@ -79,7 +79,7 @@ function runTests(options: { withMinification: boolean }) {
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / has a dynamic `generateMetadata` but nothing else is dynamic.'
'Error: Route "/" has a `generateMetadata` that depends on Request data (`cookies()`, etc...) or external data (`fetch(...)`, etc...) but the rest of the route was static or only used cached data (`"use cache"`). If you expected this route to be prerenderable update your `generateMetadata` to not use Request data and only use cached external data. Otherwise, add `await connection()` somewhere within this route to indicate explicitly it should not be prerendered.'
)
})
})
......@@ -120,7 +120,7 @@ function runTests(options: { withMinification: boolean }) {
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / has a dynamic `generateMetadata` but nothing else is dynamic.'
'Error: Route "/" has a `generateMetadata` that depends on Request data (`cookies()`, etc...) or external data (`fetch(...)`, etc...) but the rest of the route was static or only used cached data (`"use cache"`). If you expected this route to be prerenderable update your `generateMetadata` to not use Request data and only use cached external data. Otherwise, add `await connection()` somewhere within this route to indicate explicitly it should not be prerendered.'
)
})
})
......@@ -203,7 +203,7 @@ function runTests(options: { withMinification: boolean }) {
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / has a dynamic `generateViewport` but nothing else is dynamic.'
'Error: Route "/" has a `generateViewport` that depends on Request data (`cookies()`, etc...) or external data (`fetch(...)`, etc...) but the rest of the route was static or only used cached data (`"use cache"`). If you expected this route to be prerenderable update your `generateViewport` to not use Request data and only use cached external data. Otherwise, add `await connection()` somewhere within this route to indicate explicitly it should not be prerendered.'
)
})
})
......@@ -322,7 +322,7 @@ function runTests(options: { withMinification: boolean }) {
const expectError = createExpectError(next.cliOutput)
expectError(
'Error: Route / performed an IO operation that was not cached and no Suspense boundary was found to define a fallback UI.',
'In Route "/" this component accessed data without a fallback UI available somewhere above it using Suspense.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
......@@ -331,15 +331,13 @@ function runTests(options: { withMinification: boolean }) {
// one task actually reports and error at the moment. We should fix upstream but for now we exclude the second error when PPR is off
// because we are using canary React and renderToReadableStream rather than experimental React and prerender
expectError(
'Error: Route / performed an IO operation that was not cached and no Suspense boundary was found to define a fallback UI.',
'In Route "/" this component accessed data without a fallback UI available somewhere above it using Suspense.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionThree'
)
}
expectError('Error occurred prerendering page "/"')
expectError(
'Error: Route / has one or more dynamic components without a defined fallback UI.'
)
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
})
})
......
export async function BuildID() {
console.log('=== RENDER BUILD ID')
const buildID = require('./lazy-id').buildID
await 1
return (
<dl>
<dt>Build ID</dt>
<dd id="id">{buildID}</dd>
</dl>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
import { BuildID } from './build-id'
export default async function Page() {
return (
<>
<p>
This page requires a module lazily during rendering. The Module computes
a "static" id using the current time and a random number. If these APIs
are used while prerendering they would normally trigger a synchronous
dynamic bailout. However since these APIs are used in module scope they
are not semantically part of the render and should be usable like other
"static" values. We demonstrate this with this fixture by asserting that
this page still produces a static result and it does not warn for
reading current time and random in a prerender.
</p>
<BuildID />
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
dynamicIO: true,
serverMinification: true,
},
}
module.exports = 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