| import type { NextConfig } from '../../config-shared' |
| import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition' |
| import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config' |
| import type { NextRequest } from '../../web/spec-extension/request' |
| import type { PrerenderManifest } from '../../../build' |
| import type { NextURL } from '../../web/next-url' |
| import type { DeepReadonly } from '../../../shared/lib/deep-readonly' |
| import type { WorkUnitStore } from '../../app-render/work-unit-async-storage.external' |
|
|
| import { |
| RouteModule, |
| type RouteModuleHandleContext, |
| type RouteModuleOptions, |
| } from '../route-module' |
| import { createRequestStoreForAPI } from '../../async-storage/request-store' |
| import { |
| createWorkStore, |
| type WorkStoreContext, |
| } from '../../async-storage/work-store' |
| import { type HTTP_METHOD, HTTP_METHODS, isHTTPMethod } from '../../web/http' |
| import { getImplicitTags, type ImplicitTags } from '../../lib/implicit-tags' |
| import { patchFetch } from '../../lib/patch-fetch' |
| import { getTracer } from '../../lib/trace/tracer' |
| import { AppRouteRouteHandlersSpan } from '../../lib/trace/constants' |
| import { getPathnameFromAbsolutePath } from './helpers/get-pathname-from-absolute-path' |
| import * as Log from '../../../build/output/log' |
| import { autoImplementMethods } from './helpers/auto-implement-methods' |
| import { |
| appendMutableCookies, |
| type ReadonlyRequestCookies, |
| } from '../../web/spec-extension/adapters/request-cookies' |
| import { HeadersAdapter } from '../../web/spec-extension/adapters/headers' |
| import { RequestCookiesAdapter } from '../../web/spec-extension/adapters/request-cookies' |
| import { parsedUrlQueryToParams } from './helpers/parsed-url-query-to-params' |
| import { printDebugThrownValueForProspectiveRender } from '../../app-render/prospective-render-utils' |
|
|
| import * as serverHooks from '../../../client/components/hooks-server-context' |
| import { DynamicServerError } from '../../../client/components/hooks-server-context' |
|
|
| import { |
| workAsyncStorage, |
| type WorkStore, |
| } from '../../app-render/work-async-storage.external' |
| import { |
| workUnitAsyncStorage, |
| type RequestStore, |
| type PrerenderStore, |
| } from '../../app-render/work-unit-async-storage.external' |
| import { |
| actionAsyncStorage, |
| type ActionStore, |
| } from '../../app-render/action-async-storage.external' |
| import * as sharedModules from './shared-modules' |
| import { getIsPossibleServerAction } from '../../lib/server-action-request-meta' |
| import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' |
| import { cleanURL } from './helpers/clean-url' |
| import { StaticGenBailoutError } from '../../../client/components/static-generation-bailout' |
| import { isStaticGenEnabled } from './helpers/is-static-gen-enabled' |
| import { |
| abortAndThrowOnSynchronousRequestDataAccess, |
| postponeWithTracking, |
| createDynamicTrackingState, |
| getFirstDynamicReason, |
| } from '../../app-render/dynamic-rendering' |
| 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' |
| import type { AppSegment } from '../../../build/segment-config/app/app-segments' |
| import { |
| getRedirectStatusCodeFromError, |
| getURLFromRedirectError, |
| } from '../../../client/components/redirect' |
| import { |
| isRedirectError, |
| type RedirectError, |
| } from '../../../client/components/redirect-error' |
| import { |
| getAccessFallbackHTTPStatus, |
| isHTTPAccessFallbackError, |
| } from '../../../client/components/http-access-fallback/http-access-fallback' |
| import { RedirectStatusCode } from '../../../client/components/redirect-status-code' |
| import { INFINITE_CACHE } from '../../../lib/constants' |
| import { executeRevalidates } from '../../revalidation-utils' |
| import { trackPendingModules } from '../../app-render/module-loading/track-module-loading.external' |
| import { InvariantError } from '../../../shared/lib/invariant-error' |
|
|
| export class WrappedNextRouterError { |
| constructor( |
| public readonly error: RedirectError, |
| public readonly headers?: Headers |
| ) {} |
| } |
|
|
| |
| |
| |
| |
| export type AppRouteModule = typeof import('../../../build/templates/app-route') |
|
|
| export type AppRouteSharedContext = { |
| buildId: string |
| } |
|
|
| |
| |
| |
| |
| export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext { |
| renderOpts: WorkStoreContext['renderOpts'] & |
| Pick<RenderOptsPartial, 'onInstrumentationRequestError'> & |
| CollectedCacheInfo |
| prerenderManifest: DeepReadonly<PrerenderManifest> |
| sharedContext: AppRouteSharedContext |
| } |
|
|
| type CollectedCacheInfo = { |
| collectedTags?: string |
| collectedRevalidate?: number |
| collectedExpire?: number |
| collectedStale?: number |
| } |
|
|
| |
| |
| |
| |
| type AppRouteHandlerFnContext = { |
| params?: Promise<Record<string, string | string[] | undefined>> |
| } |
|
|
| |
| |
| |
| |
| export type AppRouteHandlerFn = ( |
| |
| |
| |
| req: NextRequest, |
| |
| |
| |
| |
| ctx: AppRouteHandlerFnContext |
| ) => unknown |
|
|
| |
| |
| |
| |
| export type AppRouteHandlers = { |
| [method in HTTP_METHOD]?: AppRouteHandlerFn |
| } |
|
|
| |
| |
| |
| |
| export type AppRouteUserlandModule = AppRouteHandlers & |
| Pick< |
| AppSegmentConfig, |
| 'dynamic' | 'revalidate' | 'dynamicParams' | 'fetchCache' |
| > & |
| Pick<AppSegment, 'generateStaticParams'> |
|
|
| |
| |
| |
| |
| export interface AppRouteRouteModuleOptions |
| extends RouteModuleOptions<AppRouteRouteDefinition, AppRouteUserlandModule> { |
| readonly resolvedPagePath: string |
| readonly nextConfigOutput: NextConfig['output'] |
| } |
|
|
| |
| |
| |
| export class AppRouteRouteModule extends RouteModule< |
| AppRouteRouteDefinition, |
| AppRouteUserlandModule |
| > { |
| |
| |
| |
| public readonly workUnitAsyncStorage = workUnitAsyncStorage |
|
|
| |
| |
| |
| public readonly workAsyncStorage = workAsyncStorage |
|
|
| |
| |
| |
| |
| public readonly serverHooks = serverHooks |
|
|
| public static readonly sharedModules = sharedModules |
|
|
| |
| |
| |
| |
| public readonly actionAsyncStorage = actionAsyncStorage |
|
|
| public readonly resolvedPagePath: string |
| public readonly nextConfigOutput: NextConfig['output'] | undefined |
|
|
| private readonly methods: Record<HTTP_METHOD, AppRouteHandlerFn> |
| private readonly hasNonStaticMethods: boolean |
| private readonly dynamic: AppRouteUserlandModule['dynamic'] |
|
|
| constructor({ |
| userland, |
| definition, |
| distDir, |
| relativeProjectDir, |
| resolvedPagePath, |
| nextConfigOutput, |
| }: AppRouteRouteModuleOptions) { |
| super({ userland, definition, distDir, relativeProjectDir }) |
|
|
| this.resolvedPagePath = resolvedPagePath |
| this.nextConfigOutput = nextConfigOutput |
|
|
| |
| |
| this.methods = autoImplementMethods(userland) |
| this.isAppRouter = true |
|
|
| |
| this.hasNonStaticMethods = hasNonStaticMethods(userland) |
|
|
| |
| this.dynamic = this.userland.dynamic |
| if (this.nextConfigOutput === 'export') { |
| if (this.dynamic === 'force-dynamic') { |
| throw new Error( |
| `export const dynamic = "force-dynamic" on page "${definition.pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export` |
| ) |
| } else if (!isStaticGenEnabled(this.userland) && this.userland['GET']) { |
| throw new Error( |
| `export const dynamic = "force-static"/export const revalidate not configured on route "${definition.pathname}" with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export` |
| ) |
| } else { |
| this.dynamic = 'error' |
| } |
| } |
|
|
| |
| |
| if (process.env.NODE_ENV === 'development') { |
| |
| |
| const lowercased = HTTP_METHODS.map((method) => method.toLowerCase()) |
| for (const method of lowercased) { |
| if (method in this.userland) { |
| Log.error( |
| `Detected lowercase method '${method}' in '${ |
| this.resolvedPagePath |
| }'. Export the uppercase '${method.toUpperCase()}' method name to fix this error.` |
| ) |
| } |
| } |
|
|
| |
| |
| if ('default' in this.userland) { |
| Log.error( |
| `Detected default export in '${this.resolvedPagePath}'. Export a named export for each HTTP method instead.` |
| ) |
| } |
|
|
| |
| |
| if (!HTTP_METHODS.some((method) => method in this.userland)) { |
| Log.error( |
| `No HTTP methods exported in '${this.resolvedPagePath}'. Export a named export for each HTTP method.` |
| ) |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| private resolve(method: string): AppRouteHandlerFn { |
| |
| if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 }) |
|
|
| |
| return this.methods[method] |
| } |
|
|
| private async do( |
| handler: AppRouteHandlerFn, |
| actionStore: ActionStore, |
| workStore: WorkStore, |
| |
| |
| |
| requestStore: RequestStore, |
| implicitTags: ImplicitTags, |
| request: NextRequest, |
| context: AppRouteRouteHandlerContext |
| ) { |
| const isStaticGeneration = workStore.isStaticGeneration |
| const cacheComponentsEnabled = |
| !!context.renderOpts.experimental?.cacheComponents |
|
|
| |
| patchFetch({ |
| workAsyncStorage: this.workAsyncStorage, |
| workUnitAsyncStorage: this.workUnitAsyncStorage, |
| }) |
|
|
| const handlerContext: AppRouteHandlerFnContext = { |
| params: context.params |
| ? createServerParamsForRoute( |
| parsedUrlQueryToParams(context.params), |
| workStore |
| ) |
| : undefined, |
| } |
|
|
| const resolvePendingRevalidations = () => { |
| context.renderOpts.pendingWaitUntil = executeRevalidates( |
| workStore |
| ).finally(() => { |
| if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { |
| console.log( |
| 'pending revalidates promise finished for:', |
| requestStore.url |
| ) |
| } |
| }) |
| } |
|
|
| let prerenderStore: null | PrerenderStore = null |
|
|
| let res: unknown |
| try { |
| if (isStaticGeneration) { |
| const userlandRevalidate = this.userland.revalidate |
| const defaultRevalidate: number = |
| |
| |
| |
| userlandRevalidate === false || userlandRevalidate === undefined |
| ? INFINITE_CACHE |
| : userlandRevalidate |
|
|
| if (cacheComponentsEnabled) { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const prospectiveController = new AbortController() |
| let prospectiveRenderIsDynamic = false |
| const cacheSignal = new CacheSignal() |
| let dynamicTracking = createDynamicTrackingState(undefined) |
|
|
| const prospectiveRoutePrerenderStore: PrerenderStore = |
| (prerenderStore = { |
| type: 'prerender', |
| phase: 'action', |
| |
| |
| rootParams: {}, |
| fallbackRouteParams: null, |
| implicitTags, |
| renderSignal: prospectiveController.signal, |
| controller: prospectiveController, |
| cacheSignal, |
| |
| |
| dynamicTracking, |
| allowEmptyStaticShell: false, |
| revalidate: defaultRevalidate, |
| expire: INFINITE_CACHE, |
| stale: INFINITE_CACHE, |
| tags: [...implicitTags.tags], |
| |
| prerenderResumeDataCache: null, |
| renderResumeDataCache: null, |
| hmrRefreshHash: undefined, |
| captureOwnerStack: undefined, |
| }) |
|
|
| let prospectiveResult |
| try { |
| prospectiveResult = this.workUnitAsyncStorage.run( |
| prospectiveRoutePrerenderStore, |
| handler, |
| request, |
| handlerContext |
| ) |
| } catch (err) { |
| if (prospectiveController.signal.aborted) { |
| |
| |
| prospectiveRenderIsDynamic = true |
| } else if ( |
| process.env.NEXT_DEBUG_BUILD || |
| process.env.__NEXT_VERBOSE_LOGGING |
| ) { |
| printDebugThrownValueForProspectiveRender(err, workStore.route) |
| } |
| } |
| if ( |
| typeof prospectiveResult === 'object' && |
| prospectiveResult !== null && |
| typeof (prospectiveResult as any).then === 'function' |
| ) { |
| |
| |
| ;(prospectiveResult as any as Promise<unknown>).then( |
| () => {}, |
| (err) => { |
| if (prospectiveController.signal.aborted) { |
| |
| |
| prospectiveRenderIsDynamic = true |
| } else if (process.env.NEXT_DEBUG_BUILD) { |
| printDebugThrownValueForProspectiveRender( |
| err, |
| workStore.route |
| ) |
| } |
| } |
| ) |
| } |
|
|
| trackPendingModules(cacheSignal) |
| await cacheSignal.cacheReady() |
|
|
| if (prospectiveRenderIsDynamic) { |
| |
| |
| const dynamicReason = getFirstDynamicReason(dynamicTracking) |
| if (dynamicReason) { |
| throw new DynamicServerError( |
| `Route ${workStore.route} couldn't be rendered statically because it used \`${dynamicReason}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` |
| ) |
| } else { |
| console.error( |
| 'Expected Next.js to keep track of reason for opting out of static rendering but one was not found. This is a bug in Next.js' |
| ) |
| throw new DynamicServerError( |
| `Route ${workStore.route} couldn't be rendered statically because it used a dynamic API. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` |
| ) |
| } |
| } |
|
|
| |
| |
| |
| const finalController = new AbortController() |
| dynamicTracking = createDynamicTrackingState(undefined) |
|
|
| const finalRoutePrerenderStore: PrerenderStore = (prerenderStore = { |
| type: 'prerender', |
| phase: 'action', |
| rootParams: {}, |
| fallbackRouteParams: null, |
| implicitTags, |
| renderSignal: finalController.signal, |
| controller: finalController, |
| cacheSignal: null, |
| dynamicTracking, |
| allowEmptyStaticShell: false, |
| revalidate: defaultRevalidate, |
| expire: INFINITE_CACHE, |
| stale: INFINITE_CACHE, |
| tags: [...implicitTags.tags], |
| |
| prerenderResumeDataCache: null, |
| renderResumeDataCache: null, |
| hmrRefreshHash: undefined, |
| captureOwnerStack: undefined, |
| }) |
|
|
| let responseHandled = false |
| res = await new Promise((resolve, reject) => { |
| scheduleImmediate(async () => { |
| try { |
| const result = await (this.workUnitAsyncStorage.run( |
| finalRoutePrerenderStore, |
| handler, |
| request, |
| handlerContext |
| ) as Promise<Response>) |
| if (responseHandled) { |
| |
| return |
| } else if (!(result instanceof Response)) { |
| |
| resolve(result) |
| return |
| } |
|
|
| responseHandled = true |
|
|
| let bodyHandled = false |
| result.arrayBuffer().then((body) => { |
| if (!bodyHandled) { |
| bodyHandled = true |
|
|
| resolve( |
| new Response(body, { |
| headers: result.headers, |
| status: result.status, |
| statusText: result.statusText, |
| }) |
| ) |
| } |
| }, reject) |
| scheduleImmediate(() => { |
| if (!bodyHandled) { |
| bodyHandled = true |
| finalController.abort() |
| reject(createCacheComponentsError(workStore.route)) |
| } |
| }) |
| } catch (err) { |
| reject(err) |
| } |
| }) |
| scheduleImmediate(() => { |
| if (!responseHandled) { |
| responseHandled = true |
| finalController.abort() |
| reject(createCacheComponentsError(workStore.route)) |
| } |
| }) |
| }) |
| if (finalController.signal.aborted) { |
| |
| throw createCacheComponentsError(workStore.route) |
| } else { |
| |
| |
| |
| finalController.abort() |
| } |
| } else { |
| prerenderStore = { |
| type: 'prerender-legacy', |
| phase: 'action', |
| rootParams: {}, |
| implicitTags, |
| revalidate: defaultRevalidate, |
| expire: INFINITE_CACHE, |
| stale: INFINITE_CACHE, |
| tags: [...implicitTags.tags], |
| } |
|
|
| res = await workUnitAsyncStorage.run( |
| prerenderStore, |
| handler, |
| request, |
| handlerContext |
| ) |
| } |
| } else { |
| res = await workUnitAsyncStorage.run( |
| requestStore, |
| handler, |
| request, |
| handlerContext |
| ) |
| } |
| } catch (err) { |
| if (isRedirectError(err)) { |
| const url = getURLFromRedirectError(err) |
| if (!url) { |
| throw new Error('Invariant: Unexpected redirect url format') |
| } |
|
|
| |
| |
| const headers = new Headers({ Location: url }) |
|
|
| |
| |
| |
| |
| appendMutableCookies(headers, requestStore.mutableCookies) |
|
|
| resolvePendingRevalidations() |
|
|
| |
| return new Response(null, { |
| |
| |
| |
| status: actionStore.isAction |
| ? RedirectStatusCode.SeeOther |
| : getRedirectStatusCodeFromError(err), |
| headers, |
| }) |
| } else if (isHTTPAccessFallbackError(err)) { |
| const httpStatus = getAccessFallbackHTTPStatus(err) |
| return new Response(null, { status: httpStatus }) |
| } |
|
|
| throw err |
| } |
|
|
| |
| if (!(res instanceof Response)) { |
| throw new Error( |
| `No response is returned from route handler '${this.resolvedPagePath}'. Ensure you return a \`Response\` or a \`NextResponse\` in all branches of your handler.` |
| ) |
| } |
|
|
| context.renderOpts.fetchMetrics = workStore.fetchMetrics |
|
|
| resolvePendingRevalidations() |
|
|
| if (prerenderStore) { |
| context.renderOpts.collectedTags = prerenderStore.tags?.join(',') |
| context.renderOpts.collectedRevalidate = prerenderStore.revalidate |
| context.renderOpts.collectedExpire = prerenderStore.expire |
| context.renderOpts.collectedStale = prerenderStore.stale |
| } |
|
|
| |
| |
| |
| const headers = new Headers(res.headers) |
| if (appendMutableCookies(headers, requestStore.mutableCookies)) { |
| return new Response(res.body, { |
| status: res.status, |
| statusText: res.statusText, |
| headers, |
| }) |
| } |
|
|
| return res |
| } |
|
|
| public async handle( |
| req: NextRequest, |
| context: AppRouteRouteHandlerContext |
| ): Promise<Response> { |
| |
| const handler = this.resolve(req.method) |
|
|
| |
| const staticGenerationContext: WorkStoreContext = { |
| page: this.definition.page, |
| renderOpts: context.renderOpts, |
| buildId: context.sharedContext.buildId, |
| previouslyRevalidatedTags: [], |
| } |
|
|
| |
| staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache |
|
|
| const actionStore: ActionStore = { |
| isAppRoute: true, |
| isAction: getIsPossibleServerAction(req), |
| } |
|
|
| const implicitTags = await getImplicitTags( |
| this.definition.page, |
| req.nextUrl, |
| |
| null |
| ) |
|
|
| const requestStore = createRequestStoreForAPI( |
| req, |
| req.nextUrl, |
| implicitTags, |
| undefined, |
| context.prerenderManifest.preview |
| ) |
|
|
| const workStore = createWorkStore(staticGenerationContext) |
|
|
| |
| |
| |
| const response: unknown = await this.actionAsyncStorage.run( |
| actionStore, |
| () => |
| this.workUnitAsyncStorage.run(requestStore, () => |
| this.workAsyncStorage.run(workStore, async () => { |
| |
| |
| if (this.hasNonStaticMethods) { |
| if (workStore.isStaticGeneration) { |
| const err = new DynamicServerError( |
| 'Route is configured with methods that cannot be statically generated.' |
| ) |
| workStore.dynamicUsageDescription = err.message |
| workStore.dynamicUsageStack = err.stack |
| throw err |
| } |
| } |
|
|
| |
| |
| let request = req |
|
|
| |
| switch (this.dynamic) { |
| case 'force-dynamic': { |
| |
| workStore.forceDynamic = true |
| if (workStore.isStaticGeneration) { |
| const err = new DynamicServerError( |
| 'Route is configured with dynamic = error which cannot be statically generated.' |
| ) |
| workStore.dynamicUsageDescription = err.message |
| workStore.dynamicUsageStack = err.stack |
| throw err |
| } |
| break |
| } |
| case 'force-static': |
| |
| |
| workStore.forceStatic = true |
| |
| |
| request = new Proxy(req, forceStaticRequestHandlers) |
| break |
| case 'error': |
| |
| |
| workStore.dynamicShouldError = true |
| if (workStore.isStaticGeneration) |
| request = new Proxy(req, requireStaticRequestHandlers) |
| break |
| case undefined: |
| case 'auto': |
| |
| |
| request = proxyNextRequest(req, workStore) |
| break |
| default: |
| this.dynamic satisfies never |
| } |
|
|
| |
| const route = getPathnameFromAbsolutePath(this.resolvedPagePath) |
|
|
| const tracer = getTracer() |
|
|
| |
| tracer.setRootSpanAttribute('next.route', route) |
|
|
| return tracer.trace( |
| AppRouteRouteHandlersSpan.runHandler, |
| { |
| spanName: `executing api route (app) ${route}`, |
| attributes: { |
| 'next.route': route, |
| }, |
| }, |
| async () => |
| this.do( |
| handler, |
| actionStore, |
| workStore, |
| requestStore, |
| implicitTags, |
| request, |
| context |
| ) |
| ) |
| }) |
| ) |
| ) |
|
|
| |
| |
| if (!(response instanceof Response)) { |
| |
| return new Response(null, { status: 500 }) |
| } |
|
|
| if (response.headers.has('x-middleware-rewrite')) { |
| throw new Error( |
| 'NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue.' |
| ) |
| } |
|
|
| if (response.headers.get('x-middleware-next') === '1') { |
| |
| throw new Error( |
| 'NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler' |
| ) |
| } |
|
|
| return response |
| } |
| } |
|
|
| export default AppRouteRouteModule |
|
|
| |
| |
| |
| |
| |
| |
| |
| export function hasNonStaticMethods(handlers: AppRouteHandlers): boolean { |
| if ( |
| |
| handlers.POST || |
| handlers.PUT || |
| handlers.DELETE || |
| handlers.PATCH || |
| handlers.OPTIONS |
| ) { |
| return true |
| } |
| return false |
| } |
|
|
| |
| |
| const nextURLSymbol = Symbol('nextUrl') |
| const requestCloneSymbol = Symbol('clone') |
| const urlCloneSymbol = Symbol('clone') |
| const searchParamsSymbol = Symbol('searchParams') |
| const hrefSymbol = Symbol('href') |
| const toStringSymbol = Symbol('toString') |
| const headersSymbol = Symbol('headers') |
| const cookiesSymbol = Symbol('cookies') |
|
|
| type RequestSymbolTarget = { |
| [headersSymbol]?: Headers |
| [cookiesSymbol]?: RequestCookies | ReadonlyRequestCookies |
| [nextURLSymbol]?: NextURL |
| [requestCloneSymbol]?: () => NextRequest |
| } |
|
|
| type UrlSymbolTarget = { |
| [searchParamsSymbol]?: URLSearchParams |
| [hrefSymbol]?: string |
| [toStringSymbol]?: () => string |
| [urlCloneSymbol]?: () => NextURL |
| } |
|
|
| |
| |
| |
| |
| |
| const forceStaticRequestHandlers = { |
| get( |
| target: NextRequest & RequestSymbolTarget, |
| prop: string | symbol, |
| receiver: any |
| ): unknown { |
| switch (prop) { |
| case 'headers': |
| return ( |
| target[headersSymbol] || |
| (target[headersSymbol] = HeadersAdapter.seal(new Headers({}))) |
| ) |
| case 'cookies': |
| return ( |
| target[cookiesSymbol] || |
| (target[cookiesSymbol] = RequestCookiesAdapter.seal( |
| new RequestCookies(new Headers({})) |
| )) |
| ) |
| case 'nextUrl': |
| return ( |
| target[nextURLSymbol] || |
| (target[nextURLSymbol] = new Proxy( |
| target.nextUrl, |
| forceStaticNextUrlHandlers |
| )) |
| ) |
| case 'url': |
| |
| |
| |
| return receiver.nextUrl.href |
| case 'geo': |
| case 'ip': |
| return undefined |
| case 'clone': |
| return ( |
| target[requestCloneSymbol] || |
| (target[requestCloneSymbol] = () => |
| new Proxy( |
| |
| |
| |
| |
| |
| |
| |
| target.clone() as NextRequest, |
| forceStaticRequestHandlers |
| )) |
| ) |
| default: |
| return ReflectAdapter.get(target, prop, receiver) |
| } |
| }, |
| |
| |
| } |
|
|
| const forceStaticNextUrlHandlers = { |
| get( |
| target: NextURL & UrlSymbolTarget, |
| prop: string | symbol, |
| receiver: any |
| ): unknown { |
| switch (prop) { |
| |
| case 'search': |
| return '' |
| case 'searchParams': |
| return ( |
| target[searchParamsSymbol] || |
| (target[searchParamsSymbol] = new URLSearchParams()) |
| ) |
| case 'href': |
| return ( |
| target[hrefSymbol] || |
| (target[hrefSymbol] = cleanURL(target.href).href) |
| ) |
| case 'toJSON': |
| case 'toString': |
| return ( |
| target[toStringSymbol] || |
| (target[toStringSymbol] = () => receiver.href) |
| ) |
|
|
| |
| case 'url': |
| |
| |
| |
| return undefined |
| case 'clone': |
| return ( |
| target[urlCloneSymbol] || |
| (target[urlCloneSymbol] = () => |
| new Proxy(target.clone(), forceStaticNextUrlHandlers)) |
| ) |
| default: |
| return ReflectAdapter.get(target, prop, receiver) |
| } |
| }, |
| } |
|
|
| function proxyNextRequest(request: NextRequest, workStore: WorkStore) { |
| const nextUrlHandlers = { |
| get( |
| target: NextURL & UrlSymbolTarget, |
| prop: string | symbol, |
| receiver: any |
| ): unknown { |
| switch (prop) { |
| case 'search': |
| case 'searchParams': |
| case 'url': |
| case 'href': |
| case 'toJSON': |
| case 'toString': |
| case 'origin': { |
| const workUnitStore = workUnitAsyncStorage.getStore() |
| trackDynamic(workStore, workUnitStore, `nextUrl.${prop}`) |
| return ReflectAdapter.get(target, prop, receiver) |
| } |
| case 'clone': |
| return ( |
| target[urlCloneSymbol] || |
| (target[urlCloneSymbol] = () => |
| new Proxy(target.clone(), nextUrlHandlers)) |
| ) |
| default: |
| return ReflectAdapter.get(target, prop, receiver) |
| } |
| }, |
| } |
|
|
| const nextRequestHandlers = { |
| get( |
| target: NextRequest & RequestSymbolTarget, |
| prop: string | symbol |
| ): unknown { |
| switch (prop) { |
| case 'nextUrl': |
| return ( |
| target[nextURLSymbol] || |
| (target[nextURLSymbol] = new Proxy(target.nextUrl, nextUrlHandlers)) |
| ) |
| case 'headers': |
| case 'cookies': |
| case 'url': |
| case 'body': |
| case 'blob': |
| case 'json': |
| case 'text': |
| case 'arrayBuffer': |
| case 'formData': { |
| const workUnitStore = workUnitAsyncStorage.getStore() |
| trackDynamic(workStore, workUnitStore, `request.${prop}`) |
| |
| |
| |
| return ReflectAdapter.get(target, prop, target) |
| } |
| case 'clone': |
| return ( |
| target[requestCloneSymbol] || |
| (target[requestCloneSymbol] = () => |
| new Proxy( |
| |
| |
| |
| |
| |
| |
| |
| target.clone() as NextRequest, |
| nextRequestHandlers |
| )) |
| ) |
| default: |
| |
| |
| |
| return ReflectAdapter.get(target, prop, target) |
| } |
| }, |
| |
| |
| } |
|
|
| return new Proxy(request, nextRequestHandlers) |
| } |
|
|
| const requireStaticRequestHandlers = { |
| get( |
| target: NextRequest & RequestSymbolTarget, |
| prop: string | symbol, |
| receiver: any |
| ): unknown { |
| switch (prop) { |
| case 'nextUrl': |
| return ( |
| target[nextURLSymbol] || |
| (target[nextURLSymbol] = new Proxy( |
| target.nextUrl, |
| requireStaticNextUrlHandlers |
| )) |
| ) |
| case 'headers': |
| case 'cookies': |
| case 'url': |
| case 'body': |
| case 'blob': |
| case 'json': |
| case 'text': |
| case 'arrayBuffer': |
| case 'formData': |
| throw new StaticGenBailoutError( |
| `Route ${target.nextUrl.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`request.${prop}\`.` |
| ) |
| case 'clone': |
| return ( |
| target[requestCloneSymbol] || |
| (target[requestCloneSymbol] = () => |
| new Proxy( |
| |
| |
| |
| |
| |
| |
| |
| target.clone() as NextRequest, |
| requireStaticRequestHandlers |
| )) |
| ) |
| default: |
| return ReflectAdapter.get(target, prop, receiver) |
| } |
| }, |
| |
| |
| } |
|
|
| const requireStaticNextUrlHandlers = { |
| get( |
| target: NextURL & UrlSymbolTarget, |
| prop: string | symbol, |
| receiver: any |
| ): unknown { |
| switch (prop) { |
| case 'search': |
| case 'searchParams': |
| case 'url': |
| case 'href': |
| case 'toJSON': |
| case 'toString': |
| case 'origin': |
| throw new StaticGenBailoutError( |
| `Route ${target.pathname} with \`dynamic = "error"\` couldn't be rendered statically because it used \`nextUrl.${prop}\`.` |
| ) |
| case 'clone': |
| return ( |
| target[urlCloneSymbol] || |
| (target[urlCloneSymbol] = () => |
| new Proxy(target.clone(), requireStaticNextUrlHandlers)) |
| ) |
| default: |
| return ReflectAdapter.get(target, prop, receiver) |
| } |
| }, |
| } |
|
|
| function createCacheComponentsError(route: string) { |
| return new DynamicServerError( |
| `Route ${route} couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/cache-components` |
| ) |
| } |
|
|
| function trackDynamic( |
| store: WorkStore, |
| workUnitStore: undefined | WorkUnitStore, |
| expression: string |
| ): void { |
| if (store.dynamicShouldError) { |
| throw new StaticGenBailoutError( |
| `Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` |
| ) |
| } |
|
|
| if (workUnitStore) { |
| switch (workUnitStore.type) { |
| case 'cache': |
| case 'private-cache': |
| |
| |
| throw new Error( |
| `Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` |
| ) |
| case 'unstable-cache': |
| throw new Error( |
| `Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` |
| ) |
| case 'prerender': |
| const error = new Error( |
| `Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request` |
| ) |
| return abortAndThrowOnSynchronousRequestDataAccess( |
| store.route, |
| expression, |
| error, |
| workUnitStore |
| ) |
| case 'prerender-client': |
| throw new InvariantError( |
| 'A client prerender store should not be used for a route handler.' |
| ) |
| case 'prerender-ppr': |
| return postponeWithTracking( |
| store.route, |
| expression, |
| workUnitStore.dynamicTracking |
| ) |
| case 'prerender-legacy': |
| workUnitStore.revalidate = 0 |
|
|
| const err = new DynamicServerError( |
| `Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` |
| ) |
| store.dynamicUsageDescription = expression |
| store.dynamicUsageStack = err.stack |
|
|
| throw err |
| case 'request': |
| if (process.env.NODE_ENV !== 'production') { |
| |
| |
| workUnitStore.usedDynamic = true |
| } |
| break |
| default: |
| workUnitStore satisfies never |
| } |
| } |
| } |
|
|