Unverified Commit 05f159df authored by Josh Story's avatar Josh Story Committed by GitHub

[Breaking] Update Dynamic APIs to be async (#68812)

Next.js has a number of dynamic APIs that aren't available during
prerendering. What happens when you access these APIs might differ
depending on the mode you are using, for instance if you have PPR turned
on or the newly introduced `dynamicIO` experimental mode. But regardless
of the mode the underlying API represents accessing something that might
only be available at render time (dynamic rendering) rather than
prerender time (build and revalidate rendering)

Unfortunately our current dynamic APIs make certain kinds of modeling
tricky because they are all synchronous. For instance if we wanted to
add a feature to Next.js where we started a dynamic render before a
Request even hits the server it would be interesting to be able to start
working on everything that does not rely on any dynamic data and then
once a real Request arrives we can continue the render and provide the
associated Request context through our dynamic APIs.

If our dynamic APIs were all async we could build something like this
because they represnt a value that will eventually resolve to some
Request value. This PR updates most existing dynamic APIs to be async
rather than sync. This is a breaking change and will need to be paired
with codemods to realistically adopt. Additionally since this change is
so invasive I have implemented it in a way to maximize backward
compatibility by still allowing most synchronous access. The combination
of codemods, typescript updates, and backward compat functionality
should make it possible for projects to upgrade to the latest version
with minimal effort and then follow up with a complete conversion over
time.

#### `cookies()`
`cookies()` now returns `Promise<ReadonlyRequestCookies>`. Synchronous
access to the underlying RequestCookies object is still supported to
facilitate migration.
```tsx
// ------------ preferred usage

// async Server Component
const token = (await cookies()).get('token')

// sync Server Component
import { use } from 'react'
//...
const token = use(cookies()).get('token')

// ------------ temporarily allowed usage

// javascript, dev warning at runtime
const token = cookies().get('token')

// typescript, dev warning at runtime
import { type UnsafeUnwrappedCookies } from 'next/headers'
// ...
const token = (cookies() as unknown as UnsafeUnwrappedCookies).get('token')
```

#### `headers()`
`headers()` now returns `Promise<ReadonlyHeaders>`. Synchronous access
to the underlying Headers object is still supported to facilitate
migration.
```tsx
// ------------ preferred usage

// async Server Component
const header = (await headers()).get('x-foo')

// sync Server Component
import { use } from 'react'
//...
const header = use(headers()).get('x-foo')

// ------------ temporarily allowed usage

// javascript, dev warning at runtime
const header = headers().get('x-foo')

// typescript, dev warning at runtime
import { type UnsafeUnwrappedHeaders } from 'next/headers'
// ...
const header = (headers() as unknown as UnsafeUnwrappedHeaders).get('x-foo')
```


#### `draftMode()`
`draftMode()` now returns `Promise<DraftMode>`. Synchronous access to
the underlying DraftMode object is still supported to facilitate
migration.
```tsx
// ------------ preferred usage

// async Server Component
if ((await draftMode()).isEnabled) { ... }

// sync Server Component
import { use } from 'react'
//...
if (use(draftMode()).isEnabled) { ... }

// ------------ temporarily allowed usage

// javascript, dev warning at runtime
if (draftMode().isEnabled) { ... }

// typescript, dev warning at runtime
import { type UnsafeUnwrappedDraftMode} from 'next/headers'
// ...
if ((draftMode() as unknown as UnsafeUnwrappedDraftMode).isEnabled) { ... }
```

#### `searchParams`
`searchParams` is now a `Promise<{...}>`. Synchronous access to the
underlying search params is still supported to facilitate migration.
```tsx
// ------------ preferred usage

// async Page Component
export default async function Page({
  searchParams
}: {
  searchParams: Promise<{ foo: string }>
}) {
  const fooSearchParam = (await searchParams).foo
}

// sync Page Component
import { use } from 'react'
export default function Page({
  searchParams
}: {
  searchParams: Promise<{ foo: string }>
}) {
  const fooSearchParam = use(searchParams).foo
}

// ------------ temporarily allowed usage

// javascript, dev warning at runtime
export default async function Page({ searchParams}) {
  const fooSearchParam = searchParams.foo
}

// typescript, dev warning at runtime
import { type UnsafeUnwrappedSearchParams } from 'next/server'
export default async function Page({
  searchParams
}: {
  searchParams: Promise<{ foo: string }>
}) {
  const syncSearchParams = (searchParams as unknown as UnsafeUnwrappedSearchParams<typeof searchParams>)
  const fooSearchParam = syncSearchParams.foo
}
```



#### `params`
`params` is now a `Promise<{...}>`. Synchronous access to the underlying
params is still supported to facilitate migration. It should be noted
that while params are not usually dynamic there are certain modes where
they can be such as fallback prerenders for PPR.
```tsx
// ------------ preferred usage

// async Segment Component
export default async function Layout({
  params
}: {
  params: Promise<{ foo: string }>
}) {
  const fooParam = (await params).foo
}

// sync Segment Component
import { use } from 'react'
export default function Layout({
  params
}: {
  params: Promise<{ foo: string }>
}) {
  const fooParam = use(params).foo
}

// ------------ temporarily allowed usage

// javascript, dev warning at runtime
export default async function Layout({ params}) {
  const fooParam = params.foo
}

// typescript, dev warning at runtime
import { type UnsafeUnwrappedParams } from 'next/headers'
export default async function Layout({
  params
}: {
  params: Promise<{ foo: string }>
}) {
  const syncParams = (params as unknown as UnsafeUnwrappedParams<typeof params>)
  const fooSearchParam = syncParams.foo
}
```

### Typescript Changes
When using typescript with Next.js currently it is up to you to author
types for Pages, Layouts and other Segment components that recieve props
like `params` and `searchParams`.

Next comes with some build-time type checking to ensure you have not
improperly typed various top level module exports however the current
type assertions for `params` and `searchParams` is `any`. This isn't
very helpful because it allows you to erroneously type these props.

`searchParams` is tricky because while the default type is a dictionary
object parsed using node.js url parsing it is possible to customize when
running a custom Next.js server. However we can ensure that you
correctly type the prop as a Promise so with this change the validated
type for `searchParams` will be `Promise<any>`.

In the long run we will look at updating the `searchParams` underlying
type to be URLSearchParams so we can move away from supporting
customized parsing during rendering and we can get even more explicit
about valid types.

`params` is more straight forward because the framework controls the
actual `params` prop implementation and no customization is possible. In
the long run we want to enforce you are only typing params that are
valid for the Layout level your file is located in but for now we are
updating the allowed type to be `Promise<{[key: string]: string |
string[] | undefined }>`.

These new type restrictions may also require fixes before being able to
successfully build a project that updates to include these breaking
changes. These changes will also not always be codemodable because it is
valid to type the entire component using an opaque type like `Props`
which our codemods may not have an ability to introspect or modify.
parent e92ea383
...@@ -60,14 +60,29 @@ ...@@ -60,14 +60,29 @@
"codemod", "codemod",
"codemods", "codemods",
"Destructuring", "Destructuring",
"buildtime",
"callsites",
"codemod",
"datastream",
"deduped",
"draftmode",
"Entrypoints", "Entrypoints",
"jscodeshift", "jscodeshift",
"napi", "napi",
"navigations",
"nextjs", "nextjs",
"opentelemetry", "opentelemetry",
"Preinit",
"prerendered", "prerendered",
"prerendering",
"proxied",
"renderable",
"revalidates",
"subresource",
"thenables",
"Threadsafe", "Threadsafe",
"Turbopack", "Turbopack",
"unproxied",
"zipkin" "zipkin"
], ],
"grammarly.selectors": [ "grammarly.selectors": [
......
export * from './dist/server/request/cookies'
export * from './dist/server/request/headers' export * from './dist/server/request/headers'
export * from './dist/server/request/draft-mode'
module.exports = require('./dist/server/request/headers') module.exports.cookies = require('./dist/server/request/cookies').cookies
module.exports.headers = require('./dist/server/request/headers').headers
module.exports.draftMode = require('./dist/server/request/draft-mode').draftMode
...@@ -14,3 +14,5 @@ export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url' ...@@ -14,3 +14,5 @@ export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url'
export { ImageResponse } from 'next/dist/server/web/spec-extension/image-response' export { ImageResponse } from 'next/dist/server/web/spec-extension/image-response'
export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types' export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types'
export { unstable_after } from 'next/dist/server/after' export { unstable_after } from 'next/dist/server/after'
export type { UnsafeUnwrappedSearchParams } from 'next/dist/server/request/search-params'
export type { UnsafeUnwrappedParams } from 'next/dist/server/request/params'
export * from '../server/request/cookies'
export * from '../server/request/headers' export * from '../server/request/headers'
export * from '../server/request/draft-mode'
...@@ -85,6 +85,7 @@ checkFields<Diff<{ ...@@ -85,6 +85,7 @@ checkFields<Diff<{
} }
}, TEntry, ''>>() }, TEntry, ''>>()
${options.type === 'route' ? `type RouteContext = { params: Promise<SegmentParams> }` : ''}
${ ${
options.type === 'route' options.type === 'route'
? HTTP_METHODS.map( ? HTTP_METHODS.map(
...@@ -103,7 +104,7 @@ if ('${method}' in entry) { ...@@ -103,7 +104,7 @@ if ('${method}' in entry) {
>() >()
checkFields< checkFields<
Diff< Diff<
ParamCheck<PageParams>, ParamCheck<RouteContext>,
{ {
__tag__: '${method}' __tag__: '${method}'
__param_position__: 'second' __param_position__: 'second'
...@@ -158,14 +159,14 @@ if ('generateViewport' in entry) { ...@@ -158,14 +159,14 @@ if ('generateViewport' in entry) {
} }
// Check the arguments and return type of the generateStaticParams function // Check the arguments and return type of the generateStaticParams function
if ('generateStaticParams' in entry) { if ('generateStaticParams' in entry) {
checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>() checkFields<Diff<{ params: SegmentParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>()
checkFields<Diff<{ __tag__: 'generateStaticParams', __return_type__: any[] | Promise<any[]> }, { __tag__: 'generateStaticParams', __return_type__: ReturnType<MaybeField<TEntry, 'generateStaticParams'>> }>>() checkFields<Diff<{ __tag__: 'generateStaticParams', __return_type__: any[] | Promise<any[]> }, { __tag__: 'generateStaticParams', __return_type__: ReturnType<MaybeField<TEntry, 'generateStaticParams'>> }>>()
} }
type PageParams = any type SegmentParams = {[param: string]: string | string[] | undefined}
export interface PageProps { export interface PageProps {
params?: any params?: Promise<SegmentParams>
searchParams?: any searchParams?: Promise<any>
} }
export interface LayoutProps { export interface LayoutProps {
children?: React.ReactNode children?: React.ReactNode
...@@ -174,7 +175,7 @@ ${ ...@@ -174,7 +175,7 @@ ${
? options.slots.map((slot) => ` ${slot}: React.ReactNode`).join('\n') ? options.slots.map((slot) => ` ${slot}: React.ReactNode`).join('\n')
: '' : ''
} }
params?: any params?: Promise<SegmentParams>
} }
// ============= // =============
......
'use client' 'use client'
import type { ParsedUrlQuery } from 'querystring'
import { InvariantError } from '../../shared/lib/invariant-error'
import type { Params } from '../../server/request/params'
/**
* When the Page is a client component we send the params and searchParams to this client wrapper
* where they are turned into dynamically tracked values before being passed to the actual Page component.
*
* additionally we may send promises representing the params and searchParams. We don't ever use these passed
* values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations.
* It is up to the caller to decide if the promises are needed.
*/
export function ClientPageRoot({ export function ClientPageRoot({
Component, Component,
props, searchParams,
params,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
promises,
}: { }: {
Component: React.ComponentType<any> Component: React.ComponentType<any>
props: { [props: string]: any } searchParams: ParsedUrlQuery
params: Params
promises?: Array<Promise<any>>
}) { }) {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { createDynamicallyTrackedParams } = const { staticGenerationAsyncStorage } =
require('../../server/request/fallback-params') as typeof import('../../server/request/fallback-params') require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
const { createDynamicallyTrackedSearchParams } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params') let clientSearchParams: Promise<ParsedUrlQuery>
let clientParams: Promise<Params>
// We expect to be passed searchParams but even if we aren't we can construct one from // We are going to instrument the searchParams prop with tracking for the
// an empty object. We only do this if we are in a static generation as a performance // appropriate context. We wrap differently in prerendering vs rendering
// optimization. Ideally we'd unconditionally construct the tracked params but since const store = staticGenerationAsyncStorage.getStore()
// this creates a proxy which is slow and this would happen even for client navigations if (!store) {
// that are done entirely dynamically and we know there the dynamic tracking is a noop throw new InvariantError(
// in this dynamic case we can safely elide it. 'Expected staticGenerationStore to exist when handling searchParams in a client Page.'
props.searchParams = createDynamicallyTrackedSearchParams( )
props.searchParams || {} }
)
props.params = props.params if (store.isStaticGeneration) {
? createDynamicallyTrackedParams(props.params) // We are in a prerender context
: {} const { createPrerenderSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createPrerenderSearchParamsFromClient(store)
const { createPrerenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createPrerenderParamsFromClient(params, store)
} else {
const { createRenderSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createRenderSearchParamsFromClient(
searchParams,
store
)
const { createRenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createRenderParamsFromClient(params, store)
}
return <Component params={clientParams} searchParams={clientSearchParams} />
} else {
const { createRenderSearchParamsFromClient } =
require('../../server/request/search-params.browser') as typeof import('../../server/request/search-params.browser')
const clientSearchParams = createRenderSearchParamsFromClient(searchParams)
const { createRenderParamsFromClient } =
require('../../server/request/params.browser') as typeof import('../../server/request/params.browser')
const clientParams = createRenderParamsFromClient(params)
return <Component params={clientParams} searchParams={clientSearchParams} />
} }
return <Component {...props} />
} }
'use client' 'use client'
type ClientSegmentRootProps = { import { InvariantError } from '../../shared/lib/invariant-error'
Component: React.ComponentType
props: { [props: string]: any } import type { Params } from '../../server/request/params'
}
/**
* When the Page is a client component we send the params to this client wrapper
* where they are turned into dynamically tracked values before being passed to the actual Segment component.
*
* additionally we may send a promise representing params. We don't ever use this passed
* value but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations
* such as when dynamicIO is enabled. It is up to the caller to decide if the promises are needed.
*/
export function ClientSegmentRoot({ export function ClientSegmentRoot({
Component, Component,
props, slots,
}: ClientSegmentRootProps) { params,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
promise,
}: {
Component: React.ComponentType<any>
slots: { [key: string]: React.ReactNode }
params: Params
promise?: Promise<any>
}) {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { createDynamicallyTrackedParams } = const { staticGenerationAsyncStorage } =
require('../../server/request/fallback-params') as typeof import('../../server/request/fallback-params') require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
let clientParams: Promise<Params>
// We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering
const store = staticGenerationAsyncStorage.getStore()
if (!store) {
throw new InvariantError(
'Expected staticGenerationStore to exist when handling params in a client segment such as a Layout or Template.'
)
}
const { createPrerenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
props.params = props.params if (store.isStaticGeneration) {
? createDynamicallyTrackedParams(props.params) clientParams = createPrerenderParamsFromClient(params, store)
: {} } else {
const { createRenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createRenderParamsFromClient(params, store)
}
return <Component {...slots} params={clientParams} />
} else {
const { createRenderParamsFromClient } =
require('../../server/request/params.browser') as typeof import('../../server/request/params.browser')
const clientParams = createRenderParamsFromClient(params)
return <Component {...slots} params={clientParams} />
} }
return <Component {...props} />
} }
...@@ -15,7 +15,7 @@ import { ...@@ -15,7 +15,7 @@ import {
import { getSegmentValue } from './router-reducer/reducers/get-segment-value' import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment' import { PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import { ReadonlyURLSearchParams } from './navigation.react-server' import { ReadonlyURLSearchParams } from './navigation.react-server'
import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering' import { useDynamicRouteParams } from '../../server/app-render/dynamic-rendering'
/** /**
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
...@@ -65,27 +65,6 @@ export function useSearchParams(): ReadonlyURLSearchParams { ...@@ -65,27 +65,6 @@ export function useSearchParams(): ReadonlyURLSearchParams {
return readonlySearchParams return readonlySearchParams
} }
function trackParamsAccessed(expression: string) {
if (typeof window === 'undefined') {
// AsyncLocalStorage should not be included in the client bundle.
const { staticGenerationAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (
staticGenerationStore &&
staticGenerationStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0
) {
// There are fallback route params, we should track these as dynamic
// accesses.
trackFallbackParamAccessed(staticGenerationStore, expression)
}
}
}
/** /**
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
* that lets you read the current URL's pathname. * that lets you read the current URL's pathname.
...@@ -105,7 +84,7 @@ function trackParamsAccessed(expression: string) { ...@@ -105,7 +84,7 @@ function trackParamsAccessed(expression: string) {
*/ */
// Client components API // Client components API
export function usePathname(): string { export function usePathname(): string {
trackParamsAccessed('usePathname()') useDynamicRouteParams('usePathname()')
// In the case where this is `null`, the compat types added in `next-env.d.ts` // In the case where this is `null`, the compat types added in `next-env.d.ts`
// will add a new overload that changes the return type to include `null`. // will add a new overload that changes the return type to include `null`.
...@@ -165,21 +144,19 @@ export function useRouter(): AppRouterInstance { ...@@ -165,21 +144,19 @@ export function useRouter(): AppRouterInstance {
*/ */
// Client components API // Client components API
export function useParams<T extends Params = Params>(): T { export function useParams<T extends Params = Params>(): T {
trackParamsAccessed('useParams()') useDynamicRouteParams('useParams()')
return useContext(PathParamsContext) as T return useContext(PathParamsContext) as T
} }
/** Get the canonical parameters from the current level to the leaf node. */ /** Get the canonical parameters from the current level to the leaf node. */
// Client components API // Client components API
export function getSelectedLayoutSegmentPath( function getSelectedLayoutSegmentPath(
tree: FlightRouterState, tree: FlightRouterState,
parallelRouteKey: string, parallelRouteKey: string,
first = true, first = true,
segmentPath: string[] = [] segmentPath: string[] = []
): string[] { ): string[] {
trackParamsAccessed('getSelectedLayoutSegmentPath()')
let node: FlightRouterState let node: FlightRouterState
if (first) { if (first) {
// Use the provided parallel route key on the first parallel route // Use the provided parallel route key on the first parallel route
...@@ -238,7 +215,7 @@ export function getSelectedLayoutSegmentPath( ...@@ -238,7 +215,7 @@ export function getSelectedLayoutSegmentPath(
export function useSelectedLayoutSegments( export function useSelectedLayoutSegments(
parallelRouteKey: string = 'children' parallelRouteKey: string = 'children'
): string[] { ): string[] {
trackParamsAccessed('useSelectedLayoutSegments()') useDynamicRouteParams('useSelectedLayoutSegments()')
const context = useContext(LayoutRouterContext) const context = useContext(LayoutRouterContext)
// @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts // @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts
...@@ -269,7 +246,7 @@ export function useSelectedLayoutSegments( ...@@ -269,7 +246,7 @@ export function useSelectedLayoutSegments(
export function useSelectedLayoutSegment( export function useSelectedLayoutSegment(
parallelRouteKey: string = 'children' parallelRouteKey: string = 'children'
): string | null { ): string | null {
trackParamsAccessed('useSelectedLayoutSegment()') useDynamicRouteParams('useSelectedLayoutSegment()')
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey) const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)
......
...@@ -4,6 +4,7 @@ import type { ...@@ -4,6 +4,7 @@ import type {
GetDynamicParamFromSegment, GetDynamicParamFromSegment,
} from '../../server/app-render/app-render' } from '../../server/app-render/app-render'
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { CreateServerParamsForMetadata } from '../../server/request/params'
import React from 'react' import React from 'react'
import { import {
...@@ -30,7 +31,6 @@ import type { ...@@ -30,7 +31,6 @@ import type {
} from './types/metadata-interface' } from './types/metadata-interface'
import { isNotFoundError } from '../../client/components/not-found' import { isNotFoundError } from '../../client/components/not-found'
import type { MetadataContext } from './types/resolvers' import type { MetadataContext } from './types/resolvers'
import type { CreateDynamicallyTrackedParams } from '../../server/request/fallback-params'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering' import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering'
...@@ -84,24 +84,22 @@ export function createTrackedMetadataContext( ...@@ -84,24 +84,22 @@ export function createTrackedMetadataContext(
// and the error will be caught by the error boundary and trigger fallbacks. // and the error will be caught by the error boundary and trigger fallbacks.
export function createMetadataComponents({ export function createMetadataComponents({
tree, tree,
query, searchParams,
metadataContext, metadataContext,
getDynamicParamFromSegment, getDynamicParamFromSegment,
appUsingSizeAdjustment, appUsingSizeAdjustment,
errorType, errorType,
createDynamicallyTrackedSearchParams, createServerParamsForMetadata,
createDynamicallyTrackedParams, staticGenerationStore,
}: { }: {
tree: LoaderTree tree: LoaderTree
query: ParsedUrlQuery searchParams: Promise<ParsedUrlQuery>
metadataContext: MetadataContext metadataContext: MetadataContext
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment
appUsingSizeAdjustment: boolean appUsingSizeAdjustment: boolean
errorType?: 'not-found' | 'redirect' errorType?: 'not-found' | 'redirect'
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams createServerParamsForMetadata: CreateServerParamsForMetadata
createDynamicallyTrackedSearchParams: ( staticGenerationStore: StaticGenerationStore
searchParams: ParsedUrlQuery
) => ParsedUrlQuery
}): [React.ComponentType, () => Promise<void>] { }): [React.ComponentType, () => Promise<void>] {
let currentMetadataReady: let currentMetadataReady:
| null | null
...@@ -113,11 +111,11 @@ export function createMetadataComponents({ ...@@ -113,11 +111,11 @@ export function createMetadataComponents({
async function MetadataTree() { async function MetadataTree() {
const pendingMetadata = getResolvedMetadata( const pendingMetadata = getResolvedMetadata(
tree, tree,
query, searchParams,
getDynamicParamFromSegment, getDynamicParamFromSegment,
metadataContext, metadataContext,
createDynamicallyTrackedSearchParams, createServerParamsForMetadata,
createDynamicallyTrackedParams, staticGenerationStore,
errorType errorType
) )
...@@ -177,18 +175,15 @@ export function createMetadataComponents({ ...@@ -177,18 +175,15 @@ export function createMetadataComponents({
async function getResolvedMetadata( async function getResolvedMetadata(
tree: LoaderTree, tree: LoaderTree,
query: ParsedUrlQuery, searchParams: Promise<ParsedUrlQuery>,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext, metadataContext: MetadataContext,
createDynamicallyTrackedSearchParams: ( createServerParamsForMetadata: CreateServerParamsForMetadata,
searchParams: ParsedUrlQuery staticGenerationStore: StaticGenerationStore,
) => ParsedUrlQuery,
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams,
errorType?: 'not-found' | 'redirect' errorType?: 'not-found' | 'redirect'
): Promise<[any, Array<React.ReactNode>]> { ): Promise<[any, Array<React.ReactNode>]> {
const errorMetadataItem: [null, null, null] = [null, null, null] const errorMetadataItem: [null, null, null] = [null, null, null]
const errorConvention = errorType === 'redirect' ? undefined : errorType const errorConvention = errorType === 'redirect' ? undefined : errorType
const searchParams = createDynamicallyTrackedSearchParams(query)
const [error, metadata, viewport] = await resolveMetadata({ const [error, metadata, viewport] = await resolveMetadata({
tree, tree,
...@@ -199,7 +194,8 @@ async function getResolvedMetadata( ...@@ -199,7 +194,8 @@ async function getResolvedMetadata(
getDynamicParamFromSegment, getDynamicParamFromSegment,
errorConvention, errorConvention,
metadataContext, metadataContext,
createDynamicallyTrackedParams, createServerParamsForMetadata,
staticGenerationStore,
}) })
if (!error) { if (!error) {
return [null, createMetadataElements(metadata, viewport)] return [null, createMetadataElements(metadata, viewport)]
...@@ -219,7 +215,8 @@ async function getResolvedMetadata( ...@@ -219,7 +215,8 @@ async function getResolvedMetadata(
getDynamicParamFromSegment, getDynamicParamFromSegment,
errorConvention: 'not-found', errorConvention: 'not-found',
metadataContext, metadataContext,
createDynamicallyTrackedParams, createServerParamsForMetadata,
staticGenerationStore,
}) })
return [ return [
notFoundMetadataError || error, notFoundMetadataError || error,
......
...@@ -49,7 +49,11 @@ import { getTracer } from '../../server/lib/trace/tracer' ...@@ -49,7 +49,11 @@ import { getTracer } from '../../server/lib/trace/tracer'
import { ResolveMetadataSpan } from '../../server/lib/trace/constants' import { ResolveMetadataSpan } from '../../server/lib/trace/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import type { CreateDynamicallyTrackedParams } from '../../server/request/fallback-params' import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type {
Params,
CreateServerParamsForMetadata,
} from '../../server/request/params'
type StaticIcons = Pick<ResolvedIcons, 'icon' | 'apple'> type StaticIcons = Pick<ResolvedIcons, 'icon' | 'apple'>
...@@ -479,10 +483,11 @@ export async function resolveMetadataItems({ ...@@ -479,10 +483,11 @@ export async function resolveMetadataItems({
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
errorConvention, errorConvention,
createDynamicallyTrackedParams, createServerParamsForMetadata,
staticGenerationStore,
}: { }: {
tree: LoaderTree tree: LoaderTree
parentParams: { [key: string]: any } parentParams: Params
metadataItems: MetadataItems metadataItems: MetadataItems
errorMetadataItem: MetadataItems[number] errorMetadataItem: MetadataItems[number]
/** Provided tree can be nested subtree, this argument says what is the path of such subtree */ /** Provided tree can be nested subtree, this argument says what is the path of such subtree */
...@@ -490,7 +495,8 @@ export async function resolveMetadataItems({ ...@@ -490,7 +495,8 @@ export async function resolveMetadataItems({
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment
searchParams: ParsedUrlQuery searchParams: ParsedUrlQuery
errorConvention: 'not-found' | undefined errorConvention: 'not-found' | undefined
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
}): Promise<MetadataItems> { }): Promise<MetadataItems> {
const [segment, parallelRoutes, { page }] = tree const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix = [...treePrefix, segment] const currentTreePrefix = [...treePrefix, segment]
...@@ -501,17 +507,18 @@ export async function resolveMetadataItems({ ...@@ -501,17 +507,18 @@ export async function resolveMetadataItems({
/** /**
* Create object holding the parent params and current params * Create object holding the parent params and current params
*/ */
const currentParams = let currentParams = parentParams
// Handle null case where dynamic param is optional if (segmentParam && segmentParam.value !== null) {
segmentParam && segmentParam.value !== null currentParams = {
? { ...parentParams,
...parentParams, [segmentParam.param]: segmentParam.value,
[segmentParam.param]: segmentParam.value, }
} }
: // Pass through parent params to children
parentParams
const params = createDynamicallyTrackedParams(currentParams) const params = createServerParamsForMetadata(
currentParams,
staticGenerationStore
)
let layerProps: LayoutProps | PageProps let layerProps: LayoutProps | PageProps
if (isPage) { if (isPage) {
...@@ -548,7 +555,8 @@ export async function resolveMetadataItems({ ...@@ -548,7 +555,8 @@ export async function resolveMetadataItems({
searchParams, searchParams,
getDynamicParamFromSegment, getDynamicParamFromSegment,
errorConvention, errorConvention,
createDynamicallyTrackedParams, createServerParamsForMetadata,
staticGenerationStore,
}) })
} }
...@@ -891,10 +899,11 @@ export async function resolveMetadata({ ...@@ -891,10 +899,11 @@ export async function resolveMetadata({
searchParams, searchParams,
errorConvention, errorConvention,
metadataContext, metadataContext,
createDynamicallyTrackedParams, createServerParamsForMetadata,
staticGenerationStore,
}: { }: {
tree: LoaderTree tree: LoaderTree
parentParams: { [key: string]: any } parentParams: Params
metadataItems: MetadataItems metadataItems: MetadataItems
errorMetadataItem: MetadataItems[number] errorMetadataItem: MetadataItems[number]
/** Provided tree can be nested subtree, this argument says what is the path of such subtree */ /** Provided tree can be nested subtree, this argument says what is the path of such subtree */
...@@ -903,7 +912,8 @@ export async function resolveMetadata({ ...@@ -903,7 +912,8 @@ export async function resolveMetadata({
searchParams: { [key: string]: any } searchParams: { [key: string]: any }
errorConvention: 'not-found' | undefined errorConvention: 'not-found' | undefined
metadataContext: MetadataContext metadataContext: MetadataContext
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
}): Promise<[any, ResolvedMetadata, ResolvedViewport]> { }): Promise<[any, ResolvedMetadata, ResolvedViewport]> {
const resolvedMetadataItems = await resolveMetadataItems({ const resolvedMetadataItems = await resolveMetadataItems({
tree, tree,
...@@ -913,7 +923,8 @@ export async function resolveMetadata({ ...@@ -913,7 +923,8 @@ export async function resolveMetadata({
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
errorConvention, errorConvention,
createDynamicallyTrackedParams, createServerParamsForMetadata,
staticGenerationStore,
}) })
let error let error
let metadata: ResolvedMetadata = createDefaultMetadata() let metadata: ResolvedMetadata = createDefaultMetadata()
......
...@@ -385,8 +385,8 @@ async function generateDynamicRSCPayload( ...@@ -385,8 +385,8 @@ async function generateDynamicRSCPayload(
const { const {
componentMod: { componentMod: {
tree: loaderTree, tree: loaderTree,
createDynamicallyTrackedSearchParams, createServerSearchParamsForMetadata,
createDynamicallyTrackedParams, createServerParamsForMetadata,
}, },
getDynamicParamFromSegment, getDynamicParamFromSegment,
appUsingSizeAdjustment, appUsingSizeAdjustment,
...@@ -400,9 +400,13 @@ async function generateDynamicRSCPayload( ...@@ -400,9 +400,13 @@ async function generateDynamicRSCPayload(
if (!options?.skipFlight) { if (!options?.skipFlight) {
const preloadCallbacks: PreloadCallbacks = [] const preloadCallbacks: PreloadCallbacks = []
const searchParams = createServerSearchParamsForMetadata(
query,
staticGenerationStore
)
const [MetadataTree, getMetadataReady] = createMetadataComponents({ const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree: loaderTree, tree: loaderTree,
query, searchParams,
metadataContext: createTrackedMetadataContext( metadataContext: createTrackedMetadataContext(
url.pathname, url.pathname,
ctx.renderOpts, ctx.renderOpts,
...@@ -410,8 +414,8 @@ async function generateDynamicRSCPayload( ...@@ -410,8 +414,8 @@ async function generateDynamicRSCPayload(
), ),
getDynamicParamFromSegment, getDynamicParamFromSegment,
appUsingSizeAdjustment, appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams, createServerParamsForMetadata,
createDynamicallyTrackedParams, staticGenerationStore,
}) })
flightData = ( flightData = (
await walkTreeWithFlightRouterState({ await walkTreeWithFlightRouterState({
...@@ -546,8 +550,8 @@ async function getRSCPayload( ...@@ -546,8 +550,8 @@ async function getRSCPayload(
appUsingSizeAdjustment, appUsingSizeAdjustment,
componentMod: { componentMod: {
GlobalError, GlobalError,
createDynamicallyTrackedSearchParams, createServerSearchParamsForMetadata,
createDynamicallyTrackedParams, createServerParamsForMetadata,
}, },
requestStore: { url }, requestStore: { url },
staticGenerationStore, staticGenerationStore,
...@@ -558,10 +562,14 @@ async function getRSCPayload( ...@@ -558,10 +562,14 @@ async function getRSCPayload(
query query
) )
const searchParams = createServerSearchParamsForMetadata(
query,
staticGenerationStore
)
const [MetadataTree, getMetadataReady] = createMetadataComponents({ const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree, tree,
errorType: is404 ? 'not-found' : undefined, errorType: is404 ? 'not-found' : undefined,
query, searchParams,
metadataContext: createTrackedMetadataContext( metadataContext: createTrackedMetadataContext(
url.pathname, url.pathname,
ctx.renderOpts, ctx.renderOpts,
...@@ -569,8 +577,8 @@ async function getRSCPayload( ...@@ -569,8 +577,8 @@ async function getRSCPayload(
), ),
getDynamicParamFromSegment, getDynamicParamFromSegment,
appUsingSizeAdjustment, appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams, createServerParamsForMetadata,
createDynamicallyTrackedParams, staticGenerationStore,
}) })
const preloadCallbacks: PreloadCallbacks = [] const preloadCallbacks: PreloadCallbacks = []
...@@ -642,24 +650,29 @@ async function getErrorRSCPayload( ...@@ -642,24 +650,29 @@ async function getErrorRSCPayload(
appUsingSizeAdjustment, appUsingSizeAdjustment,
componentMod: { componentMod: {
GlobalError, GlobalError,
createDynamicallyTrackedSearchParams, createServerSearchParamsForMetadata,
createDynamicallyTrackedParams, createServerParamsForMetadata,
}, },
requestStore: { url }, requestStore: { url },
requestId, requestId,
staticGenerationStore,
} = ctx } = ctx
const searchParams = createServerSearchParamsForMetadata(
query,
staticGenerationStore
)
const [MetadataTree] = createMetadataComponents({ const [MetadataTree] = createMetadataComponents({
tree, tree,
searchParams,
// We create an untracked metadata context here because we can't postpone // We create an untracked metadata context here because we can't postpone
// again during the error render. // again during the error render.
metadataContext: createMetadataContext(url.pathname, ctx.renderOpts), metadataContext: createMetadataContext(url.pathname, ctx.renderOpts),
errorType, errorType,
query,
getDynamicParamFromSegment, getDynamicParamFromSegment,
appUsingSizeAdjustment, appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams, createServerParamsForMetadata,
createDynamicallyTrackedParams, staticGenerationStore,
}) })
const initialHead = ( const initialHead = (
...@@ -1829,7 +1842,9 @@ async function prerenderToStream( ...@@ -1829,7 +1842,9 @@ async function prerenderToStream(
let flightController = new AbortController() let flightController = new AbortController()
// We're not going to use the result of this render because the only time it could be used // We're not going to use the result of this render because the only time it could be used
// is if it completes in a microtask and that's likely very rare for any non-trivial app // is if it completes in a microtask and that's likely very rare for any non-trivial app
const firstAttemptRSCPayload = await getRSCPayload( const firstAttemptRSCPayload = await prerenderAsyncStorage.run(
prospectiveRenderPrerenderStore,
getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 res.statusCode === 404
...@@ -1895,7 +1910,9 @@ async function prerenderToStream( ...@@ -1895,7 +1910,9 @@ async function prerenderToStream(
reactServerIsDynamic = true reactServerIsDynamic = true
} }
} }
const finalAttemptRSCPayload = await getRSCPayload( const finalAttemptRSCPayload = await prerenderAsyncStorage.run(
finalRenderPrerenderStore,
getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 res.statusCode === 404
...@@ -2135,7 +2152,9 @@ async function prerenderToStream( ...@@ -2135,7 +2152,9 @@ async function prerenderToStream(
dynamicTracking, dynamicTracking,
} }
const firstAttemptRSCPayload = await getRSCPayload( const firstAttemptRSCPayload = await prerenderAsyncStorage.run(
prospectiveRenderPrerenderStore,
getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 res.statusCode === 404
...@@ -2199,7 +2218,9 @@ async function prerenderToStream( ...@@ -2199,7 +2218,9 @@ async function prerenderToStream(
dynamicTracking, dynamicTracking,
} }
const finalAttemptRSCPayload = await getRSCPayload( const finalAttemptRSCPayload = await prerenderAsyncStorage.run(
finalRenderPrerenderStore,
getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 res.statusCode === 404
...@@ -2354,7 +2375,13 @@ async function prerenderToStream( ...@@ -2354,7 +2375,13 @@ async function prerenderToStream(
controller: null, controller: null,
dynamicTracking, dynamicTracking,
} }
const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404) const RSCPayload = await prerenderAsyncStorage.run(
reactServerPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
const reactServerResult = (reactServerPrerenderResult = const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResultFromRender( await createReactServerPrerenderResultFromRender(
prerenderAsyncStorage.run( prerenderAsyncStorage.run(
......
...@@ -27,7 +27,13 @@ import React from 'react' ...@@ -27,7 +27,13 @@ import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context' import { DynamicServerError } from '../../client/components/hooks-server-context'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { prerenderAsyncStorage } from './prerender-async-storage.external' import {
isDynamicIOPrerender,
prerenderAsyncStorage,
type PrerenderStore,
} from './prerender-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
const hasPostpone = typeof React.unstable_postpone === 'function' const hasPostpone = typeof React.unstable_postpone === 'function'
...@@ -107,7 +113,7 @@ export function markCurrentScopeAsDynamic( ...@@ -107,7 +113,7 @@ export function markCurrentScopeAsDynamic(
// current render because something dynamic is being used. // current render because something dynamic is being used.
// This won't throw so we still need to fall through to determine if/how we handle // This won't throw so we still need to fall through to determine if/how we handle
// this specific dynamic request. // this specific dynamic request.
abortRSCRender(prerenderStore.controller, store.route, expression) abortRender(prerenderStore.controller, store.route, expression)
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression) errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else if (prerenderStore.cacheSignal) { } else if (prerenderStore.cacheSignal) {
// we're prerendering with dynamicIO but we don't want to eagerly abort this // we're prerendering with dynamicIO but we don't want to eagerly abort this
...@@ -116,9 +122,9 @@ export function markCurrentScopeAsDynamic( ...@@ -116,9 +122,9 @@ export function markCurrentScopeAsDynamic(
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression) errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else { } else {
postponeWithTracking( postponeWithTracking(
prerenderStore.dynamicTracking,
store.route, store.route,
expression expression,
prerenderStore.dynamicTracking
) )
} }
} else { } else {
...@@ -152,7 +158,7 @@ export function trackFallbackParamAccessed( ...@@ -152,7 +158,7 @@ export function trackFallbackParamAccessed(
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
if (!prerenderStore) return if (!prerenderStore) return
postponeWithTracking(prerenderStore.dynamicTracking, store.route, expression) postponeWithTracking(store.route, expression, prerenderStore.dynamicTracking)
} }
/** /**
...@@ -185,7 +191,7 @@ export function trackDynamicDataAccessed( ...@@ -185,7 +191,7 @@ export function trackDynamicDataAccessed(
// current render because something dynamic is being used. // current render because something dynamic is being used.
// This won't throw so we still need to fall through to determine if/how we handle // This won't throw so we still need to fall through to determine if/how we handle
// this specific dynamic request. // this specific dynamic request.
abortRSCRender(prerenderStore.controller, store.route, expression) abortRender(prerenderStore.controller, store.route, expression)
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression) errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else if (prerenderStore.cacheSignal) { } else if (prerenderStore.cacheSignal) {
// we're prerendering with dynamicIO but we don't want to eagerly abort this // we're prerendering with dynamicIO but we don't want to eagerly abort this
...@@ -194,9 +200,9 @@ export function trackDynamicDataAccessed( ...@@ -194,9 +200,9 @@ export function trackDynamicDataAccessed(
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression) errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else { } else {
postponeWithTracking( postponeWithTracking(
prerenderStore.dynamicTracking,
store.route, store.route,
expression expression,
prerenderStore.dynamicTracking
) )
} }
} else { } else {
...@@ -215,6 +221,90 @@ export function trackDynamicDataAccessed( ...@@ -215,6 +221,90 @@ export function trackDynamicDataAccessed(
} }
} }
/**
* This function is meant to be used when prerendering without dynamicIO or PPR.
* When called during a build it will cause Next.js to consider the route as dynamic.
*
* @internal
*/
export function throwToInterruptStaticGeneration(
expression: string,
store: StaticGenerationStore
): never {
store.revalidate = 0
// We aren't prerendering but we are generating a static page. We need to bail out of static generation
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
}
/**
* This function should be used to track whether something dynamic happened even when
* we are in a dynamic render. This is useful for Dev where all renders are dynamic but
* we still track whether dynamic APIs were accessed for helpful messaging
*
* @internal
*/
export function trackDynamicDataInDynamicRender(store: StaticGenerationStore) {
store.revalidate = 0
}
// Despite it's name we don't actually abort unless we have a controller to call abort on
// There are times when we let a prerender run long to discover caches where we want the semantics
// of tracking dynamic access without terminating the prerender early
function abortOnSynchronousDynamicDataAccess(
route: string,
expression: string,
prerenderStore: PrerenderStore
): void {
const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`
const error = createPrerenderInterruptedError(reason)
if (prerenderStore.controller) {
prerenderStore.controller.abort(error)
}
const dynamicTracking = prerenderStore.dynamicTracking
if (dynamicTracking) {
dynamicTracking.dynamicAccesses.push({
// When we aren't debugging, we don't need to create another error for the
// stack trace.
stack: dynamicTracking.isDebugDynamicAccesses
? new Error().stack
: undefined,
expression,
})
}
}
/**
* use this function when prerendering with dynamicIO. If we are doing a
* prospective prerender we don't actually abort because we want to discover
* all caches for the shell. If this is the actual prerender we do abort.
*
* This function accepts a prerenderStore but the caller should ensure we're
* actually running in dynamicIO mode.
*
*
* @internal
*/
export function abortAndThrowOnSynchronousDynamicDataAccess(
route: string,
expression: string,
prerenderStore: PrerenderStore
): never {
abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
throw new Error(
`Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`
)
}
/** /**
* This component will call `React.postpone` that throws the postponed error. * This component will call `React.postpone` that throws the postponed error.
*/ */
...@@ -225,7 +315,7 @@ type PostponeProps = { ...@@ -225,7 +315,7 @@ type PostponeProps = {
export function Postpone({ reason, route }: PostponeProps): never { export function Postpone({ reason, route }: PostponeProps): never {
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = prerenderAsyncStorage.getStore()
const dynamicTracking = prerenderStore?.dynamicTracking || null const dynamicTracking = prerenderStore?.dynamicTracking || null
postponeWithTracking(dynamicTracking, route, reason) postponeWithTracking(route, reason, dynamicTracking)
} }
function errorWithTracking( function errorWithTracking(
...@@ -251,10 +341,10 @@ function errorWithTracking( ...@@ -251,10 +341,10 @@ function errorWithTracking(
throw createPrerenderInterruptedError(reason) throw createPrerenderInterruptedError(reason)
} }
function postponeWithTracking( export function postponeWithTracking(
dynamicTracking: null | DynamicTrackingState,
route: string, route: string,
expression: string expression: string,
dynamicTracking: null | DynamicTrackingState
): never { ): never {
assertPostpone() assertPostpone()
if (dynamicTracking) { if (dynamicTracking) {
...@@ -323,7 +413,7 @@ export function isPrerenderInterruptedError(error: unknown) { ...@@ -323,7 +413,7 @@ export function isPrerenderInterruptedError(error: unknown) {
) )
} }
function abortRSCRender( function abortRender(
controller: AbortController, controller: AbortController,
route: string, route: string,
expression: string expression: string
...@@ -409,3 +499,54 @@ export function createPostponedAbortSignal(reason: string): AbortSignal { ...@@ -409,3 +499,54 @@ export function createPostponedAbortSignal(reason: string): AbortSignal {
} }
return controller.signal return controller.signal
} }
export function annotateDynamicAccess(
expression: string,
prerenderStore: PrerenderStore
) {
const dynamicTracking = prerenderStore.dynamicTracking
if (dynamicTracking) {
dynamicTracking.dynamicAccesses.push({
stack: dynamicTracking.isDebugDynamicAccesses
? new Error().stack
: undefined,
expression,
})
}
}
export function useDynamicRouteParams(expression: string) {
if (typeof window === 'undefined') {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (
staticGenerationStore &&
staticGenerationStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0
) {
// There are fallback route params, we should track these as dynamic
// accesses.
const prerenderStore = prerenderAsyncStorage.getStore()
if (prerenderStore) {
// We're prerendering with dynamicIO or PPR or both
if (isDynamicIOPrerender(prerenderStore)) {
// We are in a prerender with dynamicIO semantics
// We are going to hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole
React.use(makeHangingPromise())
} else {
// We're prerendering with PPR
postponeWithTracking(
staticGenerationStore.route,
expression,
prerenderStore.dynamicTracking
)
}
} else {
// We're prerendering in legacy mode
throwToInterruptStaticGeneration(expression, staticGenerationStore)
}
}
}
}
...@@ -18,10 +18,15 @@ import { actionAsyncStorage } from '../../client/components/action-async-storage ...@@ -18,10 +18,15 @@ import { actionAsyncStorage } from '../../client/components/action-async-storage
import { ClientPageRoot } from '../../client/components/client-page' import { ClientPageRoot } from '../../client/components/client-page'
import { ClientSegmentRoot } from '../../client/components/client-segment' import { ClientSegmentRoot } from '../../client/components/client-segment'
import { import {
createUntrackedSearchParams, createServerSearchParamsForServerPage,
createDynamicallyTrackedSearchParams, createPrerenderSearchParamsForClientPage,
createServerSearchParamsForMetadata,
} from '../request/search-params' } from '../request/search-params'
import { createDynamicallyTrackedParams } from '../request/fallback-params' import {
createServerParamsForServerSegment,
createServerParamsForMetadata,
createPrerenderParamsForClientSegment,
} from '../request/params'
import * as serverHooks from '../../client/components/hooks-server-context' import * as serverHooks from '../../client/components/hooks-server-context'
import { NotFoundBoundary } from '../../client/components/not-found-boundary' import { NotFoundBoundary } from '../../client/components/not-found-boundary'
import { patchFetch as _patchFetch } from '../lib/patch-fetch' import { patchFetch as _patchFetch } from '../lib/patch-fetch'
...@@ -48,9 +53,12 @@ export { ...@@ -48,9 +53,12 @@ export {
staticGenerationAsyncStorage, staticGenerationAsyncStorage,
requestAsyncStorage, requestAsyncStorage,
actionAsyncStorage, actionAsyncStorage,
createUntrackedSearchParams, createServerSearchParamsForServerPage,
createDynamicallyTrackedSearchParams, createServerSearchParamsForMetadata,
createDynamicallyTrackedParams, createPrerenderSearchParamsForClientPage,
createServerParamsForServerSegment,
createServerParamsForMetadata,
createPrerenderParamsForClientSegment,
serverHooks, serverHooks,
preloadStyle, preloadStyle,
preloadFont, preloadFont,
......
...@@ -35,5 +35,9 @@ export type PrerenderStore = { ...@@ -35,5 +35,9 @@ export type PrerenderStore = {
readonly dynamicTracking: null | DynamicTrackingState readonly dynamicTracking: null | DynamicTrackingState
} }
export function isDynamicIOPrerender(prerenderStore: PrerenderStore): boolean {
return !!(prerenderStore.controller || prerenderStore.cacheSignal)
}
export type PrerenderAsyncStorage = AsyncLocalStorage<PrerenderStore> export type PrerenderAsyncStorage = AsyncLocalStorage<PrerenderStore>
export { prerenderAsyncStorage } export { prerenderAsyncStorage }
import type { __ApiPreviewProps } from './api-utils' import type { __ApiPreviewProps } from './api-utils'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher' import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from '../server/request/params' import type { Params } from './request/params'
import { import {
type FallbackRouteParams, type FallbackRouteParams,
getFallbackRouteParams, getFallbackRouteParams,
......
function hangForever() {}
/**
* This function constructs a promise that will never resolve. This is primarily
* useful for dynamicIO where we use promise resolution timing to determine which
* parts of a render can be included in a prerender.
*
* @internal
*/
export function makeHangingPromise<T>(): Promise<T> {
return new Promise(hangForever)
}
This diff is collapsed.
import type { DraftModeProvider } from '../async-storage/draft-mode-provider' import { getExpectedRequestStore } from '../../client/components/request-async-storage.external'
import type { DraftModeProvider } from '../../server/async-storage/draft-mode-provider'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering' import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering'
export class DraftMode { /**
* 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:
*
* ```
* // TODO [sync-draftMode-usage]
* ```
* 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> {
const callingExpression = 'draftMode'
const requestStore = getExpectedRequestStore(callingExpression)
if (process.env.NODE_ENV === 'development') {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const route = staticGenerationStore?.route
return createExoticDraftModeWithDevWarnings(requestStore.draftMode, route)
} else {
return createExoticDraftMode(requestStore.draftMode)
}
}
interface CacheLifetime {}
const CachedDraftModes = new WeakMap<CacheLifetime, Promise<DraftMode>>()
function createExoticDraftMode(
underlyingProvider: DraftModeProvider
): Promise<DraftMode> {
const cachedDraftMode = CachedDraftModes.get(underlyingProvider)
if (cachedDraftMode) {
return cachedDraftMode
}
const instance = new DraftMode(underlyingProvider)
const promise = Promise.resolve(instance)
CachedDraftModes.set(underlyingProvider, promise)
Object.defineProperty(promise, 'isEnabled', {
get() {
return instance.isEnabled
},
set(newValue) {
Object.defineProperty(promise, 'isEnabled', {
value: newValue,
writable: true,
enumerable: true,
})
},
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: DraftModeProvider,
route: undefined | string
): Promise<DraftMode> {
const cachedDraftMode = CachedDraftModes.get(underlyingProvider)
if (cachedDraftMode) {
return cachedDraftMode
}
const instance = new DraftMode(underlyingProvider)
const promise = Promise.resolve(instance)
CachedDraftModes.set(underlyingProvider, promise)
Object.defineProperty(promise, 'isEnabled', {
get() {
const expression = 'draftMode().isEnabled'
warnForSyncAccess(route, expression)
return instance.isEnabled
},
set(newValue) {
Object.defineProperty(promise, 'isEnabled', {
value: newValue,
writable: true,
enumerable: true,
})
},
enumerable: true,
configurable: true,
})
Object.defineProperty(promise, 'enable', {
value: function get() {
const expression = 'draftMode().enable()'
warnForSyncAccess(route, expression)
return instance.enable.apply(instance, arguments as any)
},
})
Object.defineProperty(promise, 'disable', {
value: function get() {
const expression = 'draftMode().disable()'
warnForSyncAccess(route, expression)
return instance.disable.apply(instance, arguments as any)
},
})
return promise
}
class DraftMode {
/** /**
* @internal - this declaration is stripped via `tsc --stripInternal` * @internal - this declaration is stripped via `tsc --stripInternal`
*/ */
...@@ -34,3 +159,10 @@ export class DraftMode { ...@@ -34,3 +159,10 @@ export class DraftMode {
return this._provider.disable() return this._provider.disable()
} }
} }
function warnForSyncAccess(route: undefined | string, expression: string) {
const prefix = route ? ` In route ${route} a ` : 'A '
console.error(
`${prefix}\`draftMode()\` property was accessed directly with \`${expression}\`. \`draftMode()\` now returns a Promise and the return value should be awaited before accessing properties of the underlying draftMode object. In this version of Next.js direct access to \`${expression}\` is still supported to facilitate migration but in a future version you will be required to await the result. If this \`draftMode()\` use is inside an async function await the return value before accessing attempting iteration. If this use is inside a synchronous function then convert the function to async or await the call from outside this function and pass the result in.`
)
}
import { trackFallbackParamAccessed } from '../app-render/dynamic-rendering'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import type { Params } from './params'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
export type FallbackRouteParams = ReadonlyMap<string, string> export type FallbackRouteParams = ReadonlyMap<string, string>
...@@ -41,57 +37,3 @@ export function getFallbackRouteParams( ...@@ -41,57 +37,3 @@ export function getFallbackRouteParams(
return params return params
} }
export type CreateDynamicallyTrackedParams =
typeof createDynamicallyTrackedParams
export function createDynamicallyTrackedParams(params: Params): Params {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (
!staticGenerationStore ||
!staticGenerationStore.isStaticGeneration ||
!staticGenerationStore.fallbackRouteParams ||
staticGenerationStore.fallbackRouteParams.size === 0
) {
return params
}
// If there are no unknown route params, we can just return the params.
const { fallbackRouteParams } = staticGenerationStore
return new Proxy(params as Params, {
get(target, prop, receiver) {
// If the property is in the params object, we should track the access if
// it's an unknown dynamic param.
if (
typeof prop === 'string' &&
prop in params &&
fallbackRouteParams.has(prop)
) {
trackFallbackParamAccessed(staticGenerationStore, `params.${prop}`)
}
return ReflectAdapter.get(target, prop, receiver)
},
has(target, prop) {
if (
typeof prop === 'string' &&
prop in params &&
fallbackRouteParams.has(prop)
) {
trackFallbackParamAccessed(staticGenerationStore, `params.${prop}`)
}
return ReflectAdapter.has(target, prop)
},
ownKeys(target) {
for (const key in params) {
if (fallbackRouteParams.has(key)) {
trackFallbackParamAccessed(staticGenerationStore, 'params')
}
}
return Reflect.ownKeys(target)
},
})
}
This diff is collapsed.
import type { Params } from './params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { InvariantError } from '../../shared/lib/invariant-error'
import { describeStringPropertyAccess } from './utils'
export function createRenderParamsFromClient(underlyingParams: Params) {
if (process.env.NODE_ENV === 'development') {
return makeDynamicallyTrackedExoticParamsWithDevWarnings(underlyingParams)
} else {
return makeUntrackedExoticParams(underlyingParams)
}
}
interface CacheLifetime {}
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.defineProperties(promise, {
status: {
value: 'fulfilled',
writable: true,
},
value: {
value: underlyingParams,
writable: true,
},
})
Object.keys(underlyingParams).forEach((prop) => {
switch (prop) {
case 'then':
case 'value':
case 'status': {
// These properties cannot be shadowed with a search param because they
// are necessary for ReactPromise's to work correctly with `use`
break
}
default: {
;(promise as any)[prop] = underlyingParams[prop]
}
}
})
return promise
}
function makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams: Params
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
return cachedParams
}
const promise = Promise.resolve(underlyingParams)
Object.defineProperties(promise, {
status: {
value: 'fulfilled',
writable: true,
},
value: {
value: underlyingParams,
writable: true,
},
})
const proxiedProperties = new Set<string>()
const unproxiedProperties: Array<string> = []
Object.keys(underlyingParams).forEach((prop) => {
switch (prop) {
case 'then':
case 'value':
case 'status': {
// These properties cannot be shadowed with a search param because they
// are necessary for ReactPromise's to work correctly with `use`
unproxiedProperties.push(prop)
break
}
default: {
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) ||
// We are accessing a property that doesn't exist on the promise nor the underlying
Reflect.has(target, prop) === false
) {
const expression = describeStringPropertyAccess('params', prop)
warnForSyncAccess(expression)
}
}
return ReflectAdapter.get(target, prop, receiver)
},
ownKeys(target) {
warnForEnumeration(unproxiedProperties)
return Reflect.ownKeys(target)
},
})
CachedParams.set(underlyingParams, proxiedPromise)
return proxiedPromise
}
function warnForSyncAccess(expression: string) {
console.error(
`A param property was accessed directly with ${expression}. \`params\` is now a Promise and should be awaited 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 await \`params\`. If this use is inside an async function await it. If this use is inside a synchronous function then convert the function to async or await it from outside this function and pass the result in.`
)
}
function warnForEnumeration(missingProperties: Array<string>) {
if (missingProperties.length) {
const describedMissingProperties =
describeListOfPropertyNames(missingProperties)
console.error(
`params are being enumerated incompletely with \`{...params}\`, \`Object.keys(params)\`, or similar. The following properties were not copied: ${describedMissingProperties}. \`params\` is now a Promise, however in the current version of Next.js direct access to the underlying params object is still supported to facilitate migration to the new type. param names that conflict with Promise properties cannot be accessed directly and must be accessed by first awaiting the \`params\` promise.`
)
} else {
console.error(
`params are being enumerated with \`{...params}\`, \`Object.keys(params)\`, or similar. \`params\` is now a Promise, however in the current version of Next.js direct access to the underlying params object is still supported to facilitate migration to the new type. You should update your code to await \`params\` before accessing its properties.`
)
}
}
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
}
}
}
This diff is collapsed.
import type { SearchParams } from './search-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
describeStringPropertyAccess,
describeHasCheckingStringProperty,
} from './utils'
export function createRenderSearchParamsFromClient(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
if (process.env.NODE_ENV === 'development') {
return makeUntrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams
)
} else {
return makeUntrackedExoticSearchParams(underlyingSearchParams)
}
}
interface CacheLifetime {}
const CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()
function makeUntrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
return cachedSearchParams
}
const promise = Promise.resolve(underlyingSearchParams)
Object.defineProperties(promise, {
status: {
value: 'fulfilled',
},
value: {
value: underlyingSearchParams,
},
})
Object.keys(underlyingSearchParams).forEach((prop) => {
if (Reflect.has(promise, prop)) {
// We can't assign a value over a property on the promise. The only way to
// access this is if you await the promise and recover the underlying searchParams object.
} else {
Object.defineProperty(promise, prop, {
value: underlyingSearchParams[prop],
writable: false,
enumerable: true,
})
}
})
const proxiedPromise = new Proxy(promise, {
get(target, prop, receiver) {
if (Reflect.has(target, prop)) {
return ReflectAdapter.get(target, prop, receiver)
} else if (typeof prop === 'symbol') {
return undefined
} else {
const expression = describeStringPropertyAccess('searchParams', prop)
warnForSyncAccess(expression)
return underlyingSearchParams[prop]
}
},
has(target, prop) {
if (Reflect.has(target, prop)) {
return true
} else if (typeof prop === 'symbol') {
// searchParams never has symbol properties containing searchParam data
// and we didn't match above so we just return false here.
return false
} else {
const expression = describeHasCheckingStringProperty(
'searchParams',
prop
)
warnForSyncAccess(expression)
return Reflect.has(underlyingSearchParams, prop)
}
},
ownKeys(target) {
warnForSyncSpread()
return Reflect.ownKeys(target)
},
})
CachedSearchParams.set(underlyingSearchParams, proxiedPromise)
return proxiedPromise
}
function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const promise = Promise.resolve(underlyingSearchParams)
Object.defineProperties(promise, {
status: {
value: 'fulfilled',
},
value: {
value: underlyingSearchParams,
},
})
Object.keys(underlyingSearchParams).forEach((prop) => {
if (Reflect.has(promise, prop)) {
// We can't assign a value over a property on the promise. The only way to
// access this is if you await the promise and recover the underlying searchParams object.
} else {
Object.defineProperty(promise, prop, {
value: underlyingSearchParams[prop],
writable: false,
enumerable: true,
})
}
})
return promise
}
function warnForSyncAccess(expression: string) {
console.error(
`A searchParam property was accessed directly with ${expression}. \`searchParams\` is now a Promise and should be awaited before accessing properties of the underlying searchParams object. In this version of Next.js direct access to searchParam properties is still supported to facilitate migration but in a future version you will be required to await \`searchParams\`. If this use is inside an async function await it. If this use is inside a synchronous function then convert the function to async or await it from outside this function and pass the result in.`
)
}
function warnForSyncSpread() {
console.error(
`the keys of \`searchParams\` were accessed through something like \`Object.keys(searchParams)\` or \`{...searchParams}\`. \`searchParams\` is now a Promise and should be awaited before accessing properties of the underlying searchParams object. In this version of Next.js direct access to searchParam properties is still supported to facilitate migration but in a future version you will be required to await \`searchParams\`. If this use is inside an async function await it. If this use is inside a synchronous function then convert the function to async or await it from outside this function and pass the result in.`
)
}
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
/**
* React annotates Promises with extra properties to make unwrapping them synchronous
* after they have resolved. We sometimes create promises that are compatible with this
* internal implementation detail when we want to construct a promise that is already resolved.
*
* @internal
*/
export function makeResolvedReactPromise<T>(value: T): Promise<T> {
const promise = Promise.resolve(value)
;(promise as any).status = 'fulfilled'
;(promise as any).value = value
return promise
}
// This regex will have fast negatives meaning valid identifiers may not pass
// this test. However this is only used during static generation to provide hints
// about why a page bailed out of some or all prerendering and we can use bracket notation
// for example while `ಠ_ಠ` is a valid identifier it's ok to print `searchParams['ಠ_ಠ']`
// even if this would have been fine too `searchParams.ಠ_ಠ`
const isDefinitelyAValidIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
export function describeStringPropertyAccess(target: string, prop: string) {
if (isDefinitelyAValidIdentifier.test(prop)) {
return `\`${target}.${prop}\``
}
return `\`${target}[${JSON.stringify(prop)}]\``
}
export function describeHasCheckingStringProperty(
target: string,
prop: string
) {
const stringifiedProp = JSON.stringify(prop)
return `\`Reflect.has(${target}, ${stringifiedProp}\`, \`${stringifiedProp} in ${target}\`, or similar`
}
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(
route: string,
expression: string
): never {
throw new StaticGenBailoutError(
`Route ${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`
)
}
...@@ -68,6 +68,7 @@ import { ReflectAdapter } from '../../web/spec-extension/adapters/reflect' ...@@ -68,6 +68,7 @@ import { ReflectAdapter } from '../../web/spec-extension/adapters/reflect'
import type { RenderOptsPartial } from '../../app-render/types' import type { RenderOptsPartial } from '../../app-render/types'
import { CacheSignal } from '../../app-render/cache-signal' import { CacheSignal } from '../../app-render/cache-signal'
import { scheduleImmediate } from '../../../lib/scheduler' import { scheduleImmediate } from '../../../lib/scheduler'
import { createServerParamsForRoute } from '../../request/params'
/** /**
* The AppRouteModule is the type of the module exported by the bundled App * The AppRouteModule is the type of the module exported by the bundled App
...@@ -90,7 +91,7 @@ export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext { ...@@ -90,7 +91,7 @@ export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
* second argument. * second argument.
*/ */
type AppRouteHandlerFnContext = { type AppRouteHandlerFnContext = {
params?: Record<string, string | string[]> params?: Promise<Record<string, string | string[] | undefined>>
} }
/** /**
...@@ -402,9 +403,12 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -402,9 +403,12 @@ export class AppRouteRouteModule extends RouteModule<
prerenderAsyncStorage: this.prerenderAsyncStorage, prerenderAsyncStorage: this.prerenderAsyncStorage,
}) })
const handlerContext = { const handlerContext: AppRouteHandlerFnContext = {
params: context.params params: context.params
? parsedUrlQueryToParams(context.params) ? createServerParamsForRoute(
parsedUrlQueryToParams(context.params),
staticGenerationStore
)
: undefined, : undefined,
} }
......
...@@ -19,6 +19,9 @@ export class ReadonlyRequestCookiesError extends Error { ...@@ -19,6 +19,9 @@ export class ReadonlyRequestCookiesError extends Error {
} }
} }
// We use this to type some APIs but we don't construct instances directly
export type { ResponseCookies }
// The `cookies()` API is a mix of request and response cookies. For `.get()` methods, // The `cookies()` API is a mix of request and response cookies. For `.get()` methods,
// we want to return the request cookie if it exists. For mutative methods like `.set()`, // we want to return the request cookie if it exists. For mutative methods like `.set()`,
// we want to return the response cookie. // we want to return the response cookie.
......
...@@ -21,8 +21,8 @@ describe('dynamic = "error" in devmode', () => { ...@@ -21,8 +21,8 @@ describe('dynamic = "error" in devmode', () => {
import Component from '../../index' import Component from '../../index'
export default function Page() { export default async function Page() {
cookies() await cookies()
return <Component /> return <Component />
} }
......
...@@ -875,8 +875,8 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -875,8 +875,8 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
<Segment> <Segment>
<ClientPageRoot props={{params:{}, ...}} Component={function Page}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={{}} searchParams={{}}> <Page params={Promise} searchParams={Promise}>
<div> <div>
<div> <div>
<div> <div>
...@@ -895,8 +895,8 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -895,8 +895,8 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...> <InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
<Segment> <Segment>
<ClientPageRoot props={{params:{}, ...}} Component={function Page}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={{}} searchParams={{}}> <Page params={Promise} searchParams={Promise}>
<div> <div>
<div> <div>
<div> <div>
......
...@@ -6,8 +6,8 @@ import { redirect } from 'next/navigation' ...@@ -6,8 +6,8 @@ import { redirect } from 'next/navigation'
import { headers, cookies } from 'next/headers' import { headers, cookies } from 'next/headers'
export async function getHeaders() { export async function getHeaders() {
console.log('accept header:', headers().get('accept')) console.log('accept header:', (await headers()).get('accept'))
cookies().set('test-cookie', Date.now()) ;(await cookies()).set('test-cookie', Date.now())
} }
export async function inc(value) { export async function inc(value) {
......
...@@ -3,14 +3,15 @@ import { cookies } from 'next/headers' ...@@ -3,14 +3,15 @@ import { cookies } from 'next/headers'
export const revalidate = 1 export const revalidate = 1
export const GET = async () => { export const GET = async () => {
cookies().set('foo', 'foo1') const localCookies = await cookies()
cookies().set('bar', 'bar1') localCookies.set('foo', 'foo1')
localCookies.set('bar', 'bar1')
// Key, value, options // Key, value, options
cookies().set('test1', 'value1', { secure: true }) localCookies.set('test1', 'value1', { secure: true })
// One object // One object
cookies().set({ localCookies.set({
name: 'test2', name: 'test2',
value: 'value2', value: 'value2',
httpOnly: true, httpOnly: true,
......
...@@ -4,7 +4,7 @@ import { headers, cookies } from 'next/headers' ...@@ -4,7 +4,7 @@ import { headers, cookies } from 'next/headers'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export async function setCookieWithMaxAge() { export async function setCookieWithMaxAge() {
cookies().set({ ;(await cookies()).set({
name: 'foo', name: 'foo',
value: 'bar', value: 'bar',
maxAge: 1000, maxAge: 1000,
...@@ -12,19 +12,20 @@ export async function setCookieWithMaxAge() { ...@@ -12,19 +12,20 @@ export async function setCookieWithMaxAge() {
} }
export async function getCookie(name) { export async function getCookie(name) {
return cookies().get(name) return (await cookies()).get(name)
} }
export async function getHeader(name) { export async function getHeader(name) {
return headers().get(name) return (await headers()).get(name)
} }
export async function setCookie(name, value) { export async function setCookie(name, value) {
cookies().set(name, value) const localCookies = await cookies()
return cookies().get(name) localCookies.set(name, value)
return localCookies.get(name)
} }
export async function setCookieAndRedirect(name, value, path, type) { export async function setCookieAndRedirect(name, value, path, type) {
cookies().set(name, value) ;(await cookies()).set(name, value)
redirect(path, type) redirect(path, type)
} }
...@@ -3,7 +3,7 @@ import { cookies } from 'next/headers' ...@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
export function validator(action) { export function validator(action) {
return async function (arg) { return async function (arg) {
'use server' 'use server'
const auth = cookies().get('auth') const auth = (await cookies()).get('auth')
if (auth?.value !== '1') { if (auth?.value !== '1') {
throw new Error('Unauthorized request') throw new Error('Unauthorized request')
} }
......
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
import Link from 'next/link' import Link from 'next/link'
export default function Page() { export default async function Page() {
return ( return (
<> <>
<Link id="back" href="/mutate-cookie"> <Link id="back" href="/mutate-cookie">
back back
</Link> </Link>
<p id="value">{cookies().get('test-cookie2')?.value}</p> <p id="value">{(await cookies()).get('test-cookie2')?.value}</p>
</> </>
) )
} }
...@@ -3,16 +3,16 @@ import Link from 'next/link' ...@@ -3,16 +3,16 @@ import Link from 'next/link'
async function updateCookie() { async function updateCookie() {
'use server' 'use server'
cookies().set('test-cookie2', Date.now()) ;(await cookies()).set('test-cookie2', Date.now())
} }
export default function Page() { export default async function Page() {
return ( return (
<> <>
<Link id="page-2" href="/mutate-cookie/page-2"> <Link id="page-2" href="/mutate-cookie/page-2">
to page2 to page2
</Link> </Link>
<p id="value">{cookies().get('test-cookie2')?.value}</p> <p id="value">{(await cookies()).get('test-cookie2')?.value}</p>
<form action={updateCookie}> <form action={updateCookie}>
<button id="update-cookie" type="submit"> <button id="update-cookie" type="submit">
Update Cookie Update Cookie
......
import { cookies } from 'next/dist/server/request/headers' import { cookies } from 'next/headers'
export default function Page() { export default async function Page() {
const redirectCookie = cookies().get('redirect') const redirectCookie = (await cookies()).get('redirect')
return ( return (
<div> <div>
<div id="redirected-cookie"> <div id="redirected-cookie">
......
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export default function Page({ searchParams }) { export default async function Page({ searchParams }) {
const foo = cookies().get('foo') const foo = (await cookies()).get('foo')
const bar = cookies().get('bar') const bar = (await cookies()).get('bar')
return ( return (
<div> <div>
<h1> <h1>
...@@ -12,8 +12,8 @@ export default function Page({ searchParams }) { ...@@ -12,8 +12,8 @@ export default function Page({ searchParams }) {
<form <form
action={async () => { action={async () => {
'use server' 'use server'
cookies().delete('foo') ;(await cookies()).delete('foo')
cookies().set('bar', '2') ;(await cookies()).set('bar', '2')
redirect('/redirects/action-redirect/redirect-target') redirect('/redirects/action-redirect/redirect-target')
}} }}
> >
...@@ -21,7 +21,7 @@ export default function Page({ searchParams }) { ...@@ -21,7 +21,7 @@ export default function Page({ searchParams }) {
Set Cookies and Redirect Set Cookies and Redirect
</button> </button>
</form> </form>
<h2>baz={searchParams.baz ?? ''}</h2> <h2>baz={(await searchParams).baz ?? ''}</h2>
<form <form
action={async () => { action={async () => {
'use server' 'use server'
......
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
export default function Page({ searchParams }) { export default async function Page({ searchParams }) {
const foo = cookies().get('foo') const foo = (await cookies()).get('foo')
const bar = cookies().get('bar') const bar = (await cookies()).get('bar')
const actionHeader = headers().get('next-action') const actionHeader = (await headers()).get('next-action')
if (actionHeader) { if (actionHeader) {
throw new Error('Action header should not be present') throw new Error('Action header should not be present')
} }
...@@ -12,7 +12,7 @@ export default function Page({ searchParams }) { ...@@ -12,7 +12,7 @@ export default function Page({ searchParams }) {
<h1> <h1>
foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''} foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''}
</h1> </h1>
<h2>baz={searchParams.baz ?? ''}</h2> <h2>baz={(await searchParams).baz ?? ''}</h2>
</div> </div>
) )
} }
...@@ -34,7 +34,7 @@ export default async function Page() { ...@@ -34,7 +34,7 @@ export default async function Page() {
<p> <p>
random cookie:{' '} random cookie:{' '}
<span id="random-cookie"> <span id="random-cookie">
{JSON.stringify(cookies().get('random'))} {JSON.stringify((await cookies()).get('random'))}
</span> </span>
</p> </p>
</> </>
......
...@@ -63,7 +63,7 @@ export default async function Page() { ...@@ -63,7 +63,7 @@ export default async function Page() {
<p> <p>
random cookie:{' '} random cookie:{' '}
<span id="random-cookie"> <span id="random-cookie">
{JSON.stringify(cookies().get('random'))} {JSON.stringify((await cookies()).get('random'))}
</span> </span>
</p> </p>
<form> <form>
...@@ -71,7 +71,7 @@ export default async function Page() { ...@@ -71,7 +71,7 @@ export default async function Page() {
id="set-cookie" id="set-cookie"
formAction={async () => { formAction={async () => {
'use server' 'use server'
cookies().set('random', `${Math.random()}`) ;(await cookies()).set('random', `${Math.random()}`)
}} }}
> >
set cookie set cookie
......
...@@ -3,7 +3,7 @@ import { cookies } from 'next/headers' ...@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
async function action() { async function action() {
'use server' 'use server'
cookies().set( ;(await cookies()).set(
'custom-server-action-test-cookie', 'custom-server-action-test-cookie',
'custom-server-action-test-cookie-val' 'custom-server-action-test-cookie-val'
) )
......
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export default async function Page({ params: { id } }) { export default async function Page({ params }) {
const id = (await params).id
if (id === 'source') redirect('/dynamic/dest') if (id === 'source') redirect('/dynamic/dest')
return ( return (
......
import Link from 'next/link' import Link from 'next/link'
export default async function Page({ searchParams: { timeout } }) { export default async function Page({ searchParams }) {
const timeout = (await searchParams).timeout
const randomNumber = await new Promise((resolve) => { const randomNumber = await new Promise((resolve) => {
setTimeout( setTimeout(
() => { () => {
......
import Link from 'next/link' import Link from 'next/link'
export default async function Page({ searchParams: { timeout } }) { export default async function Page({ searchParams }) {
const timeout = (await searchParams).timeout
const randomNumber = await new Promise((resolve) => { const randomNumber = await new Promise((resolve) => {
setTimeout( setTimeout(
() => { () => {
......
...@@ -2,7 +2,7 @@ import { cookies } from 'next/headers' ...@@ -2,7 +2,7 @@ import { cookies } from 'next/headers'
export const runtime = 'edge' export const runtime = 'edge'
export default function Page() { export default async function Page() {
cookies() await cookies()
return <h1>Hello!</h1> return <h1>Hello!</h1>
} }
import { use } from 'react'
import { ClientHooks } from './client-hooks-ext' import { ClientHooks } from './client-hooks-ext'
import { headers, cookies } from 'next/headers.js' import { headers, cookies } from 'next/headers.js'
export function useHooks() { export function useHooks() {
headers() headers()
cookies() use(cookies())
return <ClientHooks /> return <ClientHooks />
} }
import { use } from 'react'
import { ClientHooks } from './client-hooks' import { ClientHooks } from './client-hooks'
import { headers, cookies } from 'next/headers' import { headers, cookies } from 'next/headers'
export function useHooks() { export function useHooks() {
headers() headers()
cookies() use(cookies())
return <ClientHooks /> return <ClientHooks />
} }
...@@ -254,7 +254,7 @@ describe('app dir - middleware with middleware in src dir', () => { ...@@ -254,7 +254,7 @@ describe('app dir - middleware with middleware in src dir', () => {
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export async function middleware(request) { export async function middleware(request) {
const cookie = cookies().get('test-cookie') const cookie = (await cookies()).get('test-cookie')
return NextResponse.json({ cookie }) return NextResponse.json({ cookie })
} }
`, `,
......
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export default function Page() { export default async function Page() {
const rscCookie1 = cookies().get('rsc-cookie-value-1')?.value const rscCookie1 = (await cookies()).get('rsc-cookie-value-1')?.value
const rscCookie2 = cookies().get('rsc-cookie-value-2')?.value const rscCookie2 = (await cookies()).get('rsc-cookie-value-2')?.value
return ( return (
<div> <div>
<p id="rsc-cookie-1">Cookie 1: {rscCookie1}</p> <p id="rsc-cookie-1">Cookie 1: {rscCookie1}</p>
<p id="rsc-cookie-2">Cookie 2: {rscCookie2}</p> <p id="rsc-cookie-2">Cookie 2: {rscCookie2}</p>
<p id="total-cookies">Total Cookie Length: {cookies().size}</p> <p id="total-cookies">Total Cookie Length: {(await cookies()).size}</p>
</div> </div>
) )
} }
...@@ -2,16 +2,16 @@ import { cookies } from 'next/headers' ...@@ -2,16 +2,16 @@ import { cookies } from 'next/headers'
import Link from 'next/link' import Link from 'next/link'
import { Form } from '../form' import { Form } from '../form'
export default function Page() { export default async function Page() {
return ( return (
<div> <div>
<p id="total-cookies">Total Cookie Length: {cookies().size}</p> <p id="total-cookies">Total Cookie Length: {(await cookies()).size}</p>
<Link href="/rsc-cookies-delete">To Delete Cookies Route</Link> <Link href="/rsc-cookies-delete">To Delete Cookies Route</Link>
<Form <Form
action={async () => { action={async () => {
'use server' 'use server'
return cookies().get('rsc-secure-cookie').value return (await cookies()).get('rsc-secure-cookie').value
}} }}
/> />
</div> </div>
......
...@@ -2,21 +2,21 @@ import { cookies } from 'next/headers' ...@@ -2,21 +2,21 @@ import { cookies } from 'next/headers'
import Link from 'next/link' import Link from 'next/link'
import { Form } from './form' import { Form } from './form'
export default function Page() { export default async function Page() {
const rscCookie1 = cookies().get('rsc-cookie-value-1')?.value const rscCookie1 = (await cookies()).get('rsc-cookie-value-1')?.value
const rscCookie2 = cookies().get('rsc-cookie-value-2')?.value const rscCookie2 = (await cookies()).get('rsc-cookie-value-2')?.value
return ( return (
<div> <div>
<p id="rsc-cookie-1">Cookie 1: {rscCookie1}</p> <p id="rsc-cookie-1">Cookie 1: {rscCookie1}</p>
<p id="rsc-cookie-2">Cookie 2: {rscCookie2}</p> <p id="rsc-cookie-2">Cookie 2: {rscCookie2}</p>
<p id="total-cookies">Total Cookie Length: {cookies().size}</p> <p id="total-cookies">Total Cookie Length: {(await cookies()).size}</p>
<Link href="/rsc-cookies-delete">To Delete Cookies Route</Link> <Link href="/rsc-cookies-delete">To Delete Cookies Route</Link>
<Form <Form
action={async () => { action={async () => {
'use server' 'use server'
return cookies().get('rsc-cookie-value-1')?.value return (await cookies()).get('rsc-cookie-value-1')?.value
}} }}
/> />
</div> </div>
......
...@@ -21,7 +21,7 @@ export async function middleware(request) { ...@@ -21,7 +21,7 @@ export async function middleware(request) {
} }
if (request.nextUrl.searchParams.get('draft')) { if (request.nextUrl.searchParams.get('draft')) {
draftMode().enable() ;(await draftMode()).enable()
} }
const removeHeaders = request.nextUrl.searchParams.get('remove-headers') const removeHeaders = request.nextUrl.searchParams.get('remove-headers')
......
import Link from 'next/link' import Link from 'next/link'
export default function Home({ searchParams }) { export default async function Home({ searchParams }) {
return ( return (
<> <>
<div id="search-params-data">{JSON.stringify(searchParams)}</div> <div id="search-params-data">{JSON.stringify(await searchParams)}</div>
<Link href="?foo=true">Add search params</Link> <Link href="?foo=true">Add search params</Link>
<Link href="/force-dynamic/search-params">Clear Params</Link> <Link href="/force-dynamic/search-params">Clear Params</Link>
</> </>
......
...@@ -5,7 +5,7 @@ async function isLoggedIn() { ...@@ -5,7 +5,7 @@ async function isLoggedIn() {
// sleep for 1s // sleep for 1s
await new Promise((resolve) => setTimeout(resolve, 1000)) await new Promise((resolve) => setTimeout(resolve, 1000))
const cookieData = cookies() const cookieData = await cookies()
const hasSession = !!cookieData.get('logged-in') const hasSession = !!cookieData.get('logged-in')
return hasSession return hasSession
......
import Link from 'next/link' import Link from 'next/link'
export default function Home({ searchParams }) { export default async function Home({ searchParams }) {
return ( return (
<> <>
<div id="search-params-data">{JSON.stringify(searchParams)}</div> <div id="search-params-data">{JSON.stringify(await searchParams)}</div>
<Link href="?foo=true">Add search params</Link> <Link href="?foo=true">Add search params</Link>
<Link href="/revalidate-0/search-params">Clear Params</Link> <Link href="/revalidate-0/search-params">Clear Params</Link>
</> </>
......
...@@ -467,7 +467,7 @@ describe('app-custom-routes', () => { ...@@ -467,7 +467,7 @@ describe('app-custom-routes', () => {
}) })
}) })
describe('cookies().has()', () => { describe('(await cookies()).has()', () => {
it('gets the correct values', async () => { it('gets the correct values', async () => {
const res = await next.fetch(basePath + '/hooks/cookies/has') const res = await next.fetch(basePath + '/hooks/cookies/has')
......
...@@ -3,7 +3,7 @@ import { NextResponse } from 'next/server' ...@@ -3,7 +3,7 @@ import { NextResponse } from 'next/server'
export const dynamic = 'force-static' export const dynamic = 'force-static'
export function GET(req: Request) { export async function GET(req: Request) {
return NextResponse.json({ return NextResponse.json({
nextUrl: { nextUrl: {
href: (req as any).nextUrl.href, href: (req as any).nextUrl.href,
...@@ -15,7 +15,7 @@ export function GET(req: Request) { ...@@ -15,7 +15,7 @@ export function GET(req: Request) {
url: req.url, url: req.url,
headers: req.headers.get('accept'), headers: req.headers.get('accept'),
}, },
headers: headers().get('accept'), headers: (await headers()).get('accept'),
cookies: cookies().get('session')?.value ?? null, cookies: (await cookies()).get('session')?.value ?? null,
}) })
} }
...@@ -4,7 +4,7 @@ import { getRequestMeta } from '../../../helpers' ...@@ -4,7 +4,7 @@ import { getRequestMeta } from '../../../helpers'
export const runtime = 'experimental-edge' export const runtime = 'experimental-edge'
export function GET() { export async function GET() {
const meta = getRequestMeta(headers()) const meta = getRequestMeta(await headers())
return NextResponse.json(meta) return NextResponse.json(meta)
} }
...@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server' ...@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
export async function GET() { export async function GET() {
const c = cookies() const c = await cookies()
c.set('a', 'a') c.set('a', 'a')
const hasCookie = c.has('a') const hasCookie = c.has('a')
......
...@@ -2,7 +2,7 @@ import { cookies } from 'next/headers' ...@@ -2,7 +2,7 @@ import { cookies } from 'next/headers'
import { getRequestMeta, withRequestMeta } from '../../../helpers' import { getRequestMeta, withRequestMeta } from '../../../helpers'
export async function GET() { export async function GET() {
const c = cookies() const c = await cookies()
// Put the request meta in the response directly as meta again. // Put the request meta in the response directly as meta again.
const meta = getRequestMeta(c) const meta = getRequestMeta(c)
......
...@@ -2,7 +2,7 @@ import { headers } from 'next/headers' ...@@ -2,7 +2,7 @@ import { headers } from 'next/headers'
import { getRequestMeta, withRequestMeta } from '../../../helpers' import { getRequestMeta, withRequestMeta } from '../../../helpers'
export async function GET() { export async function GET() {
const h = headers() const h = await headers()
// Put the request meta in the response directly as meta again. // Put the request meta in the response directly as meta again.
const meta = getRequestMeta(h) const meta = getRequestMeta(h)
......
...@@ -4,7 +4,7 @@ import { type NextRequest, NextResponse } from 'next/server' ...@@ -4,7 +4,7 @@ import { type NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
if (process.env.NEXT_PHASE === 'phase-production-build') { if (process.env.NEXT_PHASE === 'phase-production-build') {
// don't error during build // don't error during build
cookies() await cookies()
} else { } else {
const url = new URL('/basic/endpoint', request.nextUrl) const url = new URL('/basic/endpoint', request.nextUrl)
return NextResponse.rewrite(url) return NextResponse.rewrite(url)
......
...@@ -4,7 +4,7 @@ import { NextResponse } from 'next/server' ...@@ -4,7 +4,7 @@ import { NextResponse } from 'next/server'
export async function GET() { export async function GET() {
if (process.env.NEXT_PHASE === 'phase-production-build') { if (process.env.NEXT_PHASE === 'phase-production-build') {
// don't error during build // don't error during build
cookies() await cookies()
} else { } else {
return NextResponse.next() return NextResponse.next()
} }
......
...@@ -3,7 +3,7 @@ import { cookies } from 'next/headers' ...@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
export async function GET() { export async function GET() {
if (process.env.NEXT_PHASE === 'phase-production-build') { if (process.env.NEXT_PHASE === 'phase-production-build') {
// don't error during build // don't error during build
cookies() await cookies()
} else { } else {
throw new Error('this is a runtime error') throw new Error('this is a runtime error')
} }
......
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
export function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const status = req.nextUrl.searchParams.get('status') const status = req.nextUrl.searchParams.get('status')
if (status === 'enable') { if (status === 'enable') {
draftMode().enable() ;(await draftMode()).enable()
} else { } else {
draftMode().disable() ;(await draftMode()).disable()
} }
return NextResponse.json({ return NextResponse.json({
......
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
export interface Props { export interface Props {
params: { params: Promise<{
slug: string slug: string
} }>
} }
const Article = ({ params }: Props) => { const Article = async ({ params }: Props) => {
const { slug } = params const { slug } = await params
if (slug !== 'works') { if (slug !== 'works') {
return notFound() return notFound()
......
export default async function Page({ searchParams }) { import { unstable_noStore as noStore } from 'next/cache'
// this page is using searchParams to opt into dynamic rendering
export default async function Page() {
// this page is using unstable_noStore() to opt into dynamic rendering
// meaning the page will bail from ISR cache and hint to patch-fetch // meaning the page will bail from ISR cache and hint to patch-fetch
// that it's in a dynamic scope and shouldn't cache the fetch. // that it's in a dynamic scope and shouldn't cache the fetch.
console.log(searchParams.q) noStore()
const data1 = await fetch( const data1 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?1', 'https://next-data-api-endpoint.vercel.app/api/random?1',
{ cache: 'default' } { cache: 'default' }
......
...@@ -2,11 +2,11 @@ import { cookies } from 'next/headers' ...@@ -2,11 +2,11 @@ import { cookies } from 'next/headers'
export const dynamic = 'error' export const dynamic = 'error'
export default function Page({ params }) { export default async function Page({ params }) {
// When PPR is enabled, we will bailout on parameter access. // When PPR is enabled, we will bailout on parameter access.
if (!process.env.__NEXT_EXPERIMENTAL_PPR) { if (!process.env.__NEXT_EXPERIMENTAL_PPR) {
if (params.id.includes('static-bailout')) { if (params.id.includes('static-bailout')) {
console.log('calling cookies', cookies()) console.log('calling cookies', await cookies())
} }
} }
return <p>Dynamic error</p> return <p>Dynamic error</p>
......
export default function Hello({ params }) { export default async function Hello({ params }) {
return <h1 id="slug">{params.slug}</h1> return <h1 id="slug">{(await params).slug}</h1>
} }
export function generateStaticParams() { export function generateStaticParams() {
......
...@@ -2,8 +2,8 @@ import { cookies } from 'next/headers' ...@@ -2,8 +2,8 @@ import { cookies } from 'next/headers'
import Refresh from './refresh' import Refresh from './refresh'
export default function Page() { export default async function Page() {
const cookieValue = cookies().get('test-cookie') const cookieValue = (await cookies()).get('test-cookie')
return ( return (
<> <>
<Refresh /> <Refresh />
......
...@@ -8,8 +8,10 @@ export const generateStaticParams = async () => { ...@@ -8,8 +8,10 @@ export const generateStaticParams = async () => {
return [{ slug: 'frameworks' }] return [{ slug: 'frameworks' }]
} }
export default function Page({ params }) { export default async function Page({ params }) {
const result = cookies().get('session')?.value ? 'has cookie' : 'no cookie' const result = (await cookies()).get('session')?.value
? 'has cookie'
: 'no cookie'
return ( return (
<div> <div>
<div id="slug">{params.slug}</div> <div id="slug">{params.slug}</div>
......
export default function IdPage({ children, params, searchParams }) { export default async function IdPage({ children, params, searchParams }) {
return ( return (
<> <>
<p> <p>
...@@ -6,8 +6,7 @@ export default function IdPage({ children, params, searchParams }) { ...@@ -6,8 +6,7 @@ export default function IdPage({ children, params, searchParams }) {
<span id="id-page-params">{JSON.stringify(params)}</span> <span id="id-page-params">{JSON.stringify(params)}</span>
</p> </p>
{children} {children}
<p id="search-params">{JSON.stringify(await searchParams)}</p>
<p id="search-params">{JSON.stringify(searchParams)}</p>
</> </>
) )
} }
import Link from 'next/link' import Link from 'next/link'
export default function Page({ searchParams }) { export default async function Page({ searchParams }) {
return ( return (
<> <>
<h1 id="result">{JSON.stringify(searchParams)}</h1> <h1 id="result">{JSON.stringify(await searchParams)}</h1>
<div> <div>
<Link href="/navigation/searchparams?a=a">To A</Link> <Link href="/navigation/searchparams?a=a">To A</Link>
</div> </div>
......
'use client' 'use client'
export default function Page({ params, searchParams }) { export default async function Page({ params, searchParams }) {
return ( return (
<h1 <h1
id="params-and-query" id="params-and-query"
data-params={params.slug} data-params={params.slug}
data-query={searchParams.slug} data-query={(await searchParams).slug}
> >
hello from /param-and-query/{params.slug}?slug={searchParams.slug} hello from /param-and-query/{params.slug}?slug={(await searchParams).slug}
</h1> </h1>
) )
} }
'use client' 'use client'
import { use } from 'react'
export default function Page({ searchParams }) { export default function Page({ searchParams }) {
const sp = use(searchParams)
return ( return (
<h1 <h1
id="params" id="params"
data-param-first={searchParams.first ?? 'N/A'} data-param-first={sp.first ?? 'N/A'}
data-param-second={searchParams.second ?? 'N/A'} data-param-second={sp.second ?? 'N/A'}
data-param-third={searchParams.third ?? 'N/A'} data-param-third={sp.third ?? 'N/A'}
data-param-not-real={searchParams.notReal ?? 'N/A'} data-param-not-real={sp.notReal ?? 'N/A'}
> >
hello from searchParams prop client hello from searchParams prop client
</h1> </h1>
......
export default function Page({ searchParams }) { export default async function Page({ searchParams }) {
const sp = await searchParams
return ( return (
<h1 <h1
id="params" id="params"
data-param-first={searchParams.first ?? 'N/A'} data-param-first={sp.first ?? 'N/A'}
data-param-second={searchParams.second ?? 'N/A'} data-param-second={sp.second ?? 'N/A'}
data-param-third={searchParams.third ?? 'N/A'} data-param-third={sp.third ?? 'N/A'}
data-param-not-real={searchParams.notReal ?? 'N/A'} data-param-not-real={sp.notReal ?? 'N/A'}
> >
hello from searchParams prop server hello from searchParams prop server
</h1> </h1>
......
...@@ -5,7 +5,7 @@ async function Suspend() { ...@@ -5,7 +5,7 @@ async function Suspend() {
await new Promise((resolve) => { await new Promise((resolve) => {
setTimeout(resolve, 3000) setTimeout(resolve, 3000)
}) })
cookies() await cookies()
return <p>suspended content</p> return <p>suspended content</p>
} }
......
import Link from 'next/link' import Link from 'next/link'
import styles from './styles.module.css' import styles from './styles.module.css'
export default function Page({ params: { num } }) { export default async function Page({
params,
}: {
params: Promise<{ num: string }>
}) {
const { num } = await params
return ( return (
<div> <div>
{new Array(100).fill(0).map((_, i) => ( {new Array(100).fill(0).map((_, i) => (
......
export default function Page({ params: { id } }) { export default async function Page({ params }: { params: Promise<{ id }> }) {
return <p>{id}</p> return <p>{(await params).id}</p>
} }
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export async function GET(request: Request) { export async function GET(request: Request) {
draftMode().disable() ;(await draftMode()).disable()
return new Response('Draft mode is disabled') return new Response('Draft mode is disabled')
} }
...@@ -16,7 +16,7 @@ export async function GET(request: Request) { ...@@ -16,7 +16,7 @@ export async function GET(request: Request) {
} }
// Enable Draft Mode by setting the cookie // Enable Draft Mode by setting the cookie
draftMode().enable() ;(await draftMode()).enable()
// Redirect to the path // Redirect to the path
redirect(`/${slug}`) redirect(`/${slug}`)
......
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export default function PreviewPage() { export default async function PreviewPage() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
return <h1>{isEnabled ? 'draft' : 'none'}</h1> return <h1>{isEnabled ? 'draft' : 'none'}</h1>
} }
import { NextResponse, type NextRequest } from 'next/server' import { NextResponse, type NextRequest } from 'next/server'
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function middleware(req: NextRequest) { export async function middleware(req: NextRequest) {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
console.log('draftMode().isEnabled from middleware:', isEnabled) console.log('draftMode().isEnabled from middleware:', isEnabled)
return NextResponse.next() return NextResponse.next()
} }
......
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function GET() { export async function GET() {
draftMode().disable() ;(await draftMode()).disable()
return new Response( return new Response(
'Disabled in Route Handler using draftMode().enable(), check cookies' 'Disabled in Route Handler using `(await draftMode()).disable()`, check cookies'
) )
} }
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export function GET(req: Request) { export async function GET(req: Request) {
draftMode().enable() ;(await draftMode()).enable()
const to = new URL(req.url).searchParams.get('to') ?? '/some-other-page' const to = new URL(req.url).searchParams.get('to') ?? '/some-other-page'
return redirect(to) return redirect(to)
} }
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function GET() { export async function GET() {
draftMode().enable() ;(await draftMode()).enable()
return new Response( return new Response(
'Enabled in Route Handler using draftMode().enable(), check cookies' 'Enabled in Route Handler using `(await draftMode()).enable()`, check cookies'
) )
} }
import React from 'react' import React from 'react'
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export default function Page() { export default async function Page() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
return ( return (
<> <>
......
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function GET() { export async function GET() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
return new Response(isEnabled ? 'ENABLED' : 'DISABLED') return new Response(isEnabled ? 'ENABLED' : 'DISABLED')
} }
import React from 'react' import React from 'react'
import { cookies, draftMode } from 'next/headers' import { cookies, draftMode } from 'next/headers'
export default function Page() { export default async function Page() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
let data: string | undefined let data: string | undefined
if (isEnabled) { if (isEnabled) {
data = cookies().get('data')?.value data = (await cookies()).get('data')?.value
} }
return ( return (
......
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function GET() { export async function GET() {
draftMode().disable() ;(await draftMode()).disable()
return new Response( return new Response(
'Disabled in Route Handler using draftMode().enable(), check cookies' 'Disabled in Route Handler using `(await draftMode()).enable()`, check cookies'
) )
} }
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
export function GET(req: Request) { export async function GET(req: Request) {
draftMode().enable() ;(await draftMode()).enable()
const to = new URL(req.url).searchParams.get('to') ?? '/some-other-page' const to = new URL(req.url).searchParams.get('to') ?? '/some-other-page'
return redirect(to) return redirect(to)
} }
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function GET() { export async function GET() {
draftMode().enable() ;(await draftMode()).enable()
return new Response( return new Response(
'Enabled in Route Handler using draftMode().enable(), check cookies' 'Enabled in Route Handler using `(await draftMode()).enable()`, check cookies'
) )
} }
import React from 'react' import React from 'react'
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export default function Page() { export default async function Page() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
return ( return (
<> <>
......
import { draftMode } from 'next/headers' import { draftMode } from 'next/headers'
export function GET() { export async function GET() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
return new Response(isEnabled ? 'ENABLED' : 'DISABLED') return new Response(isEnabled ? 'ENABLED' : 'DISABLED')
} }
import React from 'react' import React from 'react'
import { cookies, draftMode } from 'next/headers' import { cookies, draftMode } from 'next/headers'
export default function Page() { export default async function Page() {
const { isEnabled } = draftMode() const { isEnabled } = await draftMode()
let data: string | undefined let data: string | undefined
if (isEnabled) { if (isEnabled) {
data = cookies().get('data')?.value data = (await cookies()).get('data')?.value
} }
return ( return (
......
...@@ -4,7 +4,6 @@ import { unstable_cache as cache } from 'next/cache' ...@@ -4,7 +4,6 @@ import { unstable_cache as cache } from 'next/cache'
const cookies = cache(() => nextCookies()) const cookies = cache(() => nextCookies())
export default async function Page({ searchParams }) { export default async function Page({ searchParams }) {
console.log('cookies()', await cookies())
return ( return (
<div> <div>
<section> <section>
...@@ -13,22 +12,20 @@ export default async function Page({ searchParams }) { ...@@ -13,22 +12,20 @@ export default async function Page({ searchParams }) {
</section> </section>
<section id="cookies"> <section id="cookies">
<h3>cookies</h3> <h3>cookies</h3>
{cookies() {(await cookies()).getAll().map((cookie) => {
.getAll() const key = cookie.name
.map((cookie) => { let value = cookie.value
const key = cookie.name
let value = cookie.value
if (key === 'userCache') { if (key === 'userCache') {
value = value.slice(0, 10) + '...' value = value.slice(0, 10) + '...'
} }
return ( return (
<div key={key}> <div key={key}>
<h4>{key}</h4> <h4>{key}</h4>
<pre className={key}>{value}</pre> <pre className={key}>{value}</pre>
</div> </div>
) )
})} })}
</section> </section>
</div> </div>
) )
......
'use client' 'use client'
import { PageSentinel } from '../getSentinelValue'
export default async function Page({ searchParams }) { export default async function Page({ searchParams }) {
const { __TEST_SENTINEL } = process.env
return ( return (
<div> <div>
<div id="page">{__TEST_SENTINEL}</div> <PageSentinel />
<section> <section>
This example uses headers/cookies/searchParams directly in a Page This example uses headers/cookies/searchParams directly in a Page
configured with `dynamic = 'force-dynamic'`. This should cause the page configured with `dynamic = 'force-dynamic'`. This should cause the page
...@@ -20,7 +21,7 @@ export default async function Page({ searchParams }) { ...@@ -20,7 +21,7 @@ export default async function Page({ searchParams }) {
</section> </section>
<section id="searchparams"> <section id="searchparams">
<h3>searchParams</h3> <h3>searchParams</h3>
{Object.entries(searchParams).map(([key, value]) => { {Object.entries(await searchParams).map(([key, value]) => {
return ( return (
<div key={key}> <div key={key}>
<h4>{key}</h4> <h4>{key}</h4>
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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