Astro 适配器 API
Astro 旨在轻松部署到任何云提供商以进行按需渲染,也称为服务器端渲染 (SSR)。这种能力是由 integrations 适配器提供的。请参阅 按需渲染指南 了解如何使用现有适配器。
¥Astro is designed to make it easy to deploy to any cloud provider for on-demand rendering, also known as server-side rendering (SSR). This ability is provided by adapters, which are integrations. See the on-demand rendering guide to learn how to use an existing adapter.
什么是适配器?
Section titled “什么是适配器?”¥What is an adapter?
适配器是一种特殊的 integration,它在请求时提供服务器渲染的入口点。适配器可以访问完整的集成 API,并执行以下两项操作:
¥An adapter is a special kind of integration that provides an entrypoint for server rendering at request time. An adapter has access to the full Integration API and does two things:
-
实现特定于主机的 API 来处理请求。
-
根据主机约定配置构建。
¥Building an adapter
创建一个集成,并在 astro:config:done 钩子中调用 setAdapter() 函数。这允许你定义服务器入口点以及适配器支持的功能。
¥Create an integration and call the setAdapter() function in the astro:config:done hook. This allows you to define a server entrypoint and the features supported by your adapter.
以下示例创建一个适配器,该适配器具有服务器入口点和对 Astro 静态输出的稳定支持:
¥The following example creates an adapter with a server entrypoint and stable support for Astro static output:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', supportedAstroFeatures: { staticOutput: 'stable' } }); }, }, };}setAdapter() 函数接受一个包含以下属性的对象:
¥The setAdapter() function accepts an object containing the following properties:
类型:string
¥Type: string
定义适配器的唯一名称。这将用于日志记录。
¥Defines a unique name for your adapter. This will be used for logging.
serverEntrypoint
Section titled “serverEntrypoint”类型:string | URL
¥Type: string | URL
定义按需渲染的入口点。
¥Defines the entrypoint for on-demand rendering.
supportedAstroFeatures
Section titled “supportedAstroFeatures”类型:AstroAdapterFeatureMap
¥Type: AstroAdapterFeatureMap
astro@3.0.0
Astro 内置功能(适配器支持)的映射。这使 Astro 能够确定适配器支持哪些功能,从而提供相应的错误消息。
¥A map of Astro’s built-in features supported by the adapter. This allows Astro to determine which features an adapter supports, so appropriate error messages can be provided.
adapterFeatures
Section titled “adapterFeatures”类型:AstroAdapterFeatures
¥Type: AstroAdapterFeatures
astro@3.0.0
一个指定适配器支持的 改变构建输出的适配器功能 类型的对象。
¥An object that specifies which adapter features that change the build output are supported by the adapter.
类型:any
¥Type: any
一个可序列化的 JSON 值,将在运行时传递给适配器的服务器入口点。这对于将包含构建时配置(例如路径、密钥)的对象传递给服务器运行时代码非常有用。
¥A JSON-serializable value that will be passed to the adapter’s server entrypoint at runtime. This is useful to pass an object containing build-time configuration (e.g. paths, secrets) to your server runtime code.
以下示例定义了一个 args 对象,其中包含一个用于标识 Astro 生成的资源所在位置的属性:
¥The following example defines an args object with a property that identifies where assets generated by Astro are located:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ config, setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', args: { assets: config.build.assets } }); }, }, };}client
Section titled “client”类型:{ internalFetchHeaders?: Record<string, string> | () => Record<string, string>; assetQueryParams?: URLSearchParams; }
¥Type: { internalFetchHeaders?: Record<string, string> | () => Record<string, string>; assetQueryParams?: URLSearchParams; }
astro@5.15.0
Astro 客户端代码的配置对象。
¥A configuration object for Astro’s client-side code.
internalFetchHeaders
Section titled “internalFetchHeaders”类型:Record<string, string> | () => Record<string, string>
¥Type: Record<string, string> | () => Record<string, string>
定义要注入到 Astro 内部获取调用(例如 Actions、View Transitions、Server Islands、Prefetch)中的标头。这可以是包含标头的对象,也可以是返回标头的函数。
¥Defines the headers to inject into Astro’s internal fetch calls (e.g. Actions, View Transitions, Server Islands, Prefetch). This can be an object of headers or a function that returns headers.
以下示例从环境变量中检索 DEPLOY_ID,如果提供了该变量,则返回一个以标头名称为键、部署 ID 为值的对象:
¥The following example retrieves a DEPLOY_ID from the environment variables and, if provided, returns an object with the header name as key and the deploy id as value:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ config, setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', client: { internalFetchHeaders: () => { const deployId = process.env.DEPLOY_ID; return deployId ? { 'Your-Header-ID': deployId } : {}; }, }, }); }, }, };}assetQueryParams
Section titled “assetQueryParams”类型:URLSearchParams
¥Type: URLSearchParams
定义要附加到所有资源 URL(例如图片、样式表、脚本)的查询参数。这对于需要跟踪部署版本或其他元数据的适配器非常有用。
¥Defines the query parameters to append to all asset URLs (e.g. images, stylesheets, scripts). This is useful for adapters that need to track deployment versions or other metadata.
以下示例从环境变量中检索 DEPLOY_ID,如果提供了该变量,则返回一个以自定义搜索参数名称为键、部署 ID 为值的对象:
¥The following example retrieves a DEPLOY_ID from the environment variables and, if provided, returns an object with a custom search parameter name as key and the deploy id as value:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ config, setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', client: { assetQueryParams: process.env.DEPLOY_ID ? new URLSearchParams({ yourParam: process.env.DEPLOY_ID }) : undefined, }, }); }, }, };}exports
Section titled “exports”类型:string[]
¥Type: string[]
定义一个命名导出数组,用于与服务器入口点的 createExports() 功能 一起使用。
¥Defines an array of named exports to use in conjunction with the createExports() function of your server entrypoint.
以下示例假设 createExports() 提供名为 handler 的导出:
¥The following example assumes that createExports() provides an export named handler:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ config, setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', exports: ['handler'] }); }, }, };}previewEntrypoint
Section titled “previewEntrypoint”类型:string | URL
¥Type: string | URL
astro@1.5.0
定义适配器包中负责在运行 astro preview 时启动已构建服务器的模块的路径或 ID。
¥Defines the path or ID of a module in the adapter’s package that is responsible for starting up the built server when astro preview is run.
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ config, setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', previewEntrypoint: '@example/my-adapter/preview.js', }); }, }, };}构建服务器入口点
Section titled “构建服务器入口点”¥Building a server entrypoint
你需要创建一个在服务器端请求期间执行的文件,以便在你的特定主机上启用按需渲染。Astro 的适配器 API 尝试与任何类型的主机配合使用,并提供了一种灵活的方式来符合主机 API。
¥You will need to create a file that executes during server-side requests to enable on-demand rendering with your particular host. Astro’s adapter API attempts to work with any type of host and gives a flexible way to conform to the host APIs.
createExports()
Section titled “createExports()”类型:(manifest: SSRManifest, options: any) => Record<string, any>
¥Type: (manifest: SSRManifest, options: any) => Record<string, any>
一个导出的函数,其第一个参数为 SSR 清单,第二个参数为包含适配器 args 的对象。此方法应提供主机所需的导出。
¥An exported function that takes an SSR manifest as its first argument and an object containing your adapter args as its second argument. This should provide the exports required by your host.
例如,某些无服务器主机要求你导出 handler() 函数。使用适配器 API,你可以通过在服务器入口点中实现 createExports() 来实现此功能:
¥For example, some serverless hosts expect you to export an handler() function. With the adapter API, you achieve this by implementing createExports() in your server entrypoint:
import { App } from 'astro/app';
export function createExports(manifest) { const app = new App(manifest);
const handler = (event, context) => { // ... };
return { handler };}然后在你调用 setAdapter() 的集成中,在 exports 中提供此名称:
¥And then in your integration, where you call setAdapter(), provide this name in exports:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', exports: ['handler'], }); }, }, };}你可以通过 createExports() 的第二个参数访问适配器定义的 args。当你需要在服务器入口点访问构建时配置时,这将非常有用。例如,你的服务器可能需要确定 Astro 生成的资源的位置:
¥You can access the args defined by your adapter through the second argument of createExports(). This can be useful when you need to access build-time configuration in your server entrypoint. For example, your server might need to identify where assets generated by Astro are located:
import { App } from 'astro/app';
export function createExports(manifest, args) { const assetsPath = args.assets;
const handler = (event, context) => { // ... };
return { handler };}start()
Section titled “start()”类型:(manifest: SSRManifest, options: any) => Record<string, any>
¥Type: (manifest: SSRManifest, options: any) => Record<string, any>
一个导出的函数,其第一个参数为 SSR 清单,第二个参数为包含适配器 args 的对象。
¥An exported function that takes an SSR manifest as its first argument and an object containing your adapter args as its second argument.
某些主机要求你自行启动服务器,例如,通过监听端口。对于此类主机,适配器 API 允许你导出 start() 函数,该函数将在运行打包脚本时调用。
¥Some hosts expect you to start the server yourselves, for example, by listening to a port. For these types of hosts, the adapter API allows you to export a start() function, which will be called when the bundle script is run.
import { App } from 'astro/app';
export function start(manifest) { const app = new App(manifest);
addEventListener('fetch', event => { // ... });}astro/app
Section titled “astro/app”该模块用于渲染通过 astro build.0 预构建的页面。Astro 使用标准 Request 和 Response 对象。具有不同请求/响应 API 的主机应在其适配器中转换为这些类型。
¥This module is used for rendering pages that have been prebuilt through astro build. Astro uses the standard Request and Response objects. Hosts that have a different API for request/response should convert to these types in their adapter.
App 构造函数接受一个必需的 SSR 清单参数,以及一个可选的用于启用或禁用流式传输的参数,默认为 true。
¥The App constructor accepts a required SSR manifest argument, and optionally an argument to enable or disable streaming, defaulting to true.
import { App } from 'astro/app';import http from 'http';
export function start(manifest) { const app = new App(manifest);
addEventListener('fetch', event => { event.respondWith( app.render(event.request) ); });}提供以下方法:
¥The following methods are provided:
app.render()
Section titled “app.render()”类型:(request: Request, options?: RenderOptions) => Promise<Response>
¥Type: (request: Request, options?: RenderOptions) => Promise<Response>
一个接受必需的 request 参数和可选的 RenderOptions 对象的方法。这会调用与请求匹配的 Astro 页面,渲染该页面,并返回一个 Response 对象的 Promise。这也适用于不渲染页面的 API 路由。
¥A method that accepts a required request argument and an optional RenderOptions object. This calls the Astro page that matches the request, renders it, and returns a promise to a Response object. This also works for API routes that do not render pages.
const response = await app.render(request);RenderOptions
Section titled “RenderOptions”类型:{addCookieHeader?: boolean; clientAddress?: string; locals?: object; prerenderedErrorPageFetch?: (url: ErrorPagePath) => Promise<Response>; routeData?: RouteData;}
¥Type: {addCookieHeader?: boolean; clientAddress?: string; locals?: object; prerenderedErrorPageFetch?: (url: ErrorPagePath) => Promise<Response>; routeData?: RouteData;}
一个控制渲染的对象,包含以下属性:
¥An object that controls the rendering and contains the following properties:
addCookieHeader
Section titled “addCookieHeader”类型:boolean
默认:false
¥Type: boolean
Default: false
是否自动将 Astro.cookie.set() 编写的所有 cookie 添加到响应标头。
¥Whether or not to automatically add all cookies written by Astro.cookie.set() to the response headers.
设置为 true 时,它们将以逗号分隔的键值对的形式添加到响应的 Set-Cookie 标头中。你可以使用标准 response.headers.getSetCookie() API 单独读取它们。设置为 false(默认)时,cookie 只能从 App.getSetCookieFromResponse(response) 获得。
¥When set to true, they will be added to the Set-Cookie header of the response as comma-separated key-value pairs. You can use the standard response.headers.getSetCookie() API to read them individually.
When set to false(default), the cookies will only be available from App.getSetCookieFromResponse(response).
const response = await app.render(request, { addCookieHeader: true });clientAddress
Section titled “clientAddress”类型:string
默认:request[Symbol.for("astro.clientAddress")]
¥Type: string
Default: request[Symbol.for("astro.clientAddress")]
客户端 IP 地址将在页面中作为 Astro.clientAddress 提供,在 API 路由和中间件中作为 ctx.clientAddress 提供。
¥The client IP address that will be made available as Astro.clientAddress in pages, and as ctx.clientAddress in API routes and middleware.
以下示例读取 x-forwarded-for 标头并将其作为 clientAddress 传递。此值作为 Astro.clientAddress 提供给用户。
¥The example below reads the x-forwarded-for header and passes it as clientAddress. This value becomes available to the user as Astro.clientAddress.
const clientAddress = request.headers.get("x-forwarded-for");const response = await app.render(request, { clientAddress });locals
Section titled “locals”类型:object
¥Type: object
context.locals object 用于在请求的生命周期内存储和访问信息。
¥The context.locals object used to store and access information during the lifecycle of a request.
下面的示例读取名为 x-private-header 的标头,尝试将其解析为对象并将其传递给 locals,然后可以将其传递给任何 中间件函数。
¥The example below reads a header named x-private-header, attempts to parse it as an object and pass it to locals, which can then be passed to any middleware function.
const privateHeader = request.headers.get("x-private-header");let locals = {};try { if (privateHeader) { locals = JSON.parse(privateHeader); }} finally { const response = await app.render(request, { locals });}prerenderedErrorPageFetch()
Section titled “prerenderedErrorPageFetch()”类型:(url: ErrorPagePath) => Promise<Response>
默认:fetch
¥Type: (url: ErrorPagePath) => Promise<Response>
Default: fetch
astro@5.6.0
一项功能,允许你提供用于获取预渲染错误页面的自定义实现。
¥A function that allows you to provide custom implementations for fetching prerendered error pages.
这用于覆盖默认的 fetch() 行为,例如,当 fetch() 不可用或无法从服务器本身调用时。
¥This is used to override the default fetch() behavior, for example, when fetch() is unavailable or when you cannot call the server from itself.
以下示例从磁盘读取 500.html 和 404.html,而不是执行 HTTP 调用:
¥The following example reads 500.html and 404.html from disk instead of performing an HTTP call:
return app.render(request, { prerenderedErrorPageFetch: async (url: string): Promise<Response> => { if (url.includes("/500")) { const content = await fs.promises.readFile("500.html", "utf-8"); return new Response(content, { status: 500, headers: { "Content-Type": "text/html" }, }); }
const content = await fs.promises.readFile("404.html", "utf-8"); return new Response(content, { status: 404, headers: { "Content-Type": "text/html" }, }); }});如果未提供,Astro 将回退到其默认行为来获取错误页面。
¥If not provided, Astro will fallback to its default behavior for fetching error pages.
routeData
Section titled “routeData”类型:RouteData
默认:app.match(request)
¥Type: RouteData
Default: app.match(request)
如果你已经知道要渲染的路由,请为 integrationRouteData 提供一个值。这样做将绕过对 app.match() 的内部调用来确定渲染路由。
¥Provides a value for integrationRouteData if you already know the route to render. Doing so will bypass the internal call to app.match() to determine the route to render.
const routeData = app.match(request);if (routeData) { return app.render(request, { routeData });} else { /* adapter-specific 404 response */ return new Response(..., { status: 404 });}app.match()
Section titled “app.match()”类型:(request: Request, allowPrerenderedRoutes = false) => RouteData | undefined
¥Type: (request: Request, allowPrerenderedRoutes = false) => RouteData | undefined
确定请求是否与 Astro 应用的路由规则匹配。
¥Determines if a request is matched by the Astro app’s routing rules.
if(app.match(request)) { const response = await app.render(request);}你通常可以在不使用 .match 的情况下调用 app.render(request),因为如果你提供 404.astro 文件,Astro 会处理 404。如果你想以不同的方式处理 404,请使用 app.match(request)。
¥You can usually call app.render(request) without using .match because Astro handles 404s if you provide a 404.astro file. Use app.match(request) if you want to handle 404s in a different way.
默认情况下,即使匹配成功,预渲染的路由也不会返回。你可以通过将 true 用作第二个参数来更改此行为。
¥By default, prerendered routes aren’t returned, even if they are matched. You can change this behavior by using true as the second argument.
app.getAdapterLogger()
Section titled “app.getAdapterLogger()”类型:() => AstroIntegrationLogger
¥Type: () => AstroIntegrationLogger
astro@v3.0.0
返回适配器运行时环境可用的 Astro 日志记录器的实例。
¥Returns an instance of the Astro logger available to the adapter’s runtime environment.
const logger = app.getAdapterLogger();try { /* Some logic that can throw */} catch { logger.error("Your custom error message using Astro logger.");}app.getAllowedDomains()
Section titled “app.getAllowedDomains()”类型:() => Partial<RemotePattern>[] | undefined
¥Type: () => Partial<RemotePattern>[] | undefined
astro@5.14.2
使用按需渲染 如用户配置中定义 时,返回传入请求允许的主机模式列表。
¥Returns a list of permitted host patterns for incoming requests when using on-demand rendering as defined in the user configuration.
app.removeBase()
Section titled “app.removeBase()”类型:(pathname: string) => string
¥Type: (pathname: string) => string
astro@1.6.4
移除给定路径的根目录。这对于需要从文件系统中查找资源非常有用。
¥Removes the base from the given path. This is useful when you need to look up assets from the filesystem.
app.setCookieHeaders()
Section titled “app.setCookieHeaders()”类型:(response: Response) => Generator<string, string[], any>
¥Type: (response: Response) => Generator<string, string[], any>
astro@1.4.0
返回一个生成器,该生成器从 Response 对象生成各个 cookie 标头值。此功能用于正确处理请求处理期间可能设置的多个 Cookie。
¥Returns a generator that yields individual cookie header values from a Response object. This is used to properly handle multiple cookies that may have been set during request processing.
以下示例为从响应中获取的每个标头添加一个 Set-Cookie 标头:
¥The following example appends a Set-Cookie header for each header obtained from a response:
for (const setCookieHeader of app.setCookieHeaders(response)) { response.headers.append('Set-Cookie', setCookieHeader);}App.getSetCookieFromResponse()
Section titled “App.getSetCookieFromResponse()”类型:(response: Response) => Generator<string, string[]>
¥Type: (response: Response) => Generator<string, string[]>
astro@4.2.0
返回一个生成器,该生成器从 Response 对象生成各个 cookie 标头值。此方法与 app.setCookieHeaders() 的工作方式相同,但由于它是静态方法,因此可以随时使用。
¥Returns a generator that yields individual cookie header values from a Response object. This works in the same way as app.setCookieHeaders(), but can be used at any time as it is a static method.
以下示例为从响应中获取的每个标头添加一个 Set-Cookie 标头:
¥The following example appends a Set-Cookie header for each header obtained from a response:
for (const cookie of App.getSetCookieFromResponse(response)) { response.headers.append('Set-Cookie', cookie);}App.validateForwardedHost()
Section titled “App.validateForwardedHost()”类型:(forwardedHost: string, allowedDomains?: Partial<RemotePattern>[], protocol?: string = 'https') => boolean
¥Type: (forwardedHost: string, allowedDomains?: Partial<RemotePattern>[], protocol?: string = 'https') => boolean
astro@5.14.2
检查 forwardedHost 是否与给定的 allowedDomains 匹配。此静态方法接受第三个参数,允许你覆盖主机协议,默认为 https。
¥Checks whether a forwardedHost matches any of the given allowedDomains. This static method accepts a third argument that allows you to override the host protocol, defaulting to https.
以下示例从标头中检索 forwardedHost,并检查主机是否与允许的域匹配:
¥The following example retrieves the forwardedHost from the headers and checks if the host matches an allowed domain:
export function start(manifest) { addEventListener('fetch', (event) => { const forwardedHost = event.request.headers.get('X-Forwarded-Host'); if (App.validateForwardedHost(forwardedHost, manifest.allowedDomains)) { /* do something */ } });}App.sanitizeHost()
Section titled “App.sanitizeHost()”类型:(hostname: string | undefined) => string | undefined
¥Type: (hostname: string | undefined) => string | undefined
astro@5.15.5
验证主机名,拒绝任何包含路径分隔符的名称。当主机名无效时,此静态方法将返回 undefined。
¥Validates a hostname by rejecting any name containing path separators. When a hostname is invalid, this static method will return undefined.
以下示例从标头中检索 forwardedHost。并对其进行清理:
¥The following example retrieves the forwardedHost from the headers and sanitizes it:
export function start(manifest) { addEventListener('fetch', (event) => { const forwardedHost = event.request.headers.get('X-Forwarded-Host'); const sanitized = App.sanitizeHost(forwardedHost); });}App.validateForwardedHeaders()
Section titled “App.validateForwardedHeaders()”类型:(forwardedProtocol?: string, forwardedHost?: string, forwardedPort?: string, allowedDomains?: Partial<RemotePattern>[]) => { protocol?: string; host?: string; port?: string }
¥Type: (forwardedProtocol?: string, forwardedHost?: string, forwardedPort?: string, allowedDomains?: Partial<RemotePattern>[]) => { protocol?: string; host?: string; port?: string }
astro@5.15.5
根据 allowedDomains 验证转发的协议、主机和端口。此静态方法返回已验证的值,如果请求头被拒绝则返回 undefined。
¥Validates the forwarded protocol, host, and port against the allowedDomains. This static method returns validated values or undefined for rejected headers.
以下示例根据接收到的清单中定义的授权域验证转发的标头:
¥The following example validates the forwarded headers against the authorized domains defined in the received manifest:
export function start(manifest) { addEventListener('fetch', (event) => { const validated = App.validateForwardedHeaders( request.headers.get('X-Forwarded-Proto') ?? undefined, request.headers.get('X-Forwarded-Host') ?? undefined, request.headers.get('X-Forwarded-Port') ?? undefined, manifest.allowedDomains, ); });}astro/app/node
Section titled “astro/app/node”与 astro/app 一样,此模块用于渲染通过 astro build 预构建的页面。这允许你创建一个 NodeApp,提供 App 的所有可用方法以及适用于 Node 环境的其他方法。
¥Just like astro/app, this module is used for rendering pages that have been prebuilt through astro build. This allows you to create a NodeApp providing all the methods available from App and additional methods useful for Node environments.
NodeApp 构造函数接受一个必需的 SSR 清单参数,以及一个可选的用于启用或禁用流式传输的参数,默认为 true。
¥The NodeApp constructor accepts a required SSR manifest argument, and optionally an argument to enable or disable streaming, defaulting to true.
import { NodeApp } from 'astro/app/node';import http from 'http';
export function start(manifest) { const nodeApp = new NodeApp(manifest);
addEventListener('fetch', event => { event.respondWith( nodeApp.render(event.request) ); });}提供以下附加方法:
¥The following additional methods are provided:
nodeApp.render()
Section titled “nodeApp.render()”类型:(request: NodeRequest | Request, options?: RenderOptions) => Promise<Response>
¥Type: (request: NodeRequest | Request, options?: RenderOptions) => Promise<Response>
astro@4.0.0
扩展 app.render(),使其除了接受标准的 Request 对象作为第一个参数外,还接受 Node.js IncomingMessage 对象。第二个参数是一个可选对象,允许你使用 控制渲染。
¥Extends app.render() to also accept Node.js IncomingMessage objects in addition to standard Request objects as the first argument. The second argument is an optional object allowing you to control the rendering.
const response = await nodeApp.render(request);nodeApp.match()
Section titled “nodeApp.match()”类型:(req: NodeRequest | Request, allowPrerenderedRoutes?: boolean) => RouteData | undefined
¥Type: (req: NodeRequest | Request, allowPrerenderedRoutes?: boolean) => RouteData | undefined
扩展 app.match(),使其除了接受标准的 Request 对象外,还接受 Node.js IncomingMessage 对象。
¥Extends app.match() to also accept Node.js IncomingMessage objects in addition to standard Request objects.
if(nodeApp.match(request)) { const response = await nodeApp.render(request);}nodeApp.headersMap
Section titled “nodeApp.headersMap”类型:NodeAppHeadersJson | undefined
默认:undefined
¥Type: NodeAppHeadersJson | undefined
Default: undefined
astro@5.11.0
包含标头配置的数组。每个条目将路径名映射到应应用于该路由的标头列表。这对于将 CSP 指令等标头应用于预渲染路由非常有用。
¥An array containing the headers configuration. Each entry maps a pathname to a list of headers that should be applied for that route. This is useful for applying headers such as CSP directives to prerendered routes.
nodeApp.setHeadersMap()
Section titled “nodeApp.setHeadersMap()”类型:(headers: NodeAppHeadersJson) => void
¥Type: (headers: NodeAppHeadersJson) => void
astro@5.11.0
将 标头配置 加载到 NodeApp 实例中。
¥Loads headers configuration into the NodeApp instance.
nodeApp.setHeadersMap([ { pathname: "/blog", headers: [ { key: "Content-Security-Policy", value: "default-src 'self'" }, ] }]);NodeApp.createRequest()
Section titled “NodeApp.createRequest()”类型:(req: NodeRequest, options?: { skipBody?: boolean; allowedDomains?: Partial<RemotePattern>[]; }) => Request
¥Type: (req: NodeRequest, options?: { skipBody?: boolean; allowedDomains?: Partial<RemotePattern>[]; }) => Request
astro@4.2.0
将 NodeJS IncomingMessage 转换为标准的 Request 对象。此静态方法接受一个可选对象作为第二个参数,允许你定义是否应忽略请求体,默认为 false,如果忽略则返回 allowedDomains。
¥Converts a NodeJS IncomingMessage into a standard Request object. This static method accepts an optional object as the second argument, allowing you to define if the body should be ignored, defaulting to false, and the allowedDomains.
以下示例创建一个 Request 并将其传递给 app.render():
¥The following example creates a Request and passes it to app.render():
import { NodeApp } from 'astro/app/node';import { createServer } from 'node:http';
const server = createServer(async (req, res) => { const request = NodeApp.createRequest(req); const response = await app.render(request);})NodeApp.writeResponse()
Section titled “NodeApp.writeResponse()”类型:(source: Response, destination: ServerResponse) => Promise<ServerResponse<IncomingMessage> | undefined>
¥Type: (source: Response, destination: ServerResponse) => Promise<ServerResponse<IncomingMessage> | undefined>
astro@4.2.0
将符合 Web 标准的 Response 流式传输到 NodeJS 服务器响应中。此静态方法接受一个 Response 对象和初始 ServerResponse,然后返回一个 ServerResponse 对象的 Promise。
¥Streams a web-standard Response into a NodeJS server response. This static method takes a Response object and the initial ServerResponse before returning a promise of a ServerResponse object.
以下示例创建一个 Request,将其传递给 app.render(),并写入响应:
¥The following example creates a Request, passes it to app.render(), and writes the response:
import { NodeApp } from 'astro/app/node';import { createServer } from 'node:http';
const server = createServer(async (req, res) => { const request = NodeApp.createRequest(req); const response = await app.render(request); await NodeApp.writeResponse(response, res);})Astro 特性
Section titled “Astro 特性”¥Astro features
Astro 特性是一种适配器告知 Astro 其是否支持某个特性以及支持级别的方式。
¥Astro features are a way for an adapter to tell Astro whether they are able to support a feature, and also the adapter’s level of support.
当使用这些属性时,Astro 将:
¥When using these properties, Astro will:
-
运行特定验证;
-
将上下文信息发送到日志;
这些操作基于支持或不支持的功能、其支持级别、所需的日志记录量 以及用户自己的配置来运行。
¥These operations are run based on the features supported or not supported, their level of support, the desired amount of logging, and the user’s own configuration.
以下配置告诉 Astro,此适配器对 Sharp 内置图片服务具有实验性支持:
¥The following configuration tells Astro that this adapter has experimental support for the Sharp-powered built-in image service:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: 'experimental' } }); }, }, };}如果使用 Sharp 图片服务,Astro 将根据你的适配器支持向终端记录警告和错误:
¥If the Sharp image service is used, Astro will log a warning and error to the terminal based on your adapter’s support:
[@example/my-adapter] The feature is experimental and subject to issues or changes.
[@example/my-adapter] The currently selected adapter `@example/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build.可以另外提供一条消息,为用户提供更多上下文:
¥A message can additionally be provided to give more context to the user:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: { support: 'limited', message: 'This adapter has limited support for Sharp. Certain features may not work as expected.' } } }); }, }, };}此对象包含以下可配置功能:
¥This object contains the following configurable features:
staticOutput
Section titled “staticOutput”¥Type: AdapterSupport
定义适配器是否能够提供静态页面。
¥Defines whether the adapter is able to serve static pages.
hybridOutput
Section titled “hybridOutput”¥Type: AdapterSupport
定义适配器是否能够提供包含静态页面和按需渲染页面混合的网站。
¥Defines whether the adapter is able to serve sites that include a mix of static and on-demand rendered pages.
serverOutput
Section titled “serverOutput”¥Type: AdapterSupport
定义适配器是否能够提供按需渲染的页面。
¥Defines whether the adapter is able to serve on-demand rendered pages.
i18nDomains
Section titled “i18nDomains”¥Type: AdapterSupport
astro@4.3.0
定义适配器是否能够支持 i18n 域名。
¥Defines whether the adapter is able to support i18n domains.
envGetSecret
Section titled “envGetSecret”¥Type: AdapterSupport
astro@4.10.0
定义适配器是否能够支持从 astro:env/server 导出的 getSecret()。启用此功能后,你的适配器可以检索用户在 env.schema 中配置的密钥。
¥Defines whether the adapter is able to support getSecret() exported from astro:env/server. When enabled, this feature allows your adapter to retrieve secrets configured by users in env.schema.
以下示例通过将 有效的 AdapterSupportsKind 值 传递给适配器来启用此功能:
¥The following example enables the feature by passing a valid AdapterSupportsKind value to the adapter:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', supportedAstroFeatures: { envGetSecret: 'stable' } }); }, }, };}astro/env/setup 模块允许你为 getSecret() 提供实现。在 你的服务器入口点 中,请尽快调用 setGetEnv():
¥The astro/env/setup module allows you to provide an implementation for getSecret(). In your server entrypoint, call setGetEnv() as soon as possible:
import { App } from 'astro/app';import { setGetEnv } from "astro/env/setup"
setGetEnv((key) => process.env[key])
export function createExports(manifest) { const app = new App(manifest);
const handler = (event, context) => { // ... };
return { handler };}如果适配器支持密钥,请确保在将环境变量与请求关联时,在调用 getSecret() 之前调用 setGetEnv():
¥If the adapter supports secrets, be sure to call setGetEnv() before getSecret() when environment variables are tied to the request:
import type { SSRManifest } from 'astro';import { App } from 'astro/app';import { setGetEnv } from 'astro/env/setup';import { createGetEnv } from '../utils/env.js';
type Env = { [key: string]: unknown;};
export function createExports(manifest: SSRManifest) { const app = new App(manifest);
const fetch = async (request: Request, env: Env) => { setGetEnv(createGetEnv(env));
const response = await app.render(request);
return response; };
return { default: { fetch } };}sharpImageService
Section titled “sharpImageService”¥Type: AdapterSupport
astro@5.0.0
定义适配器是否支持使用内置 Sharp 图片服务进行图片转换。
¥Defines whether the adapter supports image transformation using the built-in Sharp image service.
¥Adapter features
一组更改触发文件的输出的功能。当适配器选择启用这些功能时,它们将在特定的钩子中获取附加信息,并且必须实现适当的逻辑来处理不同的输出。
¥A set of features that changes the output of the emitted files. When an adapter opts in to these features, they will get additional information inside specific hooks and must implement the proper logic to handle the different output.
edgeMiddleware
Section titled “edgeMiddleware”类型:boolean
¥Type: boolean
定义在构建时是否会打包任何按需渲染中间件代码。
¥Defines whether any on-demand rendering middleware code will be bundled when built.
启用后,这可以防止中间件代码在构建期间被所有页面打包和导入:
¥When enabled, this prevents middleware code from being bundled and imported by all pages during the build:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', adapterFeatures: { edgeMiddleware: true } }); }, }, };}然后,使用钩子 astro:build:ssr,这将为你提供文件系统上物理文件的 middlewareEntryPoint、URL。
¥Then, consume the hook astro:build:ssr, which will give you a middlewareEntryPoint, an URL to the physical file on the file system.
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', adapterFeatures: { edgeMiddleware: true } }); },
'astro:build:ssr': ({ middlewareEntryPoint }) => { // remember to check if this property exits, it will be `undefined` if the adapter doesn't opt in to the feature if (middlewareEntryPoint) { createEdgeMiddleware(middlewareEntryPoint) } } }, };}
function createEdgeMiddleware(middlewareEntryPoint) { // emit a new physical file using your bundler}buildOutput
Section titled “buildOutput”类型:"static" | "server"
默认:"server"
¥Type: "static" | "server"
Default: "server"
astro@5.0.0
允许你强制构建使用特定的输出格式。这对于仅适用于特定输出类型的适配器非常有用。例如,你的适配器可能期望一个静态网站,但使用适配器来创建特定于主机的文件。如果未指定,则默认为 server。
¥Allows you to force a specific output shape for the build. This can be useful for adapters that only work with a specific output type. For example, your adapter might expect a static website, but uses an adapter to create host-specific files. Defaults to server if not specified.
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', adapterFeatures: { buildOutput: 'static' } }); }, }, };}experimentalStaticHeaders
Section titled “experimentalStaticHeaders”类型:boolean
¥Type: boolean
astro@5.9.3
适配器是否提供对设置静态页面响应标头的实验性支持。启用此功能后,Astro 将返回静态页面触发的 Headers 的映射。此映射 experimentalRouteToHeaders 可在 astro:build:generated 钩 中使用,用于生成诸如 _headers 之类的文件,允许你更改默认 HTTP 标头。
¥Whether or not the adapter provides experimental support for setting response headers for static pages. When this feature is enabled, Astro will return a map of the Headers emitted by the static pages. This map experimentalRouteToHeaders is available in the astro:build:generated hook for generating files such as a _headers that allows you to make changes to the default HTTP header.
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', adapterFeatures: { experimentalStaticHeaders: true, }, }); }, 'astro:build:generated': ({ experimentalRouteToHeaders }) => { // use `experimentalRouteToHeaders` to generate a configuration file // for your virtual host of choice }, }, };}标头的值可能会根据应用启用/使用的功能而变化。例如,如果 已启用 CSP 为真,则不会将 <meta http-equiv="content-security-policy"> 元素添加到静态页面。或者,它的 content 可在 experimentalRouteToHeaders 映射中找到。
¥The value of the headers might change based on the features enabled/used by the application. For example, if CSP is enabled, the <meta http-equiv="content-security-policy"> element is not added to the static page. Instead, its content is available in the experimentalRouteToHeaders map.
适配器类型参考
Section titled “适配器类型参考”¥Adapter types reference
AdapterSupport
Section titled “AdapterSupport”类型:AdapterSupportsKind | AdapterSupportWithMessage
¥Type: AdapterSupportsKind | AdapterSupportWithMessage
astro@5.0.0
用于描述功能支持级别的有效格式的并集。
¥A union of valid formats to describe the support level for a feature.
AdapterSupportsKind
Section titled “AdapterSupportsKind”类型:"deprecated" | "experimental" | "limited" | "stable" | "unsupported"
¥Type: "deprecated" | "experimental" | "limited" | "stable" | "unsupported"
定义适配器对某个功能的支持级别:
¥Defines the level of support for a feature by your adapter:
-
当你的适配器在未来的版本中完全移除某个功能之前,先弃用对其的支持时,请使用
"deprecated"。 -
当你的适配器添加了对某个功能的支持,但预计会出现问题或重大变更时,请使用
"experimental"。 -
当你的适配器仅支持完整功能的一部分时,请使用
"limited"。 -
当你的适配器完全支持此功能时,请使用
"stable"。 -
使用
"unsupported"警告用户,由于你的适配器不支持此功能,他们的项目可能会遇到构建问题。
AdapterSupportWithMessage
Section titled “AdapterSupportWithMessage”
Added in:
astro@5.0.0
一个允许你定义功能支持级别以及要在用户控制台中记录的消息的对象。此对象包含以下属性:
¥An object that allows you to define a support level for a feature and a message to be logged in the user console. This object contains the following properties:
support
Section titled “support”类型:Exclude<AdapterSupportsKind, “stable”>
¥Type: Exclude<AdapterSupportsKind, “stable”>
定义适配器对某个功能的支持级别。
¥Defines the level of support for a feature by your adapter.
message
Section titled “message”类型:string
¥Type: string
定义一条自定义消息,用于记录适配器对某个功能的支持情况。
¥Defines a custom message to log regarding the support of a feature by your adapter.
suppress
Section titled “suppress”类型:"default" | "all"
¥Type: "default" | "all"
astro@5.9.0
此选项可防止显示有关适配器对某项功能支持的部分或全部记录消息。
¥An option to prevent showing some or all logged messages about an adapter’s support for a feature.
如果 Astro 的默认日志消息是冗余的,或者与你的 自定义 message 结合使用会使用户感到困惑,你可以使用 suppress: "default" 来抑制默认消息,仅记录你自己的消息:
¥If Astro’s default log message is redundant, or confusing to the user in combination with your custom message, you can use suppress: "default" to suppress the default message and only log your message:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: { support: 'limited', message: 'The adapter has limited support for Sharp. It will be used for images during build time, but will not work at runtime.', suppress: 'default' // custom message is more detailed than the default } } }); }, }, };}你还可以使用 suppress: "all" 隐藏所有关于支持该功能的消息。当这些消息在特定上下文中对用户无用时(例如,当他们的配置设置意味着他们未使用该功能时),此功能很有用。例如,你可以选择阻止从适配器记录任何有关 Sharp 支持的消息:
¥You can also use suppress: "all" to suppress all messages about support for the feature. This is useful when these messages are unhelpful to users in a specific context, such as when they have a configuration setting that means they are not using that feature. For example, you can choose to prevent logging any messages about Sharp support from your adapter:
export default function createIntegration() { return { name: '@example/my-adapter', hooks: { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@example/my-adapter', serverEntrypoint: '@example/my-adapter/server.js', supportedAstroFeatures: { sharpImageService: { support: 'limited', message: 'This adapter has limited support for Sharp. Certain features may not work as expected.', suppress: 'all' } } }); }, }, };}允许通过 astro add 安装
Section titled “允许通过 astro add 安装”¥Allow installation via astro add
astro add 命令 允许用户轻松地将集成和适配器添加到他们的项目中。要允许使用此命令安装你的适配器,请将 astro-adapter 添加到 package.json 中的 keywords 字段:
¥The astro add command allows users to easily add integrations and adapters to their project. To allow your adapter to be installed with this command, add astro-adapter to the keywords field in your package.json:
{ "name": "example", "keywords": ["astro-adapter"],}使用 将你的适配器发布到 npm 后,运行 astro add example 将安装你的软件包以及 package.json 中指定的任何对等依赖,并提示用户手动更新其项目配置。
¥Once you publish your adapter to npm, running astro add example will install your package with any peer dependencies specified in your package.json and instruct users to update their project config manually.