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 @@
"codemod",
"codemods",
"Destructuring",
"buildtime",
"callsites",
"codemod",
"datastream",
"deduped",
"draftmode",
"Entrypoints",
"jscodeshift",
"napi",
"navigations",
"nextjs",
"opentelemetry",
"Preinit",
"prerendered",
"prerendering",
"proxied",
"renderable",
"revalidates",
"subresource",
"thenables",
"Threadsafe",
"Turbopack",
"unproxied",
"zipkin"
],
"grammarly.selectors": [
......
export * from './dist/server/request/cookies'
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'
export { ImageResponse } from 'next/dist/server/web/spec-extension/image-response'
export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types'
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/draft-mode'
......@@ -85,6 +85,7 @@ checkFields<Diff<{
}
}, TEntry, ''>>()
${options.type === 'route' ? `type RouteContext = { params: Promise<SegmentParams> }` : ''}
${
options.type === 'route'
? HTTP_METHODS.map(
......@@ -103,7 +104,7 @@ if ('${method}' in entry) {
>()
checkFields<
Diff<
ParamCheck<PageParams>,
ParamCheck<RouteContext>,
{
__tag__: '${method}'
__param_position__: 'second'
......@@ -158,14 +159,14 @@ if ('generateViewport' in entry) {
}
// Check the arguments and return type of the generateStaticParams function
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'>> }>>()
}
type PageParams = any
type SegmentParams = {[param: string]: string | string[] | undefined}
export interface PageProps {
params?: any
searchParams?: any
params?: Promise<SegmentParams>
searchParams?: Promise<any>
}
export interface LayoutProps {
children?: React.ReactNode
......@@ -174,7 +175,7 @@ ${
? options.slots.map((slot) => ` ${slot}: React.ReactNode`).join('\n')
: ''
}
params?: any
params?: Promise<SegmentParams>
}
// =============
......
'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({
Component,
props,
searchParams,
params,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
promises,
}: {
Component: React.ComponentType<any>
props: { [props: string]: any }
searchParams: ParsedUrlQuery
params: Params
promises?: Array<Promise<any>>
}) {
if (typeof window === 'undefined') {
const { createDynamicallyTrackedParams } =
require('../../server/request/fallback-params') as typeof import('../../server/request/fallback-params')
const { createDynamicallyTrackedSearchParams } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
// We expect to be passed searchParams but even if we aren't we can construct one from
// an empty object. We only do this if we are in a static generation as a performance
// optimization. Ideally we'd unconditionally construct the tracked params but since
// this creates a proxy which is slow and this would happen even for client navigations
// that are done entirely dynamically and we know there the dynamic tracking is a noop
// in this dynamic case we can safely elide it.
props.searchParams = createDynamicallyTrackedSearchParams(
props.searchParams || {}
)
props.params = props.params
? createDynamicallyTrackedParams(props.params)
: {}
const { staticGenerationAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
let clientSearchParams: Promise<ParsedUrlQuery>
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 searchParams in a client Page.'
)
}
if (store.isStaticGeneration) {
// 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'
type ClientSegmentRootProps = {
Component: React.ComponentType
props: { [props: string]: any }
}
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 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({
Component,
props,
}: ClientSegmentRootProps) {
slots,
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') {
const { createDynamicallyTrackedParams } =
require('../../server/request/fallback-params') as typeof import('../../server/request/fallback-params')
const { staticGenerationAsyncStorage } =
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
? createDynamicallyTrackedParams(props.params)
: {}
if (store.isStaticGeneration) {
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 {
import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
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
......@@ -65,27 +65,6 @@ export function useSearchParams(): ReadonlyURLSearchParams {
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
* that lets you read the current URL's pathname.
......@@ -105,7 +84,7 @@ function trackParamsAccessed(expression: string) {
*/
// Client components API
export function usePathname(): string {
trackParamsAccessed('usePathname()')
useDynamicRouteParams('usePathname()')
// 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`.
......@@ -165,21 +144,19 @@ export function useRouter(): AppRouterInstance {
*/
// Client components API
export function useParams<T extends Params = Params>(): T {
trackParamsAccessed('useParams()')
useDynamicRouteParams('useParams()')
return useContext(PathParamsContext) as T
}
/** Get the canonical parameters from the current level to the leaf node. */
// Client components API
export function getSelectedLayoutSegmentPath(
function getSelectedLayoutSegmentPath(
tree: FlightRouterState,
parallelRouteKey: string,
first = true,
segmentPath: string[] = []
): string[] {
trackParamsAccessed('getSelectedLayoutSegmentPath()')
let node: FlightRouterState
if (first) {
// Use the provided parallel route key on the first parallel route
......@@ -238,7 +215,7 @@ export function getSelectedLayoutSegmentPath(
export function useSelectedLayoutSegments(
parallelRouteKey: string = 'children'
): string[] {
trackParamsAccessed('useSelectedLayoutSegments()')
useDynamicRouteParams('useSelectedLayoutSegments()')
const context = useContext(LayoutRouterContext)
// @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts
......@@ -269,7 +246,7 @@ export function useSelectedLayoutSegments(
export function useSelectedLayoutSegment(
parallelRouteKey: string = 'children'
): string | null {
trackParamsAccessed('useSelectedLayoutSegment()')
useDynamicRouteParams('useSelectedLayoutSegment()')
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)
......
......@@ -4,6 +4,7 @@ import type {
GetDynamicParamFromSegment,
} from '../../server/app-render/app-render'
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { CreateServerParamsForMetadata } from '../../server/request/params'
import React from 'react'
import {
......@@ -30,7 +31,6 @@ import type {
} from './types/metadata-interface'
import { isNotFoundError } from '../../client/components/not-found'
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 { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering'
......@@ -84,24 +84,22 @@ export function createTrackedMetadataContext(
// and the error will be caught by the error boundary and trigger fallbacks.
export function createMetadataComponents({
tree,
query,
searchParams,
metadataContext,
getDynamicParamFromSegment,
appUsingSizeAdjustment,
errorType,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
}: {
tree: LoaderTree
query: ParsedUrlQuery
searchParams: Promise<ParsedUrlQuery>
metadataContext: MetadataContext
getDynamicParamFromSegment: GetDynamicParamFromSegment
appUsingSizeAdjustment: boolean
errorType?: 'not-found' | 'redirect'
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams
createDynamicallyTrackedSearchParams: (
searchParams: ParsedUrlQuery
) => ParsedUrlQuery
createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
}): [React.ComponentType, () => Promise<void>] {
let currentMetadataReady:
| null
......@@ -113,11 +111,11 @@ export function createMetadataComponents({
async function MetadataTree() {
const pendingMetadata = getResolvedMetadata(
tree,
query,
searchParams,
getDynamicParamFromSegment,
metadataContext,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
errorType
)
......@@ -177,18 +175,15 @@ export function createMetadataComponents({
async function getResolvedMetadata(
tree: LoaderTree,
query: ParsedUrlQuery,
searchParams: Promise<ParsedUrlQuery>,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext,
createDynamicallyTrackedSearchParams: (
searchParams: ParsedUrlQuery
) => ParsedUrlQuery,
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore,
errorType?: 'not-found' | 'redirect'
): Promise<[any, Array<React.ReactNode>]> {
const errorMetadataItem: [null, null, null] = [null, null, null]
const errorConvention = errorType === 'redirect' ? undefined : errorType
const searchParams = createDynamicallyTrackedSearchParams(query)
const [error, metadata, viewport] = await resolveMetadata({
tree,
......@@ -199,7 +194,8 @@ async function getResolvedMetadata(
getDynamicParamFromSegment,
errorConvention,
metadataContext,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
if (!error) {
return [null, createMetadataElements(metadata, viewport)]
......@@ -219,7 +215,8 @@ async function getResolvedMetadata(
getDynamicParamFromSegment,
errorConvention: 'not-found',
metadataContext,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
return [
notFoundMetadataError || error,
......
......@@ -49,7 +49,11 @@ import { getTracer } from '../../server/lib/trace/tracer'
import { ResolveMetadataSpan } from '../../server/lib/trace/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
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'>
......@@ -479,10 +483,11 @@ export async function resolveMetadataItems({
getDynamicParamFromSegment,
searchParams,
errorConvention,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
}: {
tree: LoaderTree
parentParams: { [key: string]: any }
parentParams: Params
metadataItems: MetadataItems
errorMetadataItem: MetadataItems[number]
/** Provided tree can be nested subtree, this argument says what is the path of such subtree */
......@@ -490,7 +495,8 @@ export async function resolveMetadataItems({
getDynamicParamFromSegment: GetDynamicParamFromSegment
searchParams: ParsedUrlQuery
errorConvention: 'not-found' | undefined
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams
createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
}): Promise<MetadataItems> {
const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix = [...treePrefix, segment]
......@@ -501,17 +507,18 @@ export async function resolveMetadataItems({
/**
* Create object holding the parent params and current params
*/
const currentParams =
// Handle null case where dynamic param is optional
segmentParam && segmentParam.value !== null
? {
...parentParams,
[segmentParam.param]: segmentParam.value,
}
: // Pass through parent params to children
parentParams
let currentParams = parentParams
if (segmentParam && segmentParam.value !== null) {
currentParams = {
...parentParams,
[segmentParam.param]: segmentParam.value,
}
}
const params = createDynamicallyTrackedParams(currentParams)
const params = createServerParamsForMetadata(
currentParams,
staticGenerationStore
)
let layerProps: LayoutProps | PageProps
if (isPage) {
......@@ -548,7 +555,8 @@ export async function resolveMetadataItems({
searchParams,
getDynamicParamFromSegment,
errorConvention,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
}
......@@ -891,10 +899,11 @@ export async function resolveMetadata({
searchParams,
errorConvention,
metadataContext,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
}: {
tree: LoaderTree
parentParams: { [key: string]: any }
parentParams: Params
metadataItems: MetadataItems
errorMetadataItem: MetadataItems[number]
/** Provided tree can be nested subtree, this argument says what is the path of such subtree */
......@@ -903,7 +912,8 @@ export async function resolveMetadata({
searchParams: { [key: string]: any }
errorConvention: 'not-found' | undefined
metadataContext: MetadataContext
createDynamicallyTrackedParams: CreateDynamicallyTrackedParams
createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
}): Promise<[any, ResolvedMetadata, ResolvedViewport]> {
const resolvedMetadataItems = await resolveMetadataItems({
tree,
......@@ -913,7 +923,8 @@ export async function resolveMetadata({
getDynamicParamFromSegment,
searchParams,
errorConvention,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
let error
let metadata: ResolvedMetadata = createDefaultMetadata()
......
......@@ -385,8 +385,8 @@ async function generateDynamicRSCPayload(
const {
componentMod: {
tree: loaderTree,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerSearchParamsForMetadata,
createServerParamsForMetadata,
},
getDynamicParamFromSegment,
appUsingSizeAdjustment,
......@@ -400,9 +400,13 @@ async function generateDynamicRSCPayload(
if (!options?.skipFlight) {
const preloadCallbacks: PreloadCallbacks = []
const searchParams = createServerSearchParamsForMetadata(
query,
staticGenerationStore
)
const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree: loaderTree,
query,
searchParams,
metadataContext: createTrackedMetadataContext(
url.pathname,
ctx.renderOpts,
......@@ -410,8 +414,8 @@ async function generateDynamicRSCPayload(
),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
flightData = (
await walkTreeWithFlightRouterState({
......@@ -546,8 +550,8 @@ async function getRSCPayload(
appUsingSizeAdjustment,
componentMod: {
GlobalError,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerSearchParamsForMetadata,
createServerParamsForMetadata,
},
requestStore: { url },
staticGenerationStore,
......@@ -558,10 +562,14 @@ async function getRSCPayload(
query
)
const searchParams = createServerSearchParamsForMetadata(
query,
staticGenerationStore
)
const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree,
errorType: is404 ? 'not-found' : undefined,
query,
searchParams,
metadataContext: createTrackedMetadataContext(
url.pathname,
ctx.renderOpts,
......@@ -569,8 +577,8 @@ async function getRSCPayload(
),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
const preloadCallbacks: PreloadCallbacks = []
......@@ -642,24 +650,29 @@ async function getErrorRSCPayload(
appUsingSizeAdjustment,
componentMod: {
GlobalError,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerSearchParamsForMetadata,
createServerParamsForMetadata,
},
requestStore: { url },
requestId,
staticGenerationStore,
} = ctx
const searchParams = createServerSearchParamsForMetadata(
query,
staticGenerationStore
)
const [MetadataTree] = createMetadataComponents({
tree,
searchParams,
// We create an untracked metadata context here because we can't postpone
// again during the error render.
metadataContext: createMetadataContext(url.pathname, ctx.renderOpts),
errorType,
query,
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerParamsForMetadata,
staticGenerationStore,
})
const initialHead = (
......@@ -1829,7 +1842,9 @@ async function prerenderToStream(
let flightController = new AbortController()
// 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
const firstAttemptRSCPayload = await getRSCPayload(
const firstAttemptRSCPayload = await prerenderAsyncStorage.run(
prospectiveRenderPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
......@@ -1895,7 +1910,9 @@ async function prerenderToStream(
reactServerIsDynamic = true
}
}
const finalAttemptRSCPayload = await getRSCPayload(
const finalAttemptRSCPayload = await prerenderAsyncStorage.run(
finalRenderPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
......@@ -2135,7 +2152,9 @@ async function prerenderToStream(
dynamicTracking,
}
const firstAttemptRSCPayload = await getRSCPayload(
const firstAttemptRSCPayload = await prerenderAsyncStorage.run(
prospectiveRenderPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
......@@ -2199,7 +2218,9 @@ async function prerenderToStream(
dynamicTracking,
}
const finalAttemptRSCPayload = await getRSCPayload(
const finalAttemptRSCPayload = await prerenderAsyncStorage.run(
finalRenderPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
......@@ -2354,7 +2375,13 @@ async function prerenderToStream(
controller: null,
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 =
await createReactServerPrerenderResultFromRender(
prerenderAsyncStorage.run(
......
......@@ -27,7 +27,13 @@ import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context'
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'
......@@ -107,7 +113,7 @@ export function markCurrentScopeAsDynamic(
// 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 specific dynamic request.
abortRSCRender(prerenderStore.controller, store.route, expression)
abortRender(prerenderStore.controller, store.route, expression)
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else if (prerenderStore.cacheSignal) {
// we're prerendering with dynamicIO but we don't want to eagerly abort this
......@@ -116,9 +122,9 @@ export function markCurrentScopeAsDynamic(
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else {
postponeWithTracking(
prerenderStore.dynamicTracking,
store.route,
expression
expression,
prerenderStore.dynamicTracking
)
}
} else {
......@@ -152,7 +158,7 @@ export function trackFallbackParamAccessed(
const prerenderStore = prerenderAsyncStorage.getStore()
if (!prerenderStore) return
postponeWithTracking(prerenderStore.dynamicTracking, store.route, expression)
postponeWithTracking(store.route, expression, prerenderStore.dynamicTracking)
}
/**
......@@ -185,7 +191,7 @@ export function trackDynamicDataAccessed(
// 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 specific dynamic request.
abortRSCRender(prerenderStore.controller, store.route, expression)
abortRender(prerenderStore.controller, store.route, expression)
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else if (prerenderStore.cacheSignal) {
// we're prerendering with dynamicIO but we don't want to eagerly abort this
......@@ -194,9 +200,9 @@ export function trackDynamicDataAccessed(
errorWithTracking(prerenderStore.dynamicTracking, store.route, expression)
} else {
postponeWithTracking(
prerenderStore.dynamicTracking,
store.route,
expression
expression,
prerenderStore.dynamicTracking
)
}
} else {
......@@ -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.
*/
......@@ -225,7 +315,7 @@ type PostponeProps = {
export function Postpone({ reason, route }: PostponeProps): never {
const prerenderStore = prerenderAsyncStorage.getStore()
const dynamicTracking = prerenderStore?.dynamicTracking || null
postponeWithTracking(dynamicTracking, route, reason)
postponeWithTracking(route, reason, dynamicTracking)
}
function errorWithTracking(
......@@ -251,10 +341,10 @@ function errorWithTracking(
throw createPrerenderInterruptedError(reason)
}
function postponeWithTracking(
dynamicTracking: null | DynamicTrackingState,
export function postponeWithTracking(
route: string,
expression: string
expression: string,
dynamicTracking: null | DynamicTrackingState
): never {
assertPostpone()
if (dynamicTracking) {
......@@ -323,7 +413,7 @@ export function isPrerenderInterruptedError(error: unknown) {
)
}
function abortRSCRender(
function abortRender(
controller: AbortController,
route: string,
expression: string
......@@ -409,3 +499,54 @@ export function createPostponedAbortSignal(reason: string): AbortSignal {
}
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
import { ClientPageRoot } from '../../client/components/client-page'
import { ClientSegmentRoot } from '../../client/components/client-segment'
import {
createUntrackedSearchParams,
createDynamicallyTrackedSearchParams,
createServerSearchParamsForServerPage,
createPrerenderSearchParamsForClientPage,
createServerSearchParamsForMetadata,
} 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 { NotFoundBoundary } from '../../client/components/not-found-boundary'
import { patchFetch as _patchFetch } from '../lib/patch-fetch'
......@@ -48,9 +53,12 @@ export {
staticGenerationAsyncStorage,
requestAsyncStorage,
actionAsyncStorage,
createUntrackedSearchParams,
createDynamicallyTrackedSearchParams,
createDynamicallyTrackedParams,
createServerSearchParamsForServerPage,
createServerSearchParamsForMetadata,
createPrerenderSearchParamsForClientPage,
createServerParamsForServerSegment,
createServerParamsForMetadata,
createPrerenderParamsForClientSegment,
serverHooks,
preloadStyle,
preloadFont,
......
......@@ -35,5 +35,9 @@ export type PrerenderStore = {
readonly dynamicTracking: null | DynamicTrackingState
}
export function isDynamicIOPrerender(prerenderStore: PrerenderStore): boolean {
return !!(prerenderStore.controller || prerenderStore.cacheSignal)
}
export type PrerenderAsyncStorage = AsyncLocalStorage<PrerenderStore>
export { prerenderAsyncStorage }
import type { __ApiPreviewProps } from './api-utils'
import type { LoadComponentsReturnType } from './load-components'
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 {
type FallbackRouteParams,
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 { 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`
*/
......@@ -34,3 +159,10 @@ export class DraftMode {
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 { 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>
......@@ -41,57 +37,3 @@ export function getFallbackRouteParams(
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'
import type { RenderOptsPartial } from '../../app-render/types'
import { CacheSignal } from '../../app-render/cache-signal'
import { scheduleImmediate } from '../../../lib/scheduler'
import { createServerParamsForRoute } from '../../request/params'
/**
* The AppRouteModule is the type of the module exported by the bundled App
......@@ -90,7 +91,7 @@ export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
* second argument.
*/
type AppRouteHandlerFnContext = {
params?: Record<string, string | string[]>
params?: Promise<Record<string, string | string[] | undefined>>
}
/**
......@@ -402,9 +403,12 @@ export class AppRouteRouteModule extends RouteModule<
prerenderAsyncStorage: this.prerenderAsyncStorage,
})
const handlerContext = {
const handlerContext: AppRouteHandlerFnContext = {
params: context.params
? parsedUrlQueryToParams(context.params)
? createServerParamsForRoute(
parsedUrlQueryToParams(context.params),
staticGenerationStore
)
: undefined,
}
......
......@@ -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,
// we want to return the request cookie if it exists. For mutative methods like `.set()`,
// we want to return the response cookie.
......
......@@ -21,8 +21,8 @@ describe('dynamic = "error" in devmode', () => {
import Component from '../../index'
export default function Page() {
cookies()
export default async function Page() {
await cookies()
return <Component />
}
......
......@@ -875,8 +875,8 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
<Segment>
<ClientPageRoot props={{params:{}, ...}} Component={function Page}>
<Page params={{}} searchParams={{}}>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}>
<div>
<div>
<div>
......@@ -895,8 +895,8 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} segmentPath={[...]} ...>
<Segment>
<ClientPageRoot props={{params:{}, ...}} Component={function Page}>
<Page params={{}} searchParams={{}}>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}>
<div>
<div>
<div>
......
......@@ -6,8 +6,8 @@ import { redirect } from 'next/navigation'
import { headers, cookies } from 'next/headers'
export async function getHeaders() {
console.log('accept header:', headers().get('accept'))
cookies().set('test-cookie', Date.now())
console.log('accept header:', (await headers()).get('accept'))
;(await cookies()).set('test-cookie', Date.now())
}
export async function inc(value) {
......
......@@ -3,14 +3,15 @@ import { cookies } from 'next/headers'
export const revalidate = 1
export const GET = async () => {
cookies().set('foo', 'foo1')
cookies().set('bar', 'bar1')
const localCookies = await cookies()
localCookies.set('foo', 'foo1')
localCookies.set('bar', 'bar1')
// Key, value, options
cookies().set('test1', 'value1', { secure: true })
localCookies.set('test1', 'value1', { secure: true })
// One object
cookies().set({
localCookies.set({
name: 'test2',
value: 'value2',
httpOnly: true,
......
......@@ -4,7 +4,7 @@ import { headers, cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export async function setCookieWithMaxAge() {
cookies().set({
;(await cookies()).set({
name: 'foo',
value: 'bar',
maxAge: 1000,
......@@ -12,19 +12,20 @@ export async function setCookieWithMaxAge() {
}
export async function getCookie(name) {
return cookies().get(name)
return (await cookies()).get(name)
}
export async function getHeader(name) {
return headers().get(name)
return (await headers()).get(name)
}
export async function setCookie(name, value) {
cookies().set(name, value)
return cookies().get(name)
const localCookies = await cookies()
localCookies.set(name, value)
return localCookies.get(name)
}
export async function setCookieAndRedirect(name, value, path, type) {
cookies().set(name, value)
;(await cookies()).set(name, value)
redirect(path, type)
}
......@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
export function validator(action) {
return async function (arg) {
'use server'
const auth = cookies().get('auth')
const auth = (await cookies()).get('auth')
if (auth?.value !== '1') {
throw new Error('Unauthorized request')
}
......
import { cookies } from 'next/headers'
import Link from 'next/link'
export default function Page() {
export default async function Page() {
return (
<>
<Link id="back" href="/mutate-cookie">
back
</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'
async function updateCookie() {
'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 (
<>
<Link id="page-2" href="/mutate-cookie/page-2">
to page2
</Link>
<p id="value">{cookies().get('test-cookie2')?.value}</p>
<p id="value">{(await cookies()).get('test-cookie2')?.value}</p>
<form action={updateCookie}>
<button id="update-cookie" type="submit">
Update Cookie
......
import { cookies } from 'next/dist/server/request/headers'
import { cookies } from 'next/headers'
export default function Page() {
const redirectCookie = cookies().get('redirect')
export default async function Page() {
const redirectCookie = (await cookies()).get('redirect')
return (
<div>
<div id="redirected-cookie">
......
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
export default function Page({ searchParams }) {
const foo = cookies().get('foo')
const bar = cookies().get('bar')
export default async function Page({ searchParams }) {
const foo = (await cookies()).get('foo')
const bar = (await cookies()).get('bar')
return (
<div>
<h1>
......@@ -12,8 +12,8 @@ export default function Page({ searchParams }) {
<form
action={async () => {
'use server'
cookies().delete('foo')
cookies().set('bar', '2')
;(await cookies()).delete('foo')
;(await cookies()).set('bar', '2')
redirect('/redirects/action-redirect/redirect-target')
}}
>
......@@ -21,7 +21,7 @@ export default function Page({ searchParams }) {
Set Cookies and Redirect
</button>
</form>
<h2>baz={searchParams.baz ?? ''}</h2>
<h2>baz={(await searchParams).baz ?? ''}</h2>
<form
action={async () => {
'use server'
......
import { cookies, headers } from 'next/headers'
export default function Page({ searchParams }) {
const foo = cookies().get('foo')
const bar = cookies().get('bar')
const actionHeader = headers().get('next-action')
export default async function Page({ searchParams }) {
const foo = (await cookies()).get('foo')
const bar = (await cookies()).get('bar')
const actionHeader = (await headers()).get('next-action')
if (actionHeader) {
throw new Error('Action header should not be present')
}
......@@ -12,7 +12,7 @@ export default function Page({ searchParams }) {
<h1>
foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''}
</h1>
<h2>baz={searchParams.baz ?? ''}</h2>
<h2>baz={(await searchParams).baz ?? ''}</h2>
</div>
)
}
......@@ -34,7 +34,7 @@ export default async function Page() {
<p>
random cookie:{' '}
<span id="random-cookie">
{JSON.stringify(cookies().get('random'))}
{JSON.stringify((await cookies()).get('random'))}
</span>
</p>
</>
......
......@@ -63,7 +63,7 @@ export default async function Page() {
<p>
random cookie:{' '}
<span id="random-cookie">
{JSON.stringify(cookies().get('random'))}
{JSON.stringify((await cookies()).get('random'))}
</span>
</p>
<form>
......@@ -71,7 +71,7 @@ export default async function Page() {
id="set-cookie"
formAction={async () => {
'use server'
cookies().set('random', `${Math.random()}`)
;(await cookies()).set('random', `${Math.random()}`)
}}
>
set cookie
......
......@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
async function action() {
'use server'
cookies().set(
;(await cookies()).set(
'custom-server-action-test-cookie',
'custom-server-action-test-cookie-val'
)
......
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')
return (
......
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) => {
setTimeout(
() => {
......
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) => {
setTimeout(
() => {
......
......@@ -2,7 +2,7 @@ import { cookies } from 'next/headers'
export const runtime = 'edge'
export default function Page() {
cookies()
export default async function Page() {
await cookies()
return <h1>Hello!</h1>
}
import { use } from 'react'
import { ClientHooks } from './client-hooks-ext'
import { headers, cookies } from 'next/headers.js'
export function useHooks() {
headers()
cookies()
use(cookies())
return <ClientHooks />
}
import { use } from 'react'
import { ClientHooks } from './client-hooks'
import { headers, cookies } from 'next/headers'
export function useHooks() {
headers()
cookies()
use(cookies())
return <ClientHooks />
}
......@@ -254,7 +254,7 @@ describe('app dir - middleware with middleware in src dir', () => {
import { cookies } from 'next/headers'
export async function middleware(request) {
const cookie = cookies().get('test-cookie')
const cookie = (await cookies()).get('test-cookie')
return NextResponse.json({ cookie })
}
`,
......
import { cookies } from 'next/headers'
export default function Page() {
const rscCookie1 = cookies().get('rsc-cookie-value-1')?.value
const rscCookie2 = cookies().get('rsc-cookie-value-2')?.value
export default async function Page() {
const rscCookie1 = (await cookies()).get('rsc-cookie-value-1')?.value
const rscCookie2 = (await cookies()).get('rsc-cookie-value-2')?.value
return (
<div>
<p id="rsc-cookie-1">Cookie 1: {rscCookie1}</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>
)
}
......@@ -2,16 +2,16 @@ import { cookies } from 'next/headers'
import Link from 'next/link'
import { Form } from '../form'
export default function Page() {
export default async function Page() {
return (
<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>
<Form
action={async () => {
'use server'
return cookies().get('rsc-secure-cookie').value
return (await cookies()).get('rsc-secure-cookie').value
}}
/>
</div>
......
......@@ -2,21 +2,21 @@ import { cookies } from 'next/headers'
import Link from 'next/link'
import { Form } from './form'
export default function Page() {
const rscCookie1 = cookies().get('rsc-cookie-value-1')?.value
const rscCookie2 = cookies().get('rsc-cookie-value-2')?.value
export default async function Page() {
const rscCookie1 = (await cookies()).get('rsc-cookie-value-1')?.value
const rscCookie2 = (await cookies()).get('rsc-cookie-value-2')?.value
return (
<div>
<p id="rsc-cookie-1">Cookie 1: {rscCookie1}</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>
<Form
action={async () => {
'use server'
return cookies().get('rsc-cookie-value-1')?.value
return (await cookies()).get('rsc-cookie-value-1')?.value
}}
/>
</div>
......
......@@ -21,7 +21,7 @@ export async function middleware(request) {
}
if (request.nextUrl.searchParams.get('draft')) {
draftMode().enable()
;(await draftMode()).enable()
}
const removeHeaders = request.nextUrl.searchParams.get('remove-headers')
......
import Link from 'next/link'
export default function Home({ searchParams }) {
export default async function Home({ searchParams }) {
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="/force-dynamic/search-params">Clear Params</Link>
</>
......
......@@ -5,7 +5,7 @@ async function isLoggedIn() {
// sleep for 1s
await new Promise((resolve) => setTimeout(resolve, 1000))
const cookieData = cookies()
const cookieData = await cookies()
const hasSession = !!cookieData.get('logged-in')
return hasSession
......
import Link from 'next/link'
export default function Home({ searchParams }) {
export default async function Home({ searchParams }) {
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="/revalidate-0/search-params">Clear Params</Link>
</>
......
......@@ -467,7 +467,7 @@ describe('app-custom-routes', () => {
})
})
describe('cookies().has()', () => {
describe('(await cookies()).has()', () => {
it('gets the correct values', async () => {
const res = await next.fetch(basePath + '/hooks/cookies/has')
......
......@@ -3,7 +3,7 @@ import { NextResponse } from 'next/server'
export const dynamic = 'force-static'
export function GET(req: Request) {
export async function GET(req: Request) {
return NextResponse.json({
nextUrl: {
href: (req as any).nextUrl.href,
......@@ -15,7 +15,7 @@ export function GET(req: Request) {
url: req.url,
headers: req.headers.get('accept'),
},
headers: headers().get('accept'),
cookies: cookies().get('session')?.value ?? null,
headers: (await headers()).get('accept'),
cookies: (await cookies()).get('session')?.value ?? null,
})
}
......@@ -4,7 +4,7 @@ import { getRequestMeta } from '../../../helpers'
export const runtime = 'experimental-edge'
export function GET() {
const meta = getRequestMeta(headers())
export async function GET() {
const meta = getRequestMeta(await headers())
return NextResponse.json(meta)
}
......@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
export async function GET() {
const c = cookies()
const c = await cookies()
c.set('a', 'a')
const hasCookie = c.has('a')
......
......@@ -2,7 +2,7 @@ import { cookies } from 'next/headers'
import { getRequestMeta, withRequestMeta } from '../../../helpers'
export async function GET() {
const c = cookies()
const c = await cookies()
// Put the request meta in the response directly as meta again.
const meta = getRequestMeta(c)
......
......@@ -2,7 +2,7 @@ import { headers } from 'next/headers'
import { getRequestMeta, withRequestMeta } from '../../../helpers'
export async function GET() {
const h = headers()
const h = await headers()
// Put the request meta in the response directly as meta again.
const meta = getRequestMeta(h)
......
......@@ -4,7 +4,7 @@ import { type NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
if (process.env.NEXT_PHASE === 'phase-production-build') {
// don't error during build
cookies()
await cookies()
} else {
const url = new URL('/basic/endpoint', request.nextUrl)
return NextResponse.rewrite(url)
......
......@@ -4,7 +4,7 @@ import { NextResponse } from 'next/server'
export async function GET() {
if (process.env.NEXT_PHASE === 'phase-production-build') {
// don't error during build
cookies()
await cookies()
} else {
return NextResponse.next()
}
......
......@@ -3,7 +3,7 @@ import { cookies } from 'next/headers'
export async function GET() {
if (process.env.NEXT_PHASE === 'phase-production-build') {
// don't error during build
cookies()
await cookies()
} else {
throw new Error('this is a runtime error')
}
......
import { draftMode } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server'
export function GET(req: NextRequest) {
export async function GET(req: NextRequest) {
const status = req.nextUrl.searchParams.get('status')
if (status === 'enable') {
draftMode().enable()
;(await draftMode()).enable()
} else {
draftMode().disable()
;(await draftMode()).disable()
}
return NextResponse.json({
......
import { notFound } from 'next/navigation'
export interface Props {
params: {
params: Promise<{
slug: string
}
}>
}
const Article = ({ params }: Props) => {
const { slug } = params
const Article = async ({ params }: Props) => {
const { slug } = await params
if (slug !== 'works') {
return notFound()
......
export default async function Page({ searchParams }) {
// this page is using searchParams to opt into dynamic rendering
import { unstable_noStore as noStore } from 'next/cache'
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
// that it's in a dynamic scope and shouldn't cache the fetch.
console.log(searchParams.q)
noStore()
const data1 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?1',
{ cache: 'default' }
......
......@@ -2,11 +2,11 @@ import { cookies } from 'next/headers'
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.
if (!process.env.__NEXT_EXPERIMENTAL_PPR) {
if (params.id.includes('static-bailout')) {
console.log('calling cookies', cookies())
console.log('calling cookies', await cookies())
}
}
return <p>Dynamic error</p>
......
export default function Hello({ params }) {
return <h1 id="slug">{params.slug}</h1>
export default async function Hello({ params }) {
return <h1 id="slug">{(await params).slug}</h1>
}
export function generateStaticParams() {
......
......@@ -2,8 +2,8 @@ import { cookies } from 'next/headers'
import Refresh from './refresh'
export default function Page() {
const cookieValue = cookies().get('test-cookie')
export default async function Page() {
const cookieValue = (await cookies()).get('test-cookie')
return (
<>
<Refresh />
......
......@@ -8,8 +8,10 @@ export const generateStaticParams = async () => {
return [{ slug: 'frameworks' }]
}
export default function Page({ params }) {
const result = cookies().get('session')?.value ? 'has cookie' : 'no cookie'
export default async function Page({ params }) {
const result = (await cookies()).get('session')?.value
? 'has cookie'
: 'no cookie'
return (
<div>
<div id="slug">{params.slug}</div>
......
export default function IdPage({ children, params, searchParams }) {
export default async function IdPage({ children, params, searchParams }) {
return (
<>
<p>
......@@ -6,8 +6,7 @@ export default function IdPage({ children, params, searchParams }) {
<span id="id-page-params">{JSON.stringify(params)}</span>
</p>
{children}
<p id="search-params">{JSON.stringify(searchParams)}</p>
<p id="search-params">{JSON.stringify(await searchParams)}</p>
</>
)
}
import Link from 'next/link'
export default function Page({ searchParams }) {
export default async function Page({ searchParams }) {
return (
<>
<h1 id="result">{JSON.stringify(searchParams)}</h1>
<h1 id="result">{JSON.stringify(await searchParams)}</h1>
<div>
<Link href="/navigation/searchparams?a=a">To A</Link>
</div>
......
'use client'
export default function Page({ params, searchParams }) {
export default async function Page({ params, searchParams }) {
return (
<h1
id="params-and-query"
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>
)
}
'use client'
import { use } from 'react'
export default function Page({ searchParams }) {
const sp = use(searchParams)
return (
<h1
id="params"
data-param-first={searchParams.first ?? 'N/A'}
data-param-second={searchParams.second ?? 'N/A'}
data-param-third={searchParams.third ?? 'N/A'}
data-param-not-real={searchParams.notReal ?? 'N/A'}
data-param-first={sp.first ?? 'N/A'}
data-param-second={sp.second ?? 'N/A'}
data-param-third={sp.third ?? 'N/A'}
data-param-not-real={sp.notReal ?? 'N/A'}
>
hello from searchParams prop client
</h1>
......
export default function Page({ searchParams }) {
export default async function Page({ searchParams }) {
const sp = await searchParams
return (
<h1
id="params"
data-param-first={searchParams.first ?? 'N/A'}
data-param-second={searchParams.second ?? 'N/A'}
data-param-third={searchParams.third ?? 'N/A'}
data-param-not-real={searchParams.notReal ?? 'N/A'}
data-param-first={sp.first ?? 'N/A'}
data-param-second={sp.second ?? 'N/A'}
data-param-third={sp.third ?? 'N/A'}
data-param-not-real={sp.notReal ?? 'N/A'}
>
hello from searchParams prop server
</h1>
......
......@@ -5,7 +5,7 @@ async function Suspend() {
await new Promise((resolve) => {
setTimeout(resolve, 3000)
})
cookies()
await cookies()
return <p>suspended content</p>
}
......
import Link from 'next/link'
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 (
<div>
{new Array(100).fill(0).map((_, i) => (
......
export default function Page({ params: { id } }) {
return <p>{id}</p>
export default async function Page({ params }: { params: Promise<{ id }> }) {
return <p>{(await params).id}</p>
}
import { draftMode } from 'next/headers'
export async function GET(request: Request) {
draftMode().disable()
;(await draftMode()).disable()
return new Response('Draft mode is disabled')
}
......@@ -16,7 +16,7 @@ export async function GET(request: Request) {
}
// Enable Draft Mode by setting the cookie
draftMode().enable()
;(await draftMode()).enable()
// Redirect to the path
redirect(`/${slug}`)
......
import { draftMode } from 'next/headers'
export default function PreviewPage() {
const { isEnabled } = draftMode()
export default async function PreviewPage() {
const { isEnabled } = await draftMode()
return <h1>{isEnabled ? 'draft' : 'none'}</h1>
}
import { NextResponse, type NextRequest } from 'next/server'
import { draftMode } from 'next/headers'
export function middleware(req: NextRequest) {
const { isEnabled } = draftMode()
export async function middleware(req: NextRequest) {
const { isEnabled } = await draftMode()
console.log('draftMode().isEnabled from middleware:', isEnabled)
return NextResponse.next()
}
......
import { draftMode } from 'next/headers'
export function GET() {
draftMode().disable()
export async function GET() {
;(await draftMode()).disable()
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 { redirect } from 'next/navigation'
export function GET(req: Request) {
draftMode().enable()
export async function GET(req: Request) {
;(await draftMode()).enable()
const to = new URL(req.url).searchParams.get('to') ?? '/some-other-page'
return redirect(to)
}
import { draftMode } from 'next/headers'
export function GET() {
draftMode().enable()
export async function GET() {
;(await draftMode()).enable()
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 { draftMode } from 'next/headers'
export default function Page() {
const { isEnabled } = draftMode()
export default async function Page() {
const { isEnabled } = await draftMode()
return (
<>
......
import { draftMode } from 'next/headers'
export function GET() {
const { isEnabled } = draftMode()
export async function GET() {
const { isEnabled } = await draftMode()
return new Response(isEnabled ? 'ENABLED' : 'DISABLED')
}
import React from 'react'
import { cookies, draftMode } from 'next/headers'
export default function Page() {
const { isEnabled } = draftMode()
export default async function Page() {
const { isEnabled } = await draftMode()
let data: string | undefined
if (isEnabled) {
data = cookies().get('data')?.value
data = (await cookies()).get('data')?.value
}
return (
......
import { draftMode } from 'next/headers'
export function GET() {
draftMode().disable()
export async function GET() {
;(await draftMode()).disable()
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 { redirect } from 'next/navigation'
export function GET(req: Request) {
draftMode().enable()
export async function GET(req: Request) {
;(await draftMode()).enable()
const to = new URL(req.url).searchParams.get('to') ?? '/some-other-page'
return redirect(to)
}
import { draftMode } from 'next/headers'
export function GET() {
draftMode().enable()
export async function GET() {
;(await draftMode()).enable()
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 { draftMode } from 'next/headers'
export default function Page() {
const { isEnabled } = draftMode()
export default async function Page() {
const { isEnabled } = await draftMode()
return (
<>
......
import { draftMode } from 'next/headers'
export function GET() {
const { isEnabled } = draftMode()
export async function GET() {
const { isEnabled } = await draftMode()
return new Response(isEnabled ? 'ENABLED' : 'DISABLED')
}
import React from 'react'
import { cookies, draftMode } from 'next/headers'
export default function Page() {
const { isEnabled } = draftMode()
export default async function Page() {
const { isEnabled } = await draftMode()
let data: string | undefined
if (isEnabled) {
data = cookies().get('data')?.value
data = (await cookies()).get('data')?.value
}
return (
......
......@@ -4,7 +4,6 @@ import { unstable_cache as cache } from 'next/cache'
const cookies = cache(() => nextCookies())
export default async function Page({ searchParams }) {
console.log('cookies()', await cookies())
return (
<div>
<section>
......@@ -13,22 +12,20 @@ export default async function Page({ searchParams }) {
</section>
<section id="cookies">
<h3>cookies</h3>
{cookies()
.getAll()
.map((cookie) => {
const key = cookie.name
let value = cookie.value
{(await cookies()).getAll().map((cookie) => {
const key = cookie.name
let value = cookie.value
if (key === 'userCache') {
value = value.slice(0, 10) + '...'
}
return (
<div key={key}>
<h4>{key}</h4>
<pre className={key}>{value}</pre>
</div>
)
})}
if (key === 'userCache') {
value = value.slice(0, 10) + '...'
}
return (
<div key={key}>
<h4>{key}</h4>
<pre className={key}>{value}</pre>
</div>
)
})}
</section>
</div>
)
......
'use client'
import { PageSentinel } from '../getSentinelValue'
export default async function Page({ searchParams }) {
const { __TEST_SENTINEL } = process.env
return (
<div>
<div id="page">{__TEST_SENTINEL}</div>
<PageSentinel />
<section>
This example uses headers/cookies/searchParams directly in a Page
configured with `dynamic = 'force-dynamic'`. This should cause the page
......@@ -20,7 +21,7 @@ export default async function Page({ searchParams }) {
</section>
<section id="searchparams">
<h3>searchParams</h3>
{Object.entries(searchParams).map(([key, value]) => {
{Object.entries(await searchParams).map(([key, value]) => {
return (
<div key={key}>
<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