Unverified Commit 586c1ed7 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update deploy adapters outputs and handler interfaces for node and edge (#88247)

This updates to expand our normalized interface of handler(req, ctx) to
edge runtime as well and middleware. This also applies some fixes for
outputs and routes for app router. Validated against our test suite here
https://github.com/vercel/vercel/pull/14102 to start.

Once https://github.com/nextjs/adapter-vercel/pull/6 is landed we can
start wiring up the full E2E test suite for validating.
parent 1ea5b078
......@@ -38,6 +38,7 @@ import {
JSON_CONTENT_TYPE_HEADER,
NEXT_RESUME_HEADER,
} from '../../lib/constants'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import { getRedirectStatus, modifyRouteRegex } from '../../lib/redirect-status'
......@@ -47,6 +48,7 @@ import { sortSortableRoutes } from '../../shared/lib/router/utils/sortable-route
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import { defaultOverrides } from '../../server/require-hook'
import { makeIgnoreFn } from '../collect-build-traces'
import { generateRoutesManifest } from '../generate-routes-manifest'
interface SharedRouteFields {
/**
......@@ -356,6 +358,7 @@ export interface NextAdapter {
* and there are pages router items to resolve.
*/
shouldNormalizeNextData: boolean
rsc: RoutesManifest['rsc']
}
outputs: AdapterOutputs
/**
......@@ -410,6 +413,7 @@ function normalizePathnames(
export async function handleBuildComplete({
dir,
config,
appType,
buildId,
configOutDir,
distDir,
......@@ -431,6 +435,7 @@ export async function handleBuildComplete({
functionsConfigManifest,
}: {
dir: string
appType: 'app' | 'pages' | 'hybrid'
distDir: string
buildId: string
configOutDir: string
......@@ -888,6 +893,16 @@ export async function handleBuildComplete({
pathname: dataPathname,
id: dataPathname,
})
if (appPageKeys && appPageKeys.length > 0) {
const rscPage = `${page === '/' ? '/index' : page}.rsc`
outputs.staticFiles.push({
id: rscPage,
pathname: rscPage,
type: AdapterOutputType.STATIC_FILE,
filePath: rscFallbackPath,
})
}
}
for (const locale of config.i18n?.locales || []) {
......@@ -911,20 +926,19 @@ export async function handleBuildComplete({
pathname: dataPathname,
id: dataPathname,
})
if (appPageKeys && appPageKeys.length > 0) {
outputs.staticFiles.push({
id: `${localePage}.rsc`,
pathname: `${localePage}.rsc`,
type: AdapterOutputType.STATIC_FILE,
filePath: rscFallbackPath,
})
}
}
}
} else {
outputs.pagesApi.push(output)
}
if (appPageKeys && appPageKeys.length > 0) {
outputs.staticFiles.push({
id: `${output.id}.rsc`,
pathname: `${output.pathname}.rsc`,
type: AdapterOutputType.STATIC_FILE,
filePath: rscFallbackPath,
})
}
}
if (hasNodeMiddleware) {
......@@ -1025,6 +1039,11 @@ export async function handleBuildComplete({
outputs.appPages.push(output)
} else {
outputs.appRoutes.push(output)
outputs.appRoutes.push({
...output,
pathname: normalizePagePath(output.pathname) + '.rsc',
id: normalizePagePath(output.pathname) + '.rsc',
})
}
}
}
......@@ -1284,6 +1303,16 @@ export async function handleBuildComplete({
}
outputs.prerenders.push(initialOutput)
if (!isAppPage && appPageKeys && appPageKeys.length > 0) {
const rscPage = `${route === '/' ? '/index' : route}.rsc`
outputs.staticFiles.push({
id: rscPage,
pathname: rscPage,
type: AdapterOutputType.STATIC_FILE,
filePath: rscFallbackPath,
})
}
if (dataRoute) {
let dataFilePath: string | undefined = path.join(
pagesDistDir,
......@@ -1412,6 +1441,21 @@ export async function handleBuildComplete({
if (!config.i18n || isAppPage) {
outputs.prerenders.push(initialOutput)
if (
!isAppPage &&
fallback !== false &&
appPageKeys &&
appPageKeys.length > 0
) {
const rscPage = `${srcRoute === '/' ? '/index' : srcRoute}.rsc`
outputs.staticFiles.push({
id: rscPage,
pathname: rscPage,
type: AdapterOutputType.STATIC_FILE,
filePath: rscFallbackPath,
})
}
if (isAppPage) {
await handleAppMeta(dynamicRoute, initialOutput, meta)
}
......@@ -1468,6 +1512,21 @@ export async function handleBuildComplete({
}
outputs.prerenders.push(currentOutput)
if (
!isAppPage &&
fallback !== false &&
appPageKeys &&
appPageKeys.length > 0
) {
const rscPage = `${path.posix.join(`/${locale}`, initialOutput.pathname)}.rsc`
outputs.staticFiles.push({
id: rscPage,
pathname: rscPage,
type: AdapterOutputType.STATIC_FILE,
filePath: rscFallbackPath,
})
}
if (dataRoute) {
const dataPathname = path.posix.join(
`/_next/data`,
......@@ -1592,10 +1651,13 @@ export async function handleBuildComplete({
// enabled.
shouldSkipSuffixes
? '(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$'
: '(?<rscSuffix>\\.rsc|\\.prefetch\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$'
: '(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc)(?:/)?$'
),
destination: destination?.replace(/($|\?)/, '$rscSuffix$1'),
has: isFallbackFalse ? fallbackFalseHasCondition : undefined,
has:
isFallbackFalse && !pageKeys.includes(route.page)
? fallbackFalseHasCondition
: undefined,
missing: undefined,
})
}
......@@ -1765,7 +1827,7 @@ export async function handleBuildComplete({
{
// This ensures we only match known emitted-by-Next.js files and not
// user-emitted files which may be missing a hash in their filename.
sourceRegex: `^/${escapeStringRegexp(buildId)}/_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|image|media|${escapeStringRegexp(buildId)})/.+`,
sourceRegex: `${path.posix.join(config.basePath || '/', '_next/static', `/(?:[^/]+/pages|pages|chunks|runtime|css|image|media|${escapeStringRegexp(buildId)})/.+`)}`,
// Next.js assets contain a hash or entropy in their filenames, so they
// are guaranteed to be unique and cacheable indefinitely.
headers: {
......@@ -1775,6 +1837,19 @@ export async function handleBuildComplete({
],
fallback: rewrites.fallback,
shouldNormalizeNextData: !!needsMiddlewareResolveRoutes,
rsc: generateRoutesManifest({
appType,
pageKeys: {
pages: pageKeys as string[],
app: appPageKeys as string[],
},
config,
redirects: [],
headers: [],
rewrites,
restrictedRedirectPaths: [],
isAppPPREnabled: config.cacheComponents,
}).routesManifest.rsc,
},
outputs,
......
......@@ -343,6 +343,9 @@ export function getDefineEnv({
config.experimental.reactDebugChannel ?? false,
'process.env.__NEXT_TRANSITION_INDICATOR':
config.experimental.transitionIndicator ?? false,
'process.env.__NEXT_CACHE_LIFE': config.cacheLife,
'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':
config.experimental.clientParamParsingOrigins || [],
}
const userDefines = config.compiler?.define ?? {}
......
......@@ -4138,6 +4138,7 @@ export default async function build(
dir,
distDir,
config,
appType,
buildId,
configOutDir: path.join(dir, configOutDir),
staticPages,
......
......@@ -10,7 +10,12 @@ import { RouteKind } from '../../server/route-kind' with { 'turbopack-transition
import { getRevalidateReason } from '../../server/instrumentation/utils'
import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer'
import { addRequestMeta, getRequestMeta } from '../../server/request-meta'
import type { RequestMeta } from '../../server/request-meta'
import {
addRequestMeta,
getRequestMeta,
setRequestMeta,
} from '../../server/request-meta'
import { BaseServerSpan } from '../../server/lib/trace/constants'
import { interopDefault } from '../../server/app-render/interop-default'
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers'
......@@ -116,9 +121,14 @@ export async function handler(
req: IncomingMessage,
res: ServerResponse,
ctx: {
waitUntil: (prom: Promise<void>) => void
waitUntil?: (prom: Promise<void>) => void
requestMeta?: RequestMeta
}
) {
if (ctx.requestMeta) {
setRequestMeta(req, ctx.requestMeta)
}
if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
}
......
......@@ -6,7 +6,12 @@ import {
import { RouteKind } from '../../server/route-kind'
import { patchFetch as _patchFetch } from '../../server/lib/patch-fetch'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { addRequestMeta, getRequestMeta } from '../../server/request-meta'
import {
addRequestMeta,
getRequestMeta,
setRequestMeta,
type RequestMeta,
} from '../../server/request-meta'
import { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer'
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
......@@ -81,9 +86,13 @@ export async function handler(
req: IncomingMessage,
res: ServerResponse,
ctx: {
waitUntil: (prom: Promise<void>) => void
waitUntil?: (prom: Promise<void>) => void
requestMeta?: RequestMeta
}
) {
if (ctx.requestMeta) {
setRequestMeta(req, ctx.requestMeta)
}
if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
}
......
import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import type { RequestMeta } from '../../server/request-meta'
import type { EdgeHandler } from '../../server/web/adapter'
import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper'
// Import the userland code.
import * as module from 'VAR_USERLAND'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
// injected by the loader afterwards.
......@@ -22,7 +24,56 @@ if (rscManifest && rscServerManifest) {
export const ComponentMod = module
const handler: EdgeHandler = EdgeRouteModuleWrapper.wrap(module.routeModule, {
page: 'VAR_PAGE',
})
export default handler
const internalHandler: EdgeHandler = EdgeRouteModuleWrapper.wrap(
module.routeModule,
{
page: 'VAR_PAGE',
}
)
export async function handler(
request: Request,
ctx: {
waitUntil?: (prom: Promise<void>) => void
signal?: AbortSignal
requestMeta?: RequestMeta
}
): Promise<Response> {
const result = await internalHandler({
request: {
url: request.url,
method: request.method,
headers: toNodeOutgoingHttpHeaders(request.headers),
nextConfig: {
basePath: process.env.__NEXT_BASE_PATH,
i18n: process.env.__NEXT_I18N_CONFIG as any,
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
},
page: {
name: 'VAR_PAGE',
},
body:
request.method !== 'GET' && request.method !== 'HEAD'
? (request.body ?? undefined)
: undefined,
waitUntil: ctx.waitUntil,
requestMeta: ctx.requestMeta,
signal: ctx.signal || new AbortController().signal,
},
})
ctx.waitUntil?.(result.waitUntil)
return result.response
}
// backwards compat
export default internalHandler
......@@ -27,6 +27,8 @@ import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { checkIsOnDemandRevalidate } from '../../server/api-utils'
import { CloseController } from '../../server/web/web-on-close'
import { parseMaxPostponedStateSize } from '../../shared/lib/size-limit'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta'
declare const incrementalCacheHandler: any
// OPTIONAL_IMPORT:incrementalCacheHandler
......@@ -359,7 +361,7 @@ async function requestHandler(
)
}
const handler: EdgeHandler = (opts) => {
const internalHandler: EdgeHandler = (opts) => {
return adapter({
...opts,
IncrementalCache,
......@@ -368,4 +370,50 @@ const handler: EdgeHandler = (opts) => {
page: 'VAR_PAGE',
})
}
export default handler
export async function handler(
request: Request,
ctx: {
waitUntil?: (prom: Promise<void>) => void
signal?: AbortSignal
requestMeta?: RequestMeta
}
): Promise<Response> {
const result = await internalHandler({
request: {
url: request.url,
method: request.method,
headers: toNodeOutgoingHttpHeaders(request.headers),
nextConfig: {
basePath: process.env.__NEXT_BASE_PATH,
i18n: process.env.__NEXT_I18N_CONFIG as any,
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
},
page: {
name: 'VAR_PAGE',
},
body:
request.method !== 'GET' && request.method !== 'HEAD'
? (request.body ?? undefined)
: undefined,
waitUntil: ctx.waitUntil,
requestMeta: ctx.requestMeta,
signal: ctx.signal || new AbortController().signal,
},
})
ctx.waitUntil?.(result.waitUntil)
return result.response
}
// backwards compat
export default internalHandler
......@@ -28,6 +28,8 @@ import type { RenderResultMetadata } from '../../server/render-result'
import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer'
import { BaseServerSpan } from '../../server/lib/trace/constants'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
import type { RequestMeta } from '../../server/request-meta'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
// injected by the loader afterwards.
declare const pageRouteModuleOptions: any
......@@ -357,7 +359,7 @@ async function requestHandler(
)
}
const handler: EdgeHandler = (opts) => {
const internalHandler: EdgeHandler = (opts) => {
return adapter({
...opts,
IncrementalCache,
......@@ -367,4 +369,50 @@ const handler: EdgeHandler = (opts) => {
page: 'VAR_DEFINITION_PATHNAME',
})
}
export default handler
export async function handler(
request: Request,
ctx: {
waitUntil?: (prom: Promise<void>) => void
signal?: AbortSignal
requestMeta?: RequestMeta
}
): Promise<Response> {
const result = await internalHandler({
request: {
url: request.url,
method: request.method,
headers: toNodeOutgoingHttpHeaders(request.headers),
nextConfig: {
basePath: process.env.__NEXT_BASE_PATH,
i18n: process.env.__NEXT_I18N_CONFIG as any,
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
},
page: {
name: 'VAR_DEFINITION_PATHNAME',
},
body:
request.method !== 'GET' && request.method !== 'HEAD'
? (request.body ?? undefined)
: undefined,
waitUntil: ctx.waitUntil,
requestMeta: ctx.requestMeta,
signal: ctx.signal || new AbortController().signal,
},
})
ctx.waitUntil?.(result.waitUntil)
return result.response
}
// backwards compat
export default internalHandler
......@@ -8,6 +8,8 @@ import { adapter } from '../../server/web/adapter'
import * as _mod from 'VAR_USERLAND'
import { edgeInstrumentationOnRequestError } from '../../server/web/globals'
import { isNextRouterError } from '../../client/components/is-next-router-error'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta'
const mod = { ..._mod }
......@@ -69,11 +71,57 @@ function errorHandledHandler(fn: AdapterOptions['handler']) {
}
}
const handler: EdgeHandler = (opts) => {
const internalHandler: EdgeHandler = (opts) => {
return adapter({
...opts,
page,
handler: errorHandledHandler(handlerUserland),
})
}
export default handler
export async function handler(
request: Request,
ctx: {
waitUntil?: (prom: Promise<void>) => void
signal?: AbortSignal
requestMeta?: RequestMeta
}
): Promise<Response> {
const result = await internalHandler({
request: {
url: request.url,
method: request.method,
headers: toNodeOutgoingHttpHeaders(request.headers),
nextConfig: {
basePath: process.env.__NEXT_BASE_PATH,
i18n: process.env.__NEXT_I18N_CONFIG as any,
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
},
page: {
name: page,
},
body:
request.method !== 'GET' && request.method !== 'HEAD'
? (request.body ?? undefined)
: undefined,
waitUntil: ctx.waitUntil,
requestMeta: ctx.requestMeta,
signal: ctx.signal || new AbortController().signal,
},
})
ctx.waitUntil?.(result.waitUntil)
return result.response
}
// backwards compat
export default internalHandler
......@@ -13,7 +13,11 @@ import * as userland from 'VAR_USERLAND'
import { getTracer, SpanKind } from '../../server/lib/trace/tracer'
import { BaseServerSpan } from '../../server/lib/trace/constants'
import type { InstrumentationOnRequestError } from '../../server/instrumentation/types'
import { addRequestMeta } from '../../server/request-meta'
import {
addRequestMeta,
setRequestMeta,
type RequestMeta,
} from '../../server/request-meta'
// Re-export the handler (should be the default export).
export default hoist(userland, 'default')
......@@ -41,8 +45,12 @@ export async function handler(
res: ServerResponse,
ctx: {
waitUntil?: (prom: Promise<void>) => void
requestMeta?: RequestMeta
}
) {
if (ctx.requestMeta) {
setRequestMeta(req, ctx.requestMeta)
}
): Promise<void> {
if (routeModule.isDev) {
addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())
}
......
......@@ -8,6 +8,8 @@ import { wrapApiHandler } from '../../server/api-utils'
// Import the userland code.
import handlerUserland from 'VAR_USERLAND'
import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta'
const page = 'VAR_DEFINITION_PAGE'
......@@ -17,7 +19,7 @@ if (typeof handlerUserland !== 'function') {
)
}
const handler: EdgeHandler = (opts) => {
const internalHandler: EdgeHandler = (opts) => {
return adapter({
...opts,
IncrementalCache,
......@@ -25,4 +27,50 @@ const handler: EdgeHandler = (opts) => {
handler: wrapApiHandler(page, handlerUserland),
})
}
export default handler
export async function handler(
request: Request,
ctx: {
waitUntil?: (prom: Promise<void>) => void
signal?: AbortSignal
requestMeta?: RequestMeta
}
): Promise<Response> {
const result = await internalHandler({
request: {
url: request.url,
method: request.method,
headers: toNodeOutgoingHttpHeaders(request.headers),
nextConfig: {
basePath: process.env.__NEXT_BASE_PATH,
i18n: process.env.__NEXT_I18N_CONFIG as any,
trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),
experimental: {
cacheLife: process.env.__NEXT_CACHE_LIFE as any,
authInterrupts: Boolean(
process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
),
clientParamParsingOrigins: process.env
.__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,
},
},
page: {
name: 'VAR_DEFINITION_PATHNAME',
},
body:
request.method !== 'GET' && request.method !== 'HEAD'
? (request.body ?? undefined)
: undefined,
waitUntil: ctx.waitUntil,
requestMeta: ctx.requestMeta,
signal: ctx.signal || new AbortController().signal,
},
})
ctx.waitUntil?.(result.waitUntil)
return result.response
}
// backwards compat
export default internalHandler
......@@ -11,11 +11,16 @@ import type {
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
import type { OpaqueFallbackRouteParams } from './request/fallback-params'
import type { IncrementalCache } from './lib/incremental-cache'
import type { NextRequest } from './web/exports'
// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules
export const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')
export type NextIncomingMessage = (BaseNextRequest | IncomingMessage) & {
export type NextIncomingMessage = (
| BaseNextRequest
| IncomingMessage
| NextRequest
) & {
[NEXT_REQUEST_META]?: RequestMeta
}
......
import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'
import type RenderResult from '../../render-result'
import type { RenderOpts } from '../../app-render/types'
import type { NextParsedUrlQuery } from '../../request-meta'
import { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'
import type { LoaderTree } from '../../lib/app-dir-module'
import type { PrerenderManifest } from '../../../build'
......@@ -28,6 +28,10 @@ import {
RSC_HEADER,
} from '../../../client/components/app-router-headers'
import { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/interception-routes'
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage } from 'http'
let vendoredReactRSC
let vendoredReactSSR
......@@ -100,6 +104,46 @@ export class AppPageRouteModule extends RouteModule<
return matcher.match(pathname)
}
private normalizers = {
rsc: new RSCPathnameNormalizer(),
segmentPrefetchRSC: new SegmentPrefixRSCPathnameNormalizer(),
}
public normalizeUrl(
req: IncomingMessage | BaseNextRequest,
parsedUrl: UrlWithParsedQuery
) {
if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) {
const result = this.normalizers.segmentPrefetchRSC.extract(
parsedUrl.pathname || '/'
)
if (!result) return false
const { originalPathname, segmentPath } = result
parsedUrl.pathname = originalPathname
// Mark the request as a router prefetch request.
req.headers[RSC_HEADER] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath
addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true)
addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)
} else if (this.normalizers.rsc.match(parsedUrl.pathname || '/')) {
parsedUrl.pathname = this.normalizers.rsc.normalize(
parsedUrl.pathname || '/',
true
)
// Mark the request as a RSC request.
req.headers[RSC_HEADER] = '1'
addRequestMeta(req, 'isRSCRequest', true)
} else {
super.normalizeUrl(req, parsedUrl)
}
}
public render(
req: BaseNextRequest,
res: BaseNextResponse,
......
......@@ -4,7 +4,12 @@ import { RouteKind } from '../../route-kind'
import { BaseServerSpan } from '../../lib/trace/constants'
import { getTracer, SpanKind, type Span } from '../../lib/trace/tracer'
import { formatUrl } from '../../../shared/lib/router/utils/format-url'
import { addRequestMeta, getRequestMeta } from '../../request-meta'
import {
addRequestMeta,
getRequestMeta,
setRequestMeta,
type RequestMeta,
} from '../../request-meta'
import { interopDefault } from '../../app-render/interop-default'
import { getRevalidateReason } from '../../instrumentation/utils'
import { normalizeDataPath } from '../../../shared/lib/page-path/normalize-data-path'
......@@ -67,9 +72,13 @@ export const getHandler = ({
req: IncomingMessage,
res: ServerResponse,
ctx: {
waitUntil: (prom: Promise<void>) => void
waitUntil?: (prom: Promise<void>) => void
requestMeta?: RequestMeta
}
) {
if (ctx.requestMeta) {
setRequestMeta(req, ctx.requestMeta)
}
): Promise<void> {
if (routeModule.isDev) {
addRequestMeta(
req,
......
......@@ -141,6 +141,11 @@ export abstract class RouteModule<
this.relativeProjectDir = relativeProjectDir
}
public normalizeUrl(
_req: IncomingMessage | BaseNextRequest,
_parsedUrl: UrlWithParsedQuery
) {}
public async instrumentationOnRequestError(
req: IncomingMessage | BaseNextRequest,
...args: Parameters<InstrumentationOnRequestError>
......@@ -641,6 +646,7 @@ export abstract class RouteModule<
isNextDataRequest = true
parsedUrl.pathname = normalizeDataPath(parsedUrl.pathname || '/')
}
this.normalizeUrl(req, parsedUrl)
let originalPathname = parsedUrl.pathname || '/'
const originalQuery = { ...parsedUrl.query }
const pageIsDynamic = isDynamicRoute(srcPage)
......@@ -684,9 +690,15 @@ export abstract class RouteModule<
getHostname(parsedUrl, req.headers),
detectedLocale
)
addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))
const defaultLocale = domainLocale?.defaultLocale || i18n?.defaultLocale
if (Boolean(domainLocale)) {
addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))
}
const defaultLocale =
getRequestMeta(req, 'defaultLocale') ||
domainLocale?.defaultLocale ||
i18n?.defaultLocale
// Ensure parsedUrl.pathname includes locale before processing
// rewrites or they won't match correctly.
......
......@@ -35,6 +35,7 @@ import { CloseController } from './web-on-close'
import { getEdgePreviewProps } from './get-edge-preview-props'
import { getBuiltinRequestContext } from '../after/builtin-request-context'
import { getImplicitTags } from '../lib/implicit-tags'
import { setRequestMeta } from '../request-meta'
export class NextRequestHint extends NextRequest {
sourcePage: string
......@@ -187,6 +188,10 @@ export async function adapter(
},
})
if (params.request.requestMeta) {
setRequestMeta(request, params.request.requestMeta)
}
/**
* This allows to identify the request as a data request. The user doesn't
* need to know about this property neither use it. We add it for testing
......
......@@ -5,6 +5,7 @@ import type { NextResponse } from './spec-extension/response'
import type { CloneableBody } from '../body-streams'
import type { OutgoingHttpHeaders } from 'http'
import type { FetchMetrics } from '../base-http'
import type { RequestMeta } from '../request-meta'
/**
* @deprecated Use `ProxyConfig` instead. Middleware has been renamed to Proxy.
......@@ -32,6 +33,7 @@ export interface RequestData {
url: string
body?: ReadableStream<Uint8Array>
signal: AbortSignal
requestMeta?: RequestMeta
/** passed in when running in edge runtime sandbox */
waitUntil?: (promise: Promise<any>) => void
}
......
......@@ -88,6 +88,7 @@ describe('adapter-config export', () => {
onMatch: expect.toBeArray(),
fallback: expect.toBeArray(),
shouldNormalizeNextData: expect.toBeBoolean(),
rsc: expect.toBeObject(),
})
})
})
......@@ -217,6 +217,7 @@ describe('adapter-config', () => {
onMatch: expect.toBeArray(),
fallback: expect.toBeArray(),
shouldNormalizeNextData: expect.toBeBoolean(),
rsc: expect.toBeObject(),
})
})
})
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