Unverified Commit 90861b0f authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

feat(server): expose requestMeta router helpers and merge fallback context (#91235)

### What?

This PR exposes adapter-facing router helpers on `requestMeta` for
Node.js entrypoints and updates route modules to merge those
request-scoped values with the existing router server context fallback.
It also documents the new adapter contract in the `adapterPath` docs.

### Why?

When adapters invoke the Node.js handler directly, some router helpers
are needed by route handlers but currently only exist behind internal
globals. Passing them through `requestMeta` makes those helpers
available through the public handler options and still preserves the
existing fallback context for the current `relativeProjectDir`.

### How?

- add typed `requestMeta` fields for `hostname`, `revalidate`, and
`render404`
- add a `RouteModule` helper that reads the existing router server
context and overlays request-scoped values from `requestMeta`
- switch the route-module callsites that read router server context to
use the merged result
- document how adapters can pass these helpers when calling
`handler(req, res, { requestMeta })`
parent bd04a076
...@@ -576,6 +576,28 @@ handler( ...@@ -576,6 +576,28 @@ handler(
): Promise<void> ): Promise<void>
``` ```
When invoking Node.js entrypoints directly, adapters can pass helpers directly on `requestMeta` instead of relying on internals. Some of the supported fields are `hostname`,
`revalidate`, and `render404`:
```ts
await handler(req, res, {
requestMeta: {
// Relative path from process.cwd() to the Next.js project directory.
relativeProjectDir: '.',
// Optional hostname used by route handlers when constructing absolute URLs.
hostname: '127.0.0.1',
// Optional internal revalidate function to avoid revalidating over the network
revalidate: async ({ urlPath, headers, opts }) => {
// platform-specific revalidate implementation
},
// Optional function to render the 404 page for pages router `notFound: true`
render404: async (req, res, parsedUrl, setHeaders) => {
// platform-specific 404 rendering implementation
},
},
})
```
Relevant files in the Next.js core: Relevant files in the Next.js core:
- [`packages/next/src/build/templates/app-page.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/app-page.ts) - [`packages/next/src/build/templates/app-page.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/app-page.ts)
......
...@@ -258,7 +258,7 @@ async function revalidate( ...@@ -258,7 +258,7 @@ async function revalidate(
`Invalid urlPath provided to revalidate(), must be a path e.g. /blog/post-1, received ${urlPath}` `Invalid urlPath provided to revalidate(), must be a path e.g. /blog/post-1, received ${urlPath}`
) )
} }
const revalidateHeaders: HeadersInit = { const headers: HeadersInit = {
[PRERENDER_REVALIDATE_HEADER]: context.previewModeId, [PRERENDER_REVALIDATE_HEADER]: context.previewModeId,
...(opts.unstable_onlyGenerated ...(opts.unstable_onlyGenerated
? { ? {
...@@ -280,7 +280,7 @@ async function revalidate( ...@@ -280,7 +280,7 @@ async function revalidate(
for (const key of Object.keys(req.headers)) { for (const key of Object.keys(req.headers)) {
if (allowedRevalidateHeaderKeys.includes(key)) { if (allowedRevalidateHeaderKeys.includes(key)) {
revalidateHeaders[key] = req.headers[key] as string headers[key] = req.headers[key] as string
} }
} }
...@@ -293,7 +293,7 @@ async function revalidate( ...@@ -293,7 +293,7 @@ async function revalidate(
if (internalRevalidate) { if (internalRevalidate) {
return await internalRevalidate({ return await internalRevalidate({
urlPath, urlPath,
revalidateHeaders, headers,
opts, opts,
}) })
} }
...@@ -301,7 +301,7 @@ async function revalidate( ...@@ -301,7 +301,7 @@ async function revalidate(
if (context.trustHostHeader) { if (context.trustHostHeader) {
const res = await fetch(`https://${req.headers.host}${urlPath}`, { const res = await fetch(`https://${req.headers.host}${urlPath}`, {
method: 'HEAD', method: 'HEAD',
headers: revalidateHeaders, headers,
}) })
// we use the cache header to determine successful revalidate as // we use the cache header to determine successful revalidate as
// a non-200 status code can be returned from a successful revalidate // a non-200 status code can be returned from a successful revalidate
......
...@@ -74,16 +74,16 @@ export class DevBundlerService { ...@@ -74,16 +74,16 @@ export class DevBundlerService {
public async revalidate({ public async revalidate({
urlPath, urlPath,
revalidateHeaders, headers,
opts: revalidateOpts, opts: revalidateOpts,
}: { }: {
urlPath: string urlPath: string
revalidateHeaders: IncomingMessage['headers'] headers: IncomingMessage['headers']
opts: any opts: any
}) { }) {
const mocked = createRequestResponseMocks({ const mocked = createRequestResponseMocks({
url: urlPath, url: urlPath,
headers: revalidateHeaders, headers,
}) })
await this.handler(mocked.req, mocked.res) await this.handler(mocked.req, mocked.res)
......
...@@ -5,7 +5,7 @@ import type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache ...@@ -5,7 +5,7 @@ import type { ServerCacheStatus } from '../../../next-devtools/dev-overlay/cache
export type RevalidateFn = (config: { export type RevalidateFn = (config: {
urlPath: string urlPath: string
revalidateHeaders: { [key: string]: string | string[] } headers: { [key: string]: string | string[] }
opts: { unstable_onlyGenerated?: boolean } opts: { unstable_onlyGenerated?: boolean }
}) => Promise<void> }) => Promise<void>
......
...@@ -1284,16 +1284,16 @@ export default class NextNodeServer extends BaseServer< ...@@ -1284,16 +1284,16 @@ export default class NextNodeServer extends BaseServer<
public async revalidate({ public async revalidate({
urlPath, urlPath,
revalidateHeaders, headers,
opts, opts,
}: { }: {
urlPath: string urlPath: string
revalidateHeaders: { [key: string]: string | string[] } headers: { [key: string]: string | string[] }
opts: { unstable_onlyGenerated?: boolean } opts: { unstable_onlyGenerated?: boolean }
}) { }) {
const mocked = createRequestResponseMocks({ const mocked = createRequestResponseMocks({
url: urlPath, url: urlPath,
headers: revalidateHeaders, headers,
}) })
const handler = this.getRequestHandler() const handler = this.getRequestHandler()
......
import type { IncomingMessage } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url'
import type { BaseNextRequest } from './base-http' import type { BaseNextRequest } from './base-http'
import type { CloneableBody } from './body-streams' import type { CloneableBody } from './body-streams'
import type { RouteMatch } from './route-matches/route-match' import type { RouteMatch } from './route-matches/route-match'
...@@ -11,6 +12,7 @@ import type { ...@@ -11,6 +12,7 @@ import type {
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup' import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
import type { OpaqueFallbackRouteParams } from './request/fallback-params' import type { OpaqueFallbackRouteParams } from './request/fallback-params'
import type { IncrementalCache } from './lib/incremental-cache' import type { IncrementalCache } from './lib/incremental-cache'
import type { RevalidateFn } from './lib/router-utils/router-server-context'
import type { NextRequest } from './web/exports' import type { NextRequest } from './web/exports'
// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules // FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules
...@@ -255,6 +257,27 @@ export interface RequestMeta { ...@@ -255,6 +257,27 @@ export interface RequestMeta {
*/ */
distDir?: string distDir?: string
/**
Optional hostname used by route handlers when constructing absolute URLs.
hostname: '127.0.0.1',
*/
hostname?: string
/**
Optional internal revalidate function to avoid revalidating over the network
*/
revalidate?: RevalidateFn
/**
Optional function to render the 404 page for pages router `notFound: true`
*/
render404?: (
req: IncomingMessage,
res: ServerResponse,
parsedUrl?: UrlWithParsedQuery,
setHeaders?: boolean
) => Promise<void>
/** /**
* The query after resolving routes * The query after resolving routes
*/ */
......
...@@ -142,6 +142,25 @@ export abstract class RouteModule< ...@@ -142,6 +142,25 @@ export abstract class RouteModule<
this.relativeProjectDir = relativeProjectDir this.relativeProjectDir = relativeProjectDir
} }
private getRouterServerContext(
req: NextIncomingMessage
): RouterServerContext[string] | undefined {
const hostname = getRequestMeta(req, 'hostname')
const revalidate = getRequestMeta(req, 'revalidate')
const render404 = getRequestMeta(req, 'render404')
const relativeProjectDir =
getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir
const routerServerContext =
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
return {
...routerServerContext,
...(hostname !== undefined ? { hostname } : {}),
...(revalidate !== undefined ? { revalidate } : {}),
...(render404 !== undefined ? { render404 } : {}),
}
}
public normalizeUrl( public normalizeUrl(
_req: IncomingMessage | BaseNextRequest, _req: IncomingMessage | BaseNextRequest,
_parsedUrl: UrlWithParsedQuery _parsedUrl: UrlWithParsedQuery
...@@ -529,10 +548,7 @@ export abstract class RouteModule< ...@@ -529,10 +548,7 @@ export abstract class RouteModule<
let serverFilesManifest = self.__SERVER_FILES_MANIFEST as any as let serverFilesManifest = self.__SERVER_FILES_MANIFEST as any as
| RequiredServerFilesManifest | RequiredServerFilesManifest
| undefined | undefined
const relativeProjectDir = const routerServerContext = this.getRouterServerContext(req)
getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir
const routerServerContext =
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
const nextConfig = const nextConfig =
routerServerContext?.nextConfig || serverFilesManifest?.config routerServerContext?.nextConfig || serverFilesManifest?.config
...@@ -636,11 +652,8 @@ export abstract class RouteModule< ...@@ -636,11 +652,8 @@ export abstract class RouteModule<
const { routesManifest, prerenderManifest, serverFilesManifest } = manifests const { routesManifest, prerenderManifest, serverFilesManifest } = manifests
const { basePath, i18n, rewrites } = routesManifest const { basePath, i18n, rewrites } = routesManifest
const relativeProjectDir =
getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir
const routerServerContext = const routerServerContext = this.getRouterServerContext(req)
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
const nextConfig = const nextConfig =
routerServerContext?.nextConfig || serverFilesManifest?.config routerServerContext?.nextConfig || serverFilesManifest?.config
......
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