Unverified Commit 1dda5b66 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[Breaking] Remove deprecated sync access to Dynamic APIs (#84179)

This PR removes the deprecated sync access to Dynamic APIs.

- Removed UnsafeUnwrapped* types.
- Replaced `as unknown as UnsafeUnwrapped ` type casts to `as any` for
dev warning.
- Removed tests that expected sync access to not error.
- Removed `UntrackedExotic` functions.
- Modified tests that were accidentally doing sync access.
- Updated warnings to emphasize that it is a Promise and must be
awaited.
- Removed paragraph that states access is allowed from
`errors/sync-dynamic-apis.mdx`.

---------
Co-authored-by: 's avatarJosh Story <story@hey.com>
parent bc14f192
...@@ -26,9 +26,6 @@ function Page({ params }) { ...@@ -26,9 +26,6 @@ function Page({ params }) {
This also includes enumerating (e.g. `{...params}`, or `Object.keys(params)`) or iterating over the return This also includes enumerating (e.g. `{...params}`, or `Object.keys(params)`) or iterating over the return
value of these APIs (e.g. `[...headers()]` or `for (const cookie of cookies())`, or explicitly with `cookies()[Symbol.iterator]()`). value of these APIs (e.g. `[...headers()]` or `for (const cookie of cookies())`, or explicitly with `cookies()[Symbol.iterator]()`).
In the version of Next.js that issued this warning, access to these properties is still possible directly but will warn.
In future versions, these APIs will be async and direct access will not work as expected.
## Possible Ways to Fix It ## Possible Ways to Fix It
The [`next-async-request-api` codemod](/docs/app/guides/upgrading/codemods#next-async-request-api) can fix many of these cases automatically: The [`next-async-request-api` codemod](/docs/app/guides/upgrading/codemods#next-async-request-api) can fix many of these cases automatically:
......
...@@ -824,5 +824,28 @@ ...@@ -824,5 +824,28 @@
"823": "Timeout waiting for error state from frontend. The browser may not be responding to HMR messages.", "823": "Timeout waiting for error state from frontend. The browser may not be responding to HMR messages.",
"824": "URL is required in MCP browser response. This is a bug in Next.js.", "824": "URL is required in MCP browser response. This is a bug in Next.js.",
"825": "Timeout waiting for response from frontend. The browser may not be responding to HMR messages.", "825": "Timeout waiting for response from frontend. The browser may not be responding to HMR messages.",
"826": "unknown bundler: %s" "826": "unknown bundler: %s",
"827": "Route %s used \\`connection()\\` inside \\`after()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after",
"828": "Route %s with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"829": "Route %s used \"%s\" 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",
"830": "%sused %s. \\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis",
"831": "Route %s used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` 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",
"832": "%s must not be used within a Client Component. Next.js should be preventing %s from being included in Client Components statically, but did not in this case.",
"833": "Route %s used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` 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",
"834": "%sused %s. \\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis",
"835": "%sused %s. \\`draftMode()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis",
"836": "%sused %s. \\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis",
"837": "Route %s used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"838": "Route %s used \\`headers()\\` 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 \\`headers()\\` 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",
"839": "Route %s used \\`headers()\\` inside \\`after()\\`. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after",
"840": "Route %s used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"841": "Route %s used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"842": "Route %s used \\`searchParams\\` inside \"use cache\". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \\`searchParams\\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"843": "Route %s used \\`cookies()\\` inside \\`after()\\`. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after",
"844": "Route %s used \"%s\" 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",
"845": "Route %s used \"%s\" inside \\`after()\\`. The enabled status of \\`draftMode()\\` can be read inside \\`after()\\` but you cannot enable or disable \\`draftMode()\\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"846": "Route %s used \\`cookies()\\` 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 \\`cookies()\\` 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",
"847": "Route %s with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"848": "%sused %s. \\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis",
"849": "Route %s with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering"
} }
...@@ -16,5 +16,3 @@ export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types' ...@@ -16,5 +16,3 @@ export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types'
export { after } from 'next/dist/server/after' export { after } from 'next/dist/server/after'
export { unstable_rootParams } from 'next/dist/server/request/root-params' export { unstable_rootParams } from 'next/dist/server/request/root-params'
export { connection } from 'next/dist/server/request/connection' export { connection } from 'next/dist/server/request/connection'
export type { UnsafeUnwrappedSearchParams } from 'next/dist/server/request/search-params'
export type { UnsafeUnwrappedParams } from 'next/dist/server/request/params'
...@@ -423,8 +423,6 @@ function createServerDefinitions( ...@@ -423,8 +423,6 @@ function createServerDefinitions(
export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types' export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types'
export { after } from 'next/dist/server/after' export { after } from 'next/dist/server/after'
export { connection } from 'next/dist/server/request/connection' export { connection } from 'next/dist/server/request/connection'
export type { UnsafeUnwrappedSearchParams } from 'next/dist/server/request/search-params'
export type { UnsafeUnwrappedParams } from 'next/dist/server/request/params'
export function unstable_rootParams(): Promise<{ ${rootParams export function unstable_rootParams(): Promise<{ ${rootParams
.map( .map(
({ param, optional }) => ({ param, optional }) =>
......
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { ReflectAdapter } from '../../server/web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../../server/web/spec-extension/adapters/reflect'
import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
describeStringPropertyAccess, describeStringPropertyAccess,
wellKnownProperties, wellKnownProperties,
...@@ -10,63 +9,6 @@ import { ...@@ -10,63 +9,6 @@ import {
interface CacheLifetime {} interface CacheLifetime {}
const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>() const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()
function makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams: Params
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
// We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(underlyingParams)
const proxiedProperties = new Set<string>()
const unproxiedProperties: Array<string> = []
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
proxiedProperties.add(prop)
;(promise as any)[prop] = underlyingParams[prop]
}
})
const proxiedPromise = new Proxy(promise, {
get(target, prop, receiver) {
if (typeof prop === 'string') {
if (
// We are accessing a property that was proxied to the promise instance
proxiedProperties.has(prop)
) {
const expression = describeStringPropertyAccess('params', prop)
warnForSyncAccess(expression)
}
}
return ReflectAdapter.get(target, prop, receiver)
},
set(target, prop, value, receiver) {
if (typeof prop === 'string') {
proxiedProperties.delete(prop)
}
return ReflectAdapter.set(target, prop, value, receiver)
},
ownKeys(target) {
warnForEnumeration(unproxiedProperties)
return Reflect.ownKeys(target)
},
})
CachedParams.set(underlyingParams, proxiedPromise)
return proxiedPromise
}
// Similar to `makeDynamicallyTrackedExoticParamsWithDevWarnings`, but just
// logging the sync access without actually defining the params on the promise.
function makeDynamicallyTrackedParamsWithDevWarnings( function makeDynamicallyTrackedParamsWithDevWarnings(
underlyingParams: Params underlyingParams: Params
): Promise<Params> { ): Promise<Params> {
...@@ -81,7 +23,6 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -81,7 +23,6 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
const promise = Promise.resolve(underlyingParams) const promise = Promise.resolve(underlyingParams)
const proxiedProperties = new Set<string>() const proxiedProperties = new Set<string>()
const unproxiedProperties: Array<string> = []
Object.keys(underlyingParams).forEach((prop) => { Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) { if (wellKnownProperties.has(prop)) {
...@@ -112,7 +53,7 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -112,7 +53,7 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
return ReflectAdapter.set(target, prop, value, receiver) return ReflectAdapter.set(target, prop, value, receiver)
}, },
ownKeys(target) { ownKeys(target) {
warnForEnumeration(unproxiedProperties) warnForEnumeration()
return Reflect.ownKeys(target) return Reflect.ownKeys(target)
}, },
}) })
...@@ -123,55 +64,22 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -123,55 +64,22 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
function warnForSyncAccess(expression: string) { function warnForSyncAccess(expression: string) {
console.error( console.error(
`A param property was accessed directly with ${expression}. \`params\` is now a Promise and should be unwrapped with \`React.use()\` before accessing properties of the underlying params object. In this version of Next.js direct access to param properties is still supported to facilitate migration but in a future version you will be required to unwrap \`params\` with \`React.use()\`.` `A param property was accessed directly with ${expression}. ` +
`\`params\` is a Promise and must be unwrapped with \`React.use()\` before accessing its properties. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
) )
} }
function warnForEnumeration(missingProperties: Array<string>) { function warnForEnumeration() {
if (missingProperties.length) { console.error(
const describedMissingProperties = `params are being enumerated. ` +
describeListOfPropertyNames(missingProperties) `\`params\` is a Promise and must be unwrapped with \`React.use()\` before accessing its properties. ` +
console.error( `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
`params are being enumerated incompletely missing these properties: ${describedMissingProperties}. ` + )
`\`params\` should be unwrapped with \`React.use()\` before using its value. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
)
} else {
console.error(
`params are being enumerated. ` +
`\`params\` should be unwrapped with \`React.use()\` before using its value. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
)
}
}
function describeListOfPropertyNames(properties: Array<string>) {
switch (properties.length) {
case 0:
throw new InvariantError(
'Expected describeListOfPropertyNames to be called with a non-empty list of strings.'
)
case 1:
return `\`${properties[0]}\``
case 2:
return `\`${properties[0]}\` and \`${properties[1]}\``
default: {
let description = ''
for (let i = 0; i < properties.length - 1; i++) {
description += `\`${properties[i]}\`, `
}
description += `, and \`${properties[properties.length - 1]}\``
return description
}
}
} }
export function createRenderParamsFromClient( export function createRenderParamsFromClient(
clientParams: Params clientParams: Params
): Promise<Params> { ): Promise<Params> {
if (process.env.__NEXT_CACHE_COMPONENTS) { return makeDynamicallyTrackedParamsWithDevWarnings(clientParams)
return makeDynamicallyTrackedParamsWithDevWarnings(clientParams)
}
return makeDynamicallyTrackedExoticParamsWithDevWarnings(clientParams)
} }
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {} interface CacheLifetime {}
const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>() const CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()
function makeUntrackedExoticParams(underlyingParams: Params): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
const promise = Promise.resolve(underlyingParams)
CachedParams.set(underlyingParams, promise)
Object.keys(underlyingParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
;(promise as any)[prop] = underlyingParams[prop]
}
})
return promise
}
function makeUntrackedParams(underlyingParams: Params): Promise<Params> { function makeUntrackedParams(underlyingParams: Params): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams) const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) { if (cachedParams) {
...@@ -40,9 +18,5 @@ function makeUntrackedParams(underlyingParams: Params): Promise<Params> { ...@@ -40,9 +18,5 @@ function makeUntrackedParams(underlyingParams: Params): Promise<Params> {
export function createRenderParamsFromClient( export function createRenderParamsFromClient(
clientParams: Params clientParams: Params
): Promise<Params> { ): Promise<Params> {
if (process.env.__NEXT_CACHE_COMPONENTS) { return makeUntrackedParams(clientParams)
return makeUntrackedParams(clientParams)
}
return makeUntrackedExoticParams(clientParams)
} }
...@@ -10,82 +10,6 @@ import { ...@@ -10,82 +10,6 @@ import {
interface CacheLifetime {} interface CacheLifetime {}
const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>() const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()
function makeUntrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
return cachedSearchParams
}
const proxiedProperties = new Set<string>()
const unproxiedProperties: Array<string> = []
const promise = Promise.resolve(underlyingSearchParams)
Object.keys(underlyingSearchParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
unproxiedProperties.push(prop)
} else {
proxiedProperties.add(prop)
;(promise as any)[prop] = underlyingSearchParams[prop]
}
})
const proxiedPromise = new Proxy(promise, {
get(target, prop, receiver) {
if (typeof prop === 'string') {
if (
!wellKnownProperties.has(prop) &&
(proxiedProperties.has(prop) ||
// We are accessing a property that doesn't exist on the promise nor
// the underlying searchParams.
Reflect.has(target, prop) === false)
) {
const expression = describeStringPropertyAccess('searchParams', prop)
warnForSyncAccess(expression)
}
}
return ReflectAdapter.get(target, prop, receiver)
},
set(target, prop, value, receiver) {
if (typeof prop === 'string') {
proxiedProperties.delete(prop)
}
return Reflect.set(target, prop, value, receiver)
},
has(target, prop) {
if (typeof prop === 'string') {
if (
!wellKnownProperties.has(prop) &&
(proxiedProperties.has(prop) ||
// We are accessing a property that doesn't exist on the promise nor
// the underlying searchParams.
Reflect.has(target, prop) === false)
) {
const expression = describeHasCheckingStringProperty(
'searchParams',
prop
)
warnForSyncAccess(expression)
}
}
return Reflect.has(target, prop)
},
ownKeys(target) {
warnForSyncSpread()
return Reflect.ownKeys(target)
},
})
CachedSearchParams.set(underlyingSearchParams, proxiedPromise)
return proxiedPromise
}
// Similar to `makeUntrackedExoticSearchParamsWithDevWarnings`, but just logging
// the sync access without actually defining the search params on the promise.
function makeUntrackedSearchParamsWithDevWarnings( function makeUntrackedSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams underlyingSearchParams: SearchParams
): Promise<SearchParams> { ): Promise<SearchParams> {
...@@ -95,14 +19,12 @@ function makeUntrackedSearchParamsWithDevWarnings( ...@@ -95,14 +19,12 @@ function makeUntrackedSearchParamsWithDevWarnings(
} }
const proxiedProperties = new Set<string>() const proxiedProperties = new Set<string>()
const unproxiedProperties: Array<string> = []
const promise = Promise.resolve(underlyingSearchParams) const promise = Promise.resolve(underlyingSearchParams)
Object.keys(underlyingSearchParams).forEach((prop) => { Object.keys(underlyingSearchParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) { if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the // These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime // true underlying value for Promises to work correctly at runtime
unproxiedProperties.push(prop)
} else { } else {
proxiedProperties.add(prop) proxiedProperties.add(prop)
} }
...@@ -161,7 +83,7 @@ function makeUntrackedSearchParamsWithDevWarnings( ...@@ -161,7 +83,7 @@ function makeUntrackedSearchParamsWithDevWarnings(
function warnForSyncAccess(expression: string) { function warnForSyncAccess(expression: string) {
console.error( console.error(
`A searchParam property was accessed directly with ${expression}. ` + `A searchParam property was accessed directly with ${expression}. ` +
`\`searchParams\` should be unwrapped with \`React.use()\` before accessing its properties. ` + `\`searchParams\` is a Promise and must be unwrapped with \`React.use()\` before accessing its properties. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis` `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
) )
} }
...@@ -169,7 +91,7 @@ function warnForSyncAccess(expression: string) { ...@@ -169,7 +91,7 @@ function warnForSyncAccess(expression: string) {
function warnForSyncSpread() { function warnForSyncSpread() {
console.error( console.error(
`The keys of \`searchParams\` were accessed directly. ` + `The keys of \`searchParams\` were accessed directly. ` +
`\`searchParams\` should be unwrapped with \`React.use()\` before accessing its properties. ` + `\`searchParams\` is a Promise and must be unwrapped with \`React.use()\` before accessing its properties. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis` `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
) )
} }
...@@ -177,9 +99,5 @@ function warnForSyncSpread() { ...@@ -177,9 +99,5 @@ function warnForSyncSpread() {
export function createRenderSearchParamsFromClient( export function createRenderSearchParamsFromClient(
underlyingSearchParams: SearchParams underlyingSearchParams: SearchParams
): Promise<SearchParams> { ): Promise<SearchParams> {
if (process.env.__NEXT_CACHE_COMPONENTS) { return makeUntrackedSearchParamsWithDevWarnings(underlyingSearchParams)
return makeUntrackedSearchParamsWithDevWarnings(underlyingSearchParams)
}
return makeUntrackedExoticSearchParamsWithDevWarnings(underlyingSearchParams)
} }
import type { SearchParams } from '../../server/request/search-params' import type { SearchParams } from '../../server/request/search-params'
import { wellKnownProperties } from '../../shared/lib/utils/reflect-utils'
interface CacheLifetime {} interface CacheLifetime {}
const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>() const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()
function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
return cachedSearchParams
}
// We don't use makeResolvedReactPromise here because searchParams
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(underlyingSearchParams)
CachedSearchParams.set(underlyingSearchParams, promise)
Object.keys(underlyingSearchParams).forEach((prop) => {
if (wellKnownProperties.has(prop)) {
// These properties cannot be shadowed because they need to be the
// true underlying value for Promises to work correctly at runtime
} else {
;(promise as any)[prop] = underlyingSearchParams[prop]
}
})
return promise
}
function makeUntrackedSearchParams( function makeUntrackedSearchParams(
underlyingSearchParams: SearchParams underlyingSearchParams: SearchParams
): Promise<SearchParams> { ): Promise<SearchParams> {
...@@ -48,9 +20,5 @@ function makeUntrackedSearchParams( ...@@ -48,9 +20,5 @@ function makeUntrackedSearchParams(
export function createRenderSearchParamsFromClient( export function createRenderSearchParamsFromClient(
underlyingSearchParams: SearchParams underlyingSearchParams: SearchParams
): Promise<SearchParams> { ): Promise<SearchParams> {
if (process.env.__NEXT_CACHE_COMPONENTS) { return makeUntrackedSearchParams(underlyingSearchParams)
return makeUntrackedSearchParams(underlyingSearchParams)
}
return makeUntrackedExoticSearchParams(underlyingSearchParams)
} }
...@@ -342,10 +342,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess( ...@@ -342,10 +342,6 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
) )
} }
// For now these implementations are the same so we just reexport
export const trackSynchronousRequestDataAccessInDev =
trackSynchronousPlatformIOAccessInDev
/** /**
* This component will call `React.postpone` that throws the postponed error. * This component will call `React.postpone` that throws the postponed error.
*/ */
......
...@@ -32,7 +32,7 @@ export function connection(): Promise<void> { ...@@ -32,7 +32,7 @@ export function connection(): Promise<void> {
!isRequestAPICallableInsideAfter() !isRequestAPICallableInsideAfter()
) { ) {
throw new Error( throw new Error(
`Route ${workStore.route} used "connection" inside "after(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but "after(...)" executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after` `Route ${workStore.route} used \`connection()\` inside \`after()\`. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after`
) )
} }
...@@ -44,7 +44,7 @@ export function connection(): Promise<void> { ...@@ -44,7 +44,7 @@ export function connection(): Promise<void> {
if (workStore.dynamicShouldError) { if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError( throw new StaticGenBailoutError(
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
) )
} }
...@@ -52,7 +52,7 @@ export function connection(): Promise<void> { ...@@ -52,7 +52,7 @@ export function connection(): Promise<void> {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': { case 'cache': {
const error = new Error( const error = new Error(
`Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used \`connection()\` inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
Error.captureStackTrace(error, connection) Error.captureStackTrace(error, connection)
workStore.invalidDynamicUsageError ??= error workStore.invalidDynamicUsageError ??= error
...@@ -63,7 +63,7 @@ export function connection(): Promise<void> { ...@@ -63,7 +63,7 @@ export function connection(): Promise<void> {
// we don't consider runtime prefetches as "actual requests" (in the // we don't consider runtime prefetches as "actual requests" (in the
// navigation sense), despite allowing them to read cookies. // navigation sense), despite allowing them to read cookies.
const error = new Error( const error = new Error(
`Route ${workStore.route} used "connection" inside "use cache: private". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used \`connection()\` inside "use cache: private". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
Error.captureStackTrace(error, connection) Error.captureStackTrace(error, connection)
workStore.invalidDynamicUsageError ??= error workStore.invalidDynamicUsageError ??= error
...@@ -71,7 +71,7 @@ export function connection(): Promise<void> { ...@@ -71,7 +71,7 @@ export function connection(): Promise<void> {
} }
case 'unstable-cache': case 'unstable-cache':
throw new Error( throw new Error(
`Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${workStore.route} used \`connection()\` inside a function cached with \`unstable_cache()\`. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
) )
case 'prerender': case 'prerender':
case 'prerender-client': case 'prerender-client':
......
This diff is collapsed.
...@@ -15,7 +15,6 @@ import { ...@@ -15,7 +15,6 @@ import {
delayUntilRuntimeStage, delayUntilRuntimeStage,
postponeWithTracking, postponeWithTracking,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
...@@ -23,29 +22,6 @@ import { DynamicServerError } from '../../client/components/hooks-server-context ...@@ -23,29 +22,6 @@ import { DynamicServerError } from '../../client/components/hooks-server-context
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
/**
* In this version of Next.js `draftMode()` returns a Promise however you can still reference the properties of the underlying draftMode object
* synchronously to facilitate migration. The `UnsafeUnwrappedDraftMode` type is added to your code by a codemod that attempts to automatically
* updates callsites to reflect the new Promise return type. There are some cases where `draftMode()` cannot be automatically converted, namely
* when it is used inside a synchronous function and we can't be sure the function can be made async automatically. In these cases we add an
* explicit type case to `UnsafeUnwrappedDraftMode` to enable typescript to allow for the synchronous usage only where it is actually necessary.
*
* You should should update these callsites to either be async functions where the `draftMode()` value can be awaited or you should call `draftMode()`
* from outside and await the return value before passing it into this function.
*
* You can find instances that require manual migration by searching for `UnsafeUnwrappedDraftMode` in your codebase or by search for a comment that
* starts with `@next-codemod-error`.
*
* In a future version of Next.js `draftMode()` will only return a Promise and you will not be able to access the underlying draftMode object directly
* without awaiting the return value first. When this change happens the type `UnsafeUnwrappedDraftMode` will be updated to reflect that is it no longer
* usable.
*
* This type is marked deprecated to help identify it as target for refactoring away.
*
* @deprecated
*/
export type UnsafeUnwrappedDraftMode = DraftMode
export function draftMode(): Promise<DraftMode> { export function draftMode(): Promise<DraftMode> {
const callingExpression = 'draftMode' const callingExpression = 'draftMode'
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
...@@ -105,90 +81,18 @@ function createOrGetCachedDraftMode( ...@@ -105,90 +81,18 @@ function createOrGetCachedDraftMode(
return cachedDraftMode return cachedDraftMode
} }
let promise: Promise<DraftMode>
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) { if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
const route = workStore?.route const route = workStore?.route
return createDraftModeWithDevWarnings(draftModeProvider, route)
if (process.env.__NEXT_CACHE_COMPONENTS) {
return createDraftModeWithDevWarnings(draftModeProvider, route)
}
promise = createExoticDraftModeWithDevWarnings(draftModeProvider, route)
} else { } else {
if (process.env.__NEXT_CACHE_COMPONENTS) { return Promise.resolve(new DraftMode(draftModeProvider))
return Promise.resolve(new DraftMode(draftModeProvider))
}
promise = createExoticDraftMode(draftModeProvider)
} }
CachedDraftModes.set(cacheKey, promise)
return promise
} }
interface CacheLifetime {} interface CacheLifetime {}
const NullDraftMode = {} const NullDraftMode = {}
const CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>() const CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()
function createExoticDraftMode(
underlyingProvider: null | DraftModeProvider
): Promise<DraftMode> {
const instance = new DraftMode(underlyingProvider)
const promise = Promise.resolve(instance)
Object.defineProperty(promise, 'isEnabled', {
get() {
return instance.isEnabled
},
enumerable: true,
configurable: true,
})
;(promise as any).enable = instance.enable.bind(instance)
;(promise as any).disable = instance.disable.bind(instance)
return promise
}
function createExoticDraftModeWithDevWarnings(
underlyingProvider: null | DraftModeProvider,
route: undefined | string
): Promise<DraftMode> {
const instance = new DraftMode(underlyingProvider)
const promise = Promise.resolve(instance)
Object.defineProperty(promise, 'isEnabled', {
get() {
const expression = '`draftMode().isEnabled`'
syncIODev(route, expression)
return instance.isEnabled
},
enumerable: true,
configurable: true,
})
Object.defineProperty(promise, 'enable', {
value: function get() {
const expression = '`draftMode().enable()`'
syncIODev(route, expression)
return instance.enable.apply(instance, arguments as any)
},
})
Object.defineProperty(promise, 'disable', {
value: function get() {
const expression = '`draftMode().disable()`'
syncIODev(route, expression)
return instance.disable.apply(instance, arguments as any)
},
})
return promise
}
// Similar to `createExoticDraftModeWithDevWarnings`, but just logging the sync
// access without actually defining the draftMode properties on the promise.
function createDraftModeWithDevWarnings( function createDraftModeWithDevWarnings(
underlyingProvider: null | DraftModeProvider, underlyingProvider: null | DraftModeProvider,
route: undefined | string route: undefined | string
...@@ -249,37 +153,6 @@ class DraftMode { ...@@ -249,37 +153,6 @@ class DraftMode {
} }
} }
} }
function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev, we need to advance out of
// the Prerender environment when we read Request data synchronously.
trackSynchronousRequestDataAccessInDev(workUnitStore)
}
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// In all cases we warn normally
warnForSyncAccess(route, expression)
}
const warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev( const warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(
createDraftModeAccessError createDraftModeAccessError
) )
...@@ -291,7 +164,7 @@ function createDraftModeAccessError( ...@@ -291,7 +164,7 @@ function createDraftModeAccessError(
const prefix = route ? `Route "${route}" ` : 'This route ' const prefix = route ? `Route "${route}" ` : 'This route '
return new Error( return new Error(
`${prefix}used ${expression}. ` + `${prefix}used ${expression}. ` +
`\`draftMode()\` should be awaited before using its value. ` + `\`draftMode()\` returns a Promise and must be unwrapped with \`await\` or \`React.use()\` before accessing its properties. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis` `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
) )
} }
...@@ -305,7 +178,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -305,7 +178,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
// don't statically generate routes that manipulate draft mode. // don't statically generate routes that manipulate draft mode.
if (workUnitStore?.phase === 'after') { if (workUnitStore?.phase === 'after') {
throw new Error( throw new Error(
`Route ${workStore.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after` `Route ${workStore.route} used "${expression}" inside \`after()\`. The enabled status of \`draftMode()\` can be read inside \`after()\` but you cannot enable or disable \`draftMode()\`. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
) )
} }
...@@ -320,7 +193,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -320,7 +193,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
case 'cache': case 'cache':
case 'private-cache': { case 'private-cache': {
const error = new Error( const error = new Error(
`Route ${workStore.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` `Route ${workStore.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`
) )
Error.captureStackTrace(error, constructorOpt) Error.captureStackTrace(error, constructorOpt)
workStore.invalidDynamicUsageError ??= error workStore.invalidDynamicUsageError ??= error
...@@ -328,7 +201,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -328,7 +201,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
} }
case 'unstable-cache': case 'unstable-cache':
throw new Error( throw new Error(
`Route ${workStore.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` `Route ${workStore.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`
) )
case 'prerender': case 'prerender':
...@@ -346,7 +219,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) { ...@@ -346,7 +219,7 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
case 'prerender-client': case 'prerender-client':
const exportName = '`draftMode`' const exportName = '`draftMode`'
throw new InvariantError( throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.` `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
) )
case 'prerender-ppr': case 'prerender-ppr':
return postponeWithTracking( return postponeWithTracking(
......
This diff is collapsed.
This diff is collapsed.
...@@ -2,15 +2,6 @@ import { StaticGenBailoutError } from '../../client/components/static-generation ...@@ -2,15 +2,6 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external' import { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external'
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
export function throwWithStaticGenerationBailoutError(
route: string,
expression: string
): never {
throw new StaticGenBailoutError(
`Route ${route} 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`
)
}
export function throwWithStaticGenerationBailoutErrorWithDynamicError( export function throwWithStaticGenerationBailoutErrorWithDynamicError(
route: string, route: string,
expression: string expression: string
...@@ -25,7 +16,7 @@ export function throwForSearchParamsAccessInUseCache( ...@@ -25,7 +16,7 @@ export function throwForSearchParamsAccessInUseCache(
constructorOpt: Function constructorOpt: Function
): never { ): never {
const error = new Error( const error = new Error(
`Route ${workStore.route} used "searchParams" inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await "searchParams" outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
Error.captureStackTrace(error, constructorOpt) Error.captureStackTrace(error, constructorOpt)
......
import { cookies, type UnsafeUnwrappedCookies } from 'next/headers' import { cookies } from 'next/headers'
function Component() { function Component() {
;(cookies() as unknown as UnsafeUnwrappedCookies).get('component') // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
;(cookies() as unknown as UnsafeUnwrappedCookies).has('component') ;(cookies() as any).get('component')
;(cookies() as any).has('component')
const allCookies = [...(cookies() as unknown as UnsafeUnwrappedCookies)] const allCookies = [...(cookies() as any)]
return <pre>{JSON.stringify(allCookies, null, 2)}</pre> return <pre>{JSON.stringify(allCookies, null, 2)}</pre>
} }
export default function Page() { export default function Page() {
;(cookies() as unknown as UnsafeUnwrappedCookies).get('page') ;(cookies() as any).get('page')
return ( return (
<> <>
<Component /> <Component />
......
import { draftMode, type UnsafeUnwrappedDraftMode } from 'next/headers' import { draftMode } from 'next/headers'
function Component() { function Component() {
const isEnabled = (draftMode() as unknown as UnsafeUnwrappedDraftMode) // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
.isEnabled const isEnabled = (draftMode() as any).isEnabled
;(draftMode() as unknown as UnsafeUnwrappedDraftMode).enable() ;(draftMode() as any).enable()
const clonedDraftMode = { const clonedDraftMode = {
...(draftMode() as unknown as UnsafeUnwrappedDraftMode), ...(draftMode() as any),
} }
return <pre>{JSON.stringify({ clonedDraftMode, isEnabled }, null, 2)}</pre> return <pre>{JSON.stringify({ clonedDraftMode, isEnabled }, null, 2)}</pre>
} }
export default function Page() { export default function Page() {
const isEnabled = (draftMode() as unknown as UnsafeUnwrappedDraftMode) const isEnabled = (draftMode() as any).isEnabled
.isEnabled
return ( return (
<> <>
<pre>{JSON.stringify({ isEnabled }, null, 2)}</pre> <pre>{JSON.stringify({ isEnabled }, null, 2)}</pre>
......
import { headers, type UnsafeUnwrappedHeaders } from 'next/headers' import { headers } from 'next/headers'
function Component() { function Component() {
;(headers() as unknown as UnsafeUnwrappedHeaders).get('component') // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
;(headers() as unknown as UnsafeUnwrappedHeaders).has('component') ;(headers() as any).get('component')
;(headers() as any).has('component')
const allHeaders = [...(headers() as unknown as UnsafeUnwrappedHeaders)] const allHeaders = [...(headers() as any)]
return <pre>{JSON.stringify(allHeaders, null, 2)}</pre> return <pre>{JSON.stringify(allHeaders, null, 2)}</pre>
} }
export default function Page() { export default function Page() {
;(headers() as unknown as UnsafeUnwrappedHeaders).get('page') ;(headers() as any).get('page')
return ( return (
<> <>
<Component /> <Component />
......
...@@ -19,18 +19,8 @@ describe('dynamic-requests warnings', () => { ...@@ -19,18 +19,8 @@ describe('dynamic-requests warnings', () => {
return line.includes('Route "/request/cookies') return line.includes('Route "/request/cookies')
}) })
expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({ expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({
browserConsoleWarnings: [ browserConsoleWarnings: [expect.stringContaining('`cookies().get`.')],
expect.stringContaining("`cookies().get('page')`."), terminalCookieErrors: [expect.stringContaining('`cookies().get`.')],
expect.stringContaining("`cookies().get('component')`."),
expect.stringContaining("`cookies().has('component')`."),
expect.stringContaining('`...cookies()` or similar iteration'),
],
terminalCookieErrors: [
expect.stringContaining("`cookies().get('page')`."),
expect.stringContaining("`cookies().get('component')`."),
expect.stringContaining("`cookies().has('component')`."),
expect.stringContaining('`...cookies()` or similar iteration'),
],
}) })
}) })
...@@ -50,15 +40,9 @@ describe('dynamic-requests warnings', () => { ...@@ -50,15 +40,9 @@ describe('dynamic-requests warnings', () => {
expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({ expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({
browserConsoleWarnings: [ browserConsoleWarnings: [
expect.stringContaining('`draftMode().isEnabled`.'), expect.stringContaining('`draftMode().isEnabled`.'),
expect.stringContaining('`draftMode().isEnabled`.'),
expect.stringContaining('`draftMode().enable()`.'),
expect.stringContaining('`draftMode().isEnabled`.'),
], ],
terminalCookieErrors: [ terminalCookieErrors: [
expect.stringContaining('`draftMode().isEnabled`.'), expect.stringContaining('`draftMode().isEnabled`.'),
expect.stringContaining('`draftMode().isEnabled`.'),
expect.stringContaining('`draftMode().enable()`.'),
expect.stringContaining('`draftMode().isEnabled`.'),
], ],
}) })
}) })
...@@ -77,18 +61,8 @@ describe('dynamic-requests warnings', () => { ...@@ -77,18 +61,8 @@ describe('dynamic-requests warnings', () => {
return line.includes('Route "/request/headers') return line.includes('Route "/request/headers')
}) })
expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({ expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({
browserConsoleWarnings: [ browserConsoleWarnings: [expect.stringContaining('`headers().get`.')],
expect.stringContaining("`headers().get('page')`."), terminalCookieErrors: [expect.stringContaining('`headers().get`.')],
expect.stringContaining("`headers().get('component')`."),
expect.stringContaining("`headers().has('component')`."),
expect.stringContaining('`...headers()` or similar iteration'),
],
terminalCookieErrors: [
expect.stringContaining("`headers().get('page')`."),
expect.stringContaining("`headers().get('component')`."),
expect.stringContaining("`headers().has('component')`."),
expect.stringContaining('`...headers()` or similar iteration'),
],
}) })
}) })
...@@ -106,18 +80,8 @@ describe('dynamic-requests warnings', () => { ...@@ -106,18 +80,8 @@ describe('dynamic-requests warnings', () => {
return line.includes('Route "/request/params/[slug]') return line.includes('Route "/request/params/[slug]')
}) })
expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({ expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({
browserConsoleWarnings: [ browserConsoleWarnings: [expect.stringContaining('`params.slug`.')],
expect.stringContaining('`params.slug`.'), terminalCookieErrors: [expect.stringContaining('`params.slug`.')],
expect.stringContaining('`params.slug`.'),
expect.stringContaining('`params.slug`.'),
expect.stringContaining('`...params` or similar expression'),
],
terminalCookieErrors: [
expect.stringContaining('`params.slug`.'),
expect.stringContaining('`params.slug`.'),
expect.stringContaining('`params.slug`.'),
expect.stringContaining('`...params` or similar expression'),
],
}) })
}) })
...@@ -135,18 +99,8 @@ describe('dynamic-requests warnings', () => { ...@@ -135,18 +99,8 @@ describe('dynamic-requests warnings', () => {
return line.includes('Route "/request/searchParams') return line.includes('Route "/request/searchParams')
}) })
expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({ expect({ browserConsoleWarnings, terminalCookieErrors }).toEqual({
browserConsoleWarnings: [ browserConsoleWarnings: [expect.stringContaining('`searchParams.slug`.')],
expect.stringContaining('`searchParams.slug`.'), terminalCookieErrors: [expect.stringContaining('`searchParams.slug`.')],
expect.stringContaining('`searchParams.slug`.'),
expect.stringContaining('`searchParams.slug`.'),
expect.stringContaining('`Object.keys(searchParams)` or similar'),
],
terminalCookieErrors: [
expect.stringContaining('`searchParams.slug`.'),
expect.stringContaining('`searchParams.slug`.'),
expect.stringContaining('`searchParams.slug`.'),
expect.stringContaining('`Object.keys(searchParams)` or similar'),
],
}) })
}) })
......
...@@ -13,7 +13,7 @@ describe('app dir - dynamic error trace', () => { ...@@ -13,7 +13,7 @@ describe('app dir - dynamic error trace', () => {
// TODO(veil): Where is the stackframe for app/page.js? // TODO(veil): Where is the stackframe for app/page.js?
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route / with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering", "description": "Route / with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/lib.js (4:13) @ Foo "source": "app/lib.js (4:13) @ Foo
......
...@@ -14,7 +14,7 @@ describe('DevErrorOverlay', () => { ...@@ -14,7 +14,7 @@ describe('DevErrorOverlay', () => {
const errorCode = await browser.elementByCss('[data-nextjs-error-code]') const errorCode = await browser.elementByCss('[data-nextjs-error-code]')
const code = await errorCode.getAttribute('data-nextjs-error-code') const code = await errorCode.getAttribute('data-nextjs-error-code')
expect(code).toBe('E127') expect(code).toBe('E838')
}) })
it('sends feedback when clicking helpful button', async () => { it('sends feedback when clicking helpful button', async () => {
......
...@@ -11,7 +11,7 @@ async function getData({ params }) { ...@@ -11,7 +11,7 @@ async function getData({ params }) {
console.log('data.json', data) console.log('data.json', data)
return { return {
id: params.id, id: (await params).id,
} }
} }
......
'use client' 'use client'
import { type UnsafeUnwrappedSearchParams } from 'next/server'
type SearchParams = { foo: string | string[] | undefined } type SearchParams = { foo: string | string[] | undefined }
export default function Page(props: { searchParams: Promise<SearchParams> }) { export default function Page(props: { searchParams: Promise<SearchParams> }) {
return ( return (
...@@ -21,9 +19,8 @@ function SearchParamsReadingComponent({ ...@@ -21,9 +19,8 @@ function SearchParamsReadingComponent({
}: { }: {
searchParams: Promise<SearchParams> searchParams: Promise<SearchParams>
}) { }) {
const fooParam = ( // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
searchParams as unknown as UnsafeUnwrappedSearchParams<typeof searchParams> const fooParam = (searchParams as any).foo
).foo
return ( return (
<div> <div>
this component reads the `foo` search param:{' '} this component reads the `foo` search param:{' '}
......
import { cookies, type UnsafeUnwrappedCookies } from 'next/headers' import { cookies } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -20,8 +20,8 @@ export default async function Page() { ...@@ -20,8 +20,8 @@ export default async function Page() {
async function CookiesReadingComponent() { async function CookiesReadingComponent() {
// Await a connection to test the subsequent sync cookies access at runtime. // Await a connection to test the subsequent sync cookies access at runtime.
await connection() await connection()
// Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
const token = (cookies() as unknown as UnsafeUnwrappedCookies).get('token') const token = (cookies() as any).get('token')
return ( return (
<div> <div>
......
import { cookies, type UnsafeUnwrappedCookies } from 'next/headers' import { cookies } from 'next/headers'
export default async function Page() { export default async function Page() {
return ( return (
...@@ -14,7 +14,8 @@ export default async function Page() { ...@@ -14,7 +14,8 @@ export default async function Page() {
} }
async function CookiesReadingComponent() { async function CookiesReadingComponent() {
const token = (cookies() as unknown as UnsafeUnwrappedCookies).get('token') // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
const token = (cookies() as any).get('token')
return ( return (
<div> <div>
......
import { draftMode, UnsafeUnwrappedDraftMode } from 'next/headers' import { draftMode } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -20,8 +20,8 @@ export default async function Page() { ...@@ -20,8 +20,8 @@ export default async function Page() {
async function DraftModeReadingComponent() { async function DraftModeReadingComponent() {
await new Promise((r) => process.nextTick(r)) await new Promise((r) => process.nextTick(r))
const isEnabled = (draftMode() as unknown as UnsafeUnwrappedDraftMode) // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
.isEnabled const isEnabled = (draftMode() as any).isEnabled
return ( return (
<div> <div>
this component read the draftMode isEnabled status synchronously:{' '} this component read the draftMode isEnabled status synchronously:{' '}
......
import { headers, type UnsafeUnwrappedHeaders } from 'next/headers' import { headers } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
...@@ -20,10 +20,8 @@ export default async function Page() { ...@@ -20,10 +20,8 @@ export default async function Page() {
async function HeadersReadingComponent() { async function HeadersReadingComponent() {
// Await a connection to test the subsequent sync headers access at runtime. // Await a connection to test the subsequent sync headers access at runtime.
await connection() await connection()
// Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
const userAgent = (headers() as unknown as UnsafeUnwrappedHeaders).get( const userAgent = (headers() as any).get('user-agent')
'user-agent'
)
return ( return (
<div> <div>
this component reads the `user-agent` header synchronously: {userAgent} this component reads the `user-agent` header synchronously: {userAgent}
......
import { headers, type UnsafeUnwrappedHeaders } from 'next/headers' import { headers } from 'next/headers'
export default async function Page() { export default async function Page() {
return ( return (
...@@ -14,9 +14,8 @@ export default async function Page() { ...@@ -14,9 +14,8 @@ export default async function Page() {
} }
async function HeadersReadingComponent() { async function HeadersReadingComponent() {
const userAgent = (headers() as unknown as UnsafeUnwrappedHeaders).get( // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
'user-agent' const userAgent = (headers() as any).get('user-agent')
)
return ( return (
<div> <div>
this component reads the `user-agent` header synchronously: {userAgent} this component reads the `user-agent` header synchronously: {userAgent}
......
import { connection, type UnsafeUnwrappedSearchParams } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
type SearchParams = { foo: string | string[] | undefined } type SearchParams = { foo: string | string[] | undefined }
...@@ -25,9 +25,8 @@ async function SearchParamsReadingComponent({ ...@@ -25,9 +25,8 @@ async function SearchParamsReadingComponent({
}: { }: {
searchParams: Promise<SearchParams> searchParams: Promise<SearchParams>
}) { }) {
const fooParam = ( // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
searchParams as unknown as UnsafeUnwrappedSearchParams<typeof searchParams> const fooParam = (searchParams as any).foo
).foo
return ( return (
<div> <div>
this component reads the `foo` search param:{' '} this component reads the `foo` search param:{' '}
......
import { UnsafeUnwrappedCookies } from 'next/headers' import type { cookies } from 'next/headers'
// We don't export this type (why) but we can exfiltrate it through our exported typecase type type ReadonlyRequestCookies = Awaited<ReturnType<typeof cookies>>
type ReadonlyRequestCookies = UnsafeUnwrappedCookies
export function AllComponents({ export function AllComponents({
cookies, cookies,
......
...@@ -178,7 +178,7 @@ describe('dynamic-data with dynamic = "error"', () => { ...@@ -178,7 +178,7 @@ describe('dynamic-data with dynamic = "error"', () => {
try { try {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route /cookies with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering", "description": "Route /cookies with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/cookies/page.js (14:24) @ Page "source": "app/cookies/page.js (14:24) @ Page
...@@ -197,7 +197,7 @@ describe('dynamic-data with dynamic = "error"', () => { ...@@ -197,7 +197,7 @@ describe('dynamic-data with dynamic = "error"', () => {
try { try {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route /connection with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering", "description": "Route /connection with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/connection/page.js (6:19) @ Page "source": "app/connection/page.js (6:19) @ Page
...@@ -216,7 +216,7 @@ describe('dynamic-data with dynamic = "error"', () => { ...@@ -216,7 +216,7 @@ describe('dynamic-data with dynamic = "error"', () => {
try { try {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route /headers with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering", "description": "Route /headers with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers()\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/headers/page.js (14:35) @ Page "source": "app/headers/page.js (14:35) @ Page
...@@ -259,13 +259,13 @@ describe('dynamic-data with dynamic = "error"', () => { ...@@ -259,13 +259,13 @@ describe('dynamic-data with dynamic = "error"', () => {
} }
// Error: Page with `dynamic = "error"` couldn't be rendered statically because it used `headers` // Error: Page with `dynamic = "error"` couldn't be rendered statically because it used `headers`
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /cookies with `dynamic = "error"` couldn\'t be rendered statically because it used `cookies`' 'Error: Route /cookies with `dynamic = "error"` couldn\'t be rendered statically because it used `cookies()`'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /connection with `dynamic = "error"` couldn\'t be rendered statically because it used `connection`' 'Error: Route /connection with `dynamic = "error"` couldn\'t be rendered statically because it used `connection()`'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /headers with `dynamic = "error"` couldn\'t be rendered statically because it used `headers`' 'Error: Route /headers with `dynamic = "error"` couldn\'t be rendered statically because it used `headers()`'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /search with `dynamic = "error"` couldn\'t be rendered statically because it used `await searchParams`, `searchParams.then`, or similar' 'Error: Route /search with `dynamic = "error"` couldn\'t be rendered statically because it used `await searchParams`, `searchParams.then`, or similar'
...@@ -307,7 +307,7 @@ describe('dynamic-data inside cache scope', () => { ...@@ -307,7 +307,7 @@ describe('dynamic-data inside cache scope', () => {
try { try {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route /cookies used "cookies" 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 "cookies" 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", "description": "Route /cookies used \`cookies()\` 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 \`cookies()\` 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",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/cookies/page.js (4:40) @ ${isTurbopack ? '<anonymous>' : 'eval'} "source": "app/cookies/page.js (4:40) @ ${isTurbopack ? '<anonymous>' : 'eval'}
...@@ -327,7 +327,7 @@ describe('dynamic-data inside cache scope', () => { ...@@ -327,7 +327,7 @@ describe('dynamic-data inside cache scope', () => {
try { try {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route /connection used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache", "description": "Route /connection used \`connection()\` inside a function cached with \`unstable_cache()\`. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/connection/page.js (4:54) @ ${isTurbopack ? '<anonymous>' : 'eval'} "source": "app/connection/page.js (4:54) @ ${isTurbopack ? '<anonymous>' : 'eval'}
...@@ -347,7 +347,7 @@ describe('dynamic-data inside cache scope', () => { ...@@ -347,7 +347,7 @@ describe('dynamic-data inside cache scope', () => {
try { try {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Route /headers used "headers" 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 "headers" 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", "description": "Route /headers used \`headers()\` 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 \`headers()\` 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",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Runtime Error", "label": "Runtime Error",
"source": "app/headers/page.js (4:40) @ ${isTurbopack ? '<anonymous>' : 'eval'} "source": "app/headers/page.js (4:40) @ ${isTurbopack ? '<anonymous>' : 'eval'}
...@@ -371,13 +371,13 @@ describe('dynamic-data inside cache scope', () => { ...@@ -371,13 +371,13 @@ describe('dynamic-data inside cache scope', () => {
// We expect this to fail // We expect this to fail
} }
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /cookies used "cookies" inside a function cached with "unstable_cache(...)".' 'Error: Route /cookies used `cookies()` inside a function cached with `unstable_cache()`.'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /connection used "connection" inside a function cached with "unstable_cache(...)".' 'Error: Route /connection used `connection()` inside a function cached with `unstable_cache()`.'
) )
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
'Error: Route /headers used "headers" inside a function cached with "unstable_cache(...)".' 'Error: Route /headers used `headers()` inside a function cached with `unstable_cache()`.'
) )
}) })
} }
......
...@@ -55,32 +55,32 @@ describe('nextjs APIs in after()', () => { ...@@ -55,32 +55,32 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] headers(): ok`) expect(logs).not.toContain(`[${path}] headers(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] headers(): error: Error: Route ${path} used "headers" inside "after(...)". This is not supported.` `[${path}] headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] nested headers(): ok`) expect(logs).not.toContain(`[${path}] nested headers(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested headers(): error: Error: Route ${path} used "headers" inside "after(...)". This is not supported.` `[${path}] nested headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] cookies(): ok`) expect(logs).not.toContain(`[${path}] cookies(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] cookies(): error: Error: Route ${path} used "cookies" inside "after(...)". This is not supported.` `[${path}] cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] nested cookies(): ok`) expect(logs).not.toContain(`[${path}] nested cookies(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested cookies(): error: Error: Route ${path} used "cookies" inside "after(...)". This is not supported.` `[${path}] nested cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] connection(): ok`) expect(logs).not.toContain(`[${path}] connection(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] connection(): error: Error: Route ${path} used "connection" inside "after(...)".` `[${path}] connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
) )
expect(logs).not.toContain(`[${path}] nested connection(): ok`) expect(logs).not.toContain(`[${path}] nested connection(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested connection(): error: Error: Route ${path} used "connection" inside "after(...)".` `[${path}] nested connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
) )
}) })
}) })
...@@ -102,32 +102,32 @@ describe('nextjs APIs in after()', () => { ...@@ -102,32 +102,32 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] headers(): ok`) expect(logs).not.toContain(`[${path}] headers(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] headers(): error: Error: Route ${path} used "headers" inside "after(...)". This is not supported.` `[${path}] headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] nested headers(): ok`) expect(logs).not.toContain(`[${path}] nested headers(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested headers(): error: Error: Route ${path} used "headers" inside "after(...)". This is not supported.` `[${path}] nested headers(): error: Error: Route ${path} used \`headers()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] cookies(): ok`) expect(logs).not.toContain(`[${path}] cookies(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] cookies(): error: Error: Route ${path} used "cookies" inside "after(...)". This is not supported.` `[${path}] cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] nested cookies(): ok`) expect(logs).not.toContain(`[${path}] nested cookies(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested cookies(): error: Error: Route ${path} used "cookies" inside "after(...)". This is not supported.` `[${path}] nested cookies(): error: Error: Route ${path} used \`cookies()\` inside \`after()\`. This is not supported.`
) )
expect(logs).not.toContain(`[${path}] connection(): ok`) expect(logs).not.toContain(`[${path}] connection(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] connection(): error: Error: Route ${path} used "connection" inside "after(...)".` `[${path}] connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
) )
expect(logs).not.toContain(`[${path}] nested connection(): ok`) expect(logs).not.toContain(`[${path}] nested connection(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested connection(): error: Error: Route ${path} used "connection" inside "after(...)".` `[${path}] nested connection(): error: Error: Route ${path} used \`connection()\` inside \`after()\`.`
) )
}) })
}) })
...@@ -190,32 +190,32 @@ describe('nextjs APIs in after()', () => { ...@@ -190,32 +190,32 @@ describe('nextjs APIs in after()', () => {
expect(logs).not.toContain(`[${path}] headers(): ok`) expect(logs).not.toContain(`[${path}] headers(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] headers(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`.` `[${path}] headers(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers()\`.`
) )
expect(logs).not.toContain(`[${path}] nested headers(): ok`) expect(logs).not.toContain(`[${path}] nested headers(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested headers(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`.` `[${path}] nested headers(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers()\`.`
) )
expect(logs).not.toContain(`[${path}] cookies(): ok`) expect(logs).not.toContain(`[${path}] cookies(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] cookies(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`.` `[${path}] cookies(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies()\`.`
) )
expect(logs).not.toContain(`[${path}] nested cookies(): ok`) expect(logs).not.toContain(`[${path}] nested cookies(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested cookies(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`.` `[${path}] nested cookies(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies()\`.`
) )
expect(logs).not.toContain(`[${path}] connection(): ok`) expect(logs).not.toContain(`[${path}] connection(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] connection(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`.` `[${path}] connection(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection()\`.`
) )
expect(logs).not.toContain(`[${path}] nested connection(): ok`) expect(logs).not.toContain(`[${path}] nested connection(): ok`)
expect(logs).toContain( expect(logs).toContain(
`[${path}] nested connection(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`.` `[${path}] nested connection(): error: Error: Route ${path} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection()\`.`
) )
}) })
}) })
...@@ -250,10 +250,10 @@ describe('nextjs APIs in after()', () => { ...@@ -250,10 +250,10 @@ describe('nextjs APIs in after()', () => {
const logs = isDynamic || isNextDev ? getLogs() : buildLogs const logs = isDynamic || isNextDev ? getLogs() : buildLogs
expect(logs).toContain(`[${path}] draft.isEnabled: false`) expect(logs).toContain(`[${path}] draft.isEnabled: false`)
expect(logs).toContain( expect(logs).toContain(
`Route ${path} used "draftMode().enable()" inside \`after\`` `Route ${path} used "draftMode().enable()" inside \`after()\``
) )
expect(logs).toContain( expect(logs).toContain(
`Route ${path} used "draftMode().disable()" inside \`after\`` `Route ${path} used "draftMode().disable()" inside \`after()\``
) )
}) })
}) })
...@@ -266,10 +266,10 @@ describe('nextjs APIs in after()', () => { ...@@ -266,10 +266,10 @@ describe('nextjs APIs in after()', () => {
const logs = getLogs() const logs = getLogs()
expect(logs).toContain(`[${path}] draft.isEnabled: false`) expect(logs).toContain(`[${path}] draft.isEnabled: false`)
expect(logs).toContain( expect(logs).toContain(
`Route ${path} used "draftMode().enable()" inside \`after\`` `Route ${path} used "draftMode().enable()" inside \`after()\``
) )
expect(logs).toContain( expect(logs).toContain(
`Route ${path} used "draftMode().disable()" inside \`after\`` `Route ${path} used "draftMode().disable()" inside \`after()\``
) )
}) })
}) })
......
import React from 'react' import React from 'react'
import * as next from 'next/headers' import * as next from 'next/headers'
export const Dynamic = ({ pathname, fallback = null, params = null }) => { export const Dynamic = async ({ pathname, fallback = null, params = null }) => {
if (fallback) { if (fallback) {
return <div data-fallback>Dynamic Loading...</div> return <div data-fallback>Dynamic Loading...</div>
} }
const headers = next.headers() const headers = await next.headers()
const messages = [] const messages = []
for (const name of ['x-test-input', 'user-agent']) { for (const name of ['x-test-input', 'user-agent']) {
messages.push({ name, value: headers.get(name) }) messages.push({ name, value: headers.get(name) })
......
...@@ -9,7 +9,7 @@ import { ...@@ -9,7 +9,7 @@ import {
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
const getExpectedErrorMessage = (route: string) => const getExpectedErrorMessage = (route: string) =>
`Route ${route} used "searchParams" inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await "searchParams" outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${route} used \`searchParams\` inside "use cache". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \`searchParams\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
describe('use-cache-search-params', () => { describe('use-cache-search-params', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
......
...@@ -886,7 +886,7 @@ describe('use-cache', () => { ...@@ -886,7 +886,7 @@ describe('use-cache', () => {
const expectedErrorMessage = disableJavaScript const expectedErrorMessage = disableJavaScript
? 'Failed to load resource: the server responded with a status of 500 (Internal Server Error)' ? 'Failed to load resource: the server responded with a status of 500 (Internal Server Error)'
: isNextDev : isNextDev
? 'Route /draft-mode/[mode] used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" 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' ? 'Route /draft-mode/[mode] used `cookies()` inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use `cookies()` 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'
: GENERIC_RSC_ERROR : GENERIC_RSC_ERROR
expect(logs).toMatchObject( expect(logs).toMatchObject(
......
...@@ -85,25 +85,6 @@ describe('production - app dir - build output', () => { ...@@ -85,25 +85,6 @@ describe('production - app dir - build output', () => {
expect(cliOutput).toContain('Next.js build worker exited with code: 78') expect(cliOutput).toContain('Next.js build worker exited with code: 78')
}) })
it('should fail the build if you use a dynamic API outside of a render context - searchParams', async () => {
await next.stop()
await next.patchFile(
'app/out-of-band-dynamic-api/page.tsx',
outdent`
export default async function Page({ searchParams }) {
setTimeout(() => {
searchParams.foo
}, 0)
return <div>Hello World</div>
}
`
)
const { cliOutput } = await next.build()
await next.deleteFile('app/out-of-band-dynamic-api/page.tsx')
expect(cliOutput).toContain('Next.js build worker exited with code: 78')
})
it('should fail the build if you use a dynamic API outside of a render context - redirect', async () => { it('should fail the build if you use a dynamic API outside of a render context - redirect', async () => {
await next.stop() await next.stop()
await next.patchFile( await next.patchFile(
......
import { cookies, type UnsafeUnwrappedCookies } from 'next/headers' import { cookies } from 'next/headers'
// The purpose of this file is to demonstrate that without proper symbolic file checking // The purpose of this file is to demonstrate that without proper symbolic file checking
// next accidentally marks files in the root of the project as client files. // next accidentally marks files in the root of the project as client files.
export default function () { export default async function () {
const locale = const locale = (await cookies()).get('locale')?.value ?? 'en'
(cookies() as unknown as UnsafeUnwrappedCookies).get('locale')?.value ??
'en'
return { return {
locale, locale,
......
...@@ -22,7 +22,7 @@ export default async function Page({ params }) { ...@@ -22,7 +22,7 @@ export default async function Page({ params }) {
<Suspense> <Suspense>
<Postpone> <Postpone>
<p id="page">/rewrite/[slug]</p> <p id="page">/rewrite/[slug]</p>
<p id="params">{JSON.stringify(params)}</p> <p id="params">{JSON.stringify(await params)}</p>
<p id="now">{Date.now()}</p> <p id="now">{Date.now()}</p>
</Postpone> </Postpone>
</Suspense> </Suspense>
......
export default function Page({ searchParams, params }) { export default async function Page({ searchParams, params }) {
return ( return (
<dl> <dl>
<dt>params.key</dt> <dt>params.key</dt>
<dd data-params>{params.key}</dd> <dd data-params>{(await params).key}</dd>
<dt>searchParams.key</dt> <dt>searchParams.key</dt>
<dd data-searchParams>{searchParams.key}</dd> <dd data-searchParams>{(await searchParams).key}</dd>
</dl> </dl>
) )
} }
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