调用入口点
使用适配器运行时上下文调用 Node.js 和 Edge 构建入口点。
构建输出入口点使用 handler(..., ctx) 接口,并带有特定于运行时的请求/响应类型。
Node.js 运行时(runtime: 'nodejs')
Node.js 入口点使用以下接口:
handler(
req: IncomingMessage,
res: ServerResponse,
ctx: {
waitUntil?: (promise: Promise<void>) => void
requestMeta?: RequestMeta
}
): Promise<void>
直接调用 Node.js 入口点时,适配器可以直接在 requestMeta 上传递辅助函数,而无须依赖内部实现。部分受支持的字段包括 hostname、
revalidate 和 render404:
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
},
},
})
Next.js 核心中的相关文件:
packages/next/src/build/templates/app-page.tspackages/next/src/build/templates/app-route.ts- 以及
packages/next/src/build/templates/pages-api.ts
Edge 运行时(runtime: 'edge')(已弃用)
Edge 运行时已弃用。新路由应使用 Node.js 运行时。
Edge 入口点使用以下接口:
handler(
request: Request,
ctx: {
waitUntil?: (prom: Promise<void>) => void
signal?: AbortSignal
requestMeta?: RequestMeta
}
): Promise<Response>
该结构围绕 handler(..., ctx) 对齐,但 Node.js 和 Edge 运行时使用不同的请求/响应原语。
对于带有 runtime: 'edge' 的输出,Next.js 还提供 output.edgeRuntime,其中包含调用入口点所需的规范元数据:
{
modulePath: string // Absolute path to the module registered in the edge runtime
entryKey: string // Canonical key used by the edge entry registry
handlerExport: string // Export name to invoke, currently 'handler'
}
在你的 Edge 运行时加载并求值 modulePath 的 chunk 之后,使用 entryKey 从全局 edge 入口注册表(globalThis._ENTRIES)中读取已注册的入口,然后从该入口调用 handlerExport:
const entry = await globalThis._ENTRIES[output.edgeRuntime.entryKey]
const handler = entry[output.edgeRuntime.handlerExport]
await handler(request, ctx)
请使用 edgeRuntime,而不要从文件名推导注册表键或处理器名称。
Next.js 核心中的相关文件: