@astrojs/ node
此适配器允许 Astro 将你的 按需渲染的路由和功能 部署到 Node 目标平台,包括 服务器岛、actions 和 sessions。
¥This adapter allows Astro to deploy your on-demand rendered routes and features to Node targets, including server islands, actions, and sessions.
如果你使用 Astro 作为静态站点构建器,则不需要适配器。
¥If you’re using Astro as a static site builder, you don’t need an adapter.
为什么选择 Astro Node.js
Section titled “为什么选择 Astro Node.js”¥Why Astro Node.js
Node.js 是服务器端代码的 JavaScript 运行时。@astrojs/node can be used either in standalone mode or as middleware for other http servers, such as Express.
¥Node.js is a JavaScript runtime for server-side code. @astrojs/node can be used either in standalone mode or as middleware for other http servers, such as Express.
¥Installation
Astro 包含一个 astro add 命令来自动设置官方集成。如果你愿意,你可以改用 安装集成手动。
¥Astro includes an astro add command to automate the setup of official integrations. If you prefer, you can install integrations manually instead.
使用 astro add 命令添加 Node 适配器以在你的 Astro 项目中启用按需渲染。这将安装 @astrojs/node 并在一个步骤中对你的 astro.config.* 文件进行适当的更改。
¥Add the Node adapter to enable on-demand rendering in your Astro project with the astro add command.
This will install @astrojs/node and make the appropriate changes to your astro.config.* file in one step.
npx astro add nodepnpm astro add nodeyarn astro add node现在,你可以启用 每页按需渲染,或将构建输出配置设置为 output: 'server' 到 默认服务器渲染所有页面。
¥Now, you can enable on-demand rendering per page, or set your build output configuration to output: 'server' to server-render all your pages by default.
¥Manual Install
首先,使用你首选的包管理器将 Node 适配器添加到项目的依赖中。
¥First, add the Node adapter to your project’s dependencies using your preferred package manager.
npm install @astrojs/nodepnpm add @astrojs/nodeyarn add @astrojs/node然后,将适配器添加到你的 astro.config.* 文件中:
¥Then, add the adapter to your astro.config.* file:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone', }),});¥Configuration
@astrojs/node can be configured by passing options into the adapter function.可以使用以下选项:
¥@astrojs/node can be configured by passing options into the adapter function. The following options are available:
类型:'middleware' | 'standalone'
¥Type: 'middleware' | 'standalone'
控制适配器是否构建为 middleware 或 standalone 模式。
¥Controls whether the adapter builds to middleware or standalone mode.
-
middleware模式允许将构建的输出用作另一个 Node.js 服务器的中间件,例如 Express.js 或 Fastify。 -
standalone模式构建一个服务器,在入口模块运行时自动启动。这使你能够更轻松地将构建部署到主机,而无需额外的代码。
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'middleware', }),});experimentalDisableStreaming
Section titled “experimentalDisableStreaming”类型:boolean
默认:false
¥Type: boolean
Default: false
@astrojs/node@9.3.0
禁用 Astro 按需渲染页面的默认 HTML 流式传输。
¥Disables Astro’s default HTML streaming for pages rendered on demand.
HTML 流式传输有助于提高性能,通常可提供更好的访客体验。大多数情况下,不建议禁用流媒体。
¥HTML streaming helps with performance and generally provides a better visitor experience. In most cases, disabling streaming is not recommended.
但是,当你需要禁用 HTML 流式传输(例如,你的主机仅支持 CDN 级别的非流式 HTML 缓存)时,你可以选择退出默认行为:
¥However, when you need to disable HTML streaming (e.g. your host only supports non-streamed HTML caching at the CDN level), you can opt out of the default behavior:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone', experimentalDisableStreaming: true, }),});experimentalStaticHeaders
Section titled “experimentalStaticHeaders”类型:boolean
默认:false
¥Type: boolean
Default: false
@astrojs/node@9.3.0
如果启用,适配器将使用 Astro 功能(例如内容安全策略)提供的 Response 对象来提供预渲染页面的标题。
¥If enabled, the adapter will serve the headers of prerendered pages using the Response object when provided by Astro features, such as Content Security Policy.
例如,启用 实验性内容安全策略 后,可以使用 experimentalStaticHeaders 将 CSP 标头添加到 Response 对象,而无需创建 <meta> 元素:
¥For example, when experimental Content Security Policy is enabled, experimentalStaticHeaders can be used to add the CSP headers to the Response object instead of creating a <meta> element:
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ experimental: { csp: true }, adapter: node({ mode: 'standalone', experimentalStaticHeaders: true, })});experimentalErrorPageHost
Section titled “experimentalErrorPageHost”类型:string | URL
默认:undefined
¥Type: string | URL
Default: undefined
@astrojs/node@9.4.0
指定用于加载预渲染 自定义错误页面 的备用主机。
¥Specifies an alternate host for loading prerendered custom error pages.
Astro 需要能够加载你的 404 页面才能将其作为响应返回。默认情况下,Astro 会从与请求相同的主机加载预渲染的自定义错误页面。例如,如果向 https://example.com/nonexistent-page 发出请求,Astro 将尝试从 https://example.com/404.html 加载预渲染的错误页面。
¥Astro needs to be able to load your 404 page in order to return it in a response. By default, Astro will load prerendered custom error pages from the same host as the one that the request is made to. For example, if a request is made to https://example.com/nonexistent-page, Astro will attempt to load the prerendered error page from https://example.com/404.html.
当你的自定义错误页面必须从不同的主机加载时,例如服务器运行在反向代理之后或可能无法访问外部主机 URL 的容器中时,请使用 experimentalErrorPageHost。当从本地主机加载预渲染的错误页面比通过公共互联网加载更高效时,你也可以使用此功能。
¥Use experimentalErrorPageHost when your custom error page must be loaded from a different host, such as when the server is running behind a reverse proxy or in a container that may not have access to the external host URL. You can also use this when it is more efficient to load the prerendered error page from localhost rather than via the public internet.
该值可以是字符串或 URL 对象。必须是包含协议的完整 URL(例如,http://localhost:4321)。Astro 将始终从根路径加载预渲染的错误页面,任何路径或查询参数都将被忽略。
¥The value can be a string or a URL object. It must be a fully-qualified URL, including the protocol (e.g., http://localhost:4321). Astro will always load the prerendered error page from the root path, and any path or query parameters will be ignored.
import { defineConfig } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ // Load pages from localhost, not the public URL. experimentalErrorPageHost: 'http://localhost:4321', })});¥Usage
首先,执行构建。根据选择的 mode(见上文),执行以下相应步骤:
¥First, performing a build. Depending on which mode selected (see above) follow the appropriate steps below:
¥Middleware
默认情况下,服务器入口点构建为 ./dist/server/entry.mjs。该模块导出 handler 函数,可与支持 Node request 和 response 对象的任何框架一起使用。
¥The server entrypoint is built to ./dist/server/entry.mjs by default. This module exports a handler function that can be used with any framework that supports the Node request and response objects.
例如,使用 Express:
¥For example, with Express:
import express from 'express';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = express();// Change this based on your astro.config.mjs, `base` option.// They should match. The default value is "/".const base = '/';app.use(base, express.static('dist/client/'));app.use(ssrHandler);
app.listen(8080);或者,使用 Fastify (>4):
¥Or, with Fastify (>4):
import Fastify from 'fastify';import fastifyMiddie from '@fastify/middie';import fastifyStatic from '@fastify/static';import { fileURLToPath } from 'node:url';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = Fastify({ logger: true });
await app .register(fastifyStatic, { root: fileURLToPath(new URL('./dist/client', import.meta.url)), }) .register(fastifyMiddie);app.use(ssrHandler);
app.listen({ port: 8080 });此外,你还可以传入要使用 Astro.locals 或 Astro 中间件访问的对象:
¥Additionally, you can also pass in an object to be accessed with Astro.locals or in Astro middleware:
import express from 'express';import { handler as ssrHandler } from './dist/server/entry.mjs';
const app = express();app.use(express.static('dist/client/'));app.use((req, res, next) => { const locals = { title: 'New title', };
ssrHandler(req, res, next, locals);});
app.listen(8080);请注意,中间件模式不提供文件服务。你需要配置 HTTP 框架来为你执行此操作。默认情况下,客户端资源写入 ./dist/client/。
¥Note that middleware mode does not do file serving. You’ll need to configure your HTTP framework to do that for you. By default the client assets are written to ./dist/client/.
¥Standalone
在独立模式下,服务器在服务器入口点运行时启动。默认情况下,它是按照 ./dist/server/entry.mjs 构建的。你可以使用以下命令运行它:
¥In standalone mode a server starts when the server entrypoint is run. By default it is built to ./dist/server/entry.mjs. You can run it with:
node ./dist/server/entry.mjs对于独立模式,服务器除了处理页面和 API 路由之外,还处理文件服务。
¥For standalone mode the server handles file serving in addition to the page and API routes.
自定义主机和端口
Section titled “自定义主机和端口”¥Custom host and port
你可以通过在运行时将其作为环境变量传递来覆盖独立服务器运行的主机和端口:
¥You can override the host and port the standalone server runs on by passing them as environment variables at runtime:
HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjs默认情况下,独立服务器使用 HTTP。如果你前面有一个执行 HTTPS 的代理服务器,则此方法效果很好。如果你需要独立服务器本身运行 HTTPS,则需要提供 SSL 密钥和证书。
¥By default the standalone server uses HTTP. This works well if you have a proxy server in front of it that does HTTPS. If you need the standalone server to run HTTPS itself you need to provide your SSL key and certificate.
你可以通过环境变量 SERVER_CERT_PATH 和 SERVER_KEY_PATH 传递密钥和证书的路径。这是你在 bash 中传递它们的方式:
¥You can pass the path to your key and certification via the environment variables SERVER_CERT_PATH and SERVER_KEY_PATH. This is how you might pass them in bash:
SERVER_KEY_PATH=./private/key.pem SERVER_CERT_PATH=./private/cert.pem node ./dist/server/entry.mjs¥Assets
在独立模式下,dist/client/ 文件夹中的资源通过独立服务器提供。你可能会将这些资源部署到 CDN,在这种情况下,服务器实际上永远不会为它们提供服务。但在某些情况下,例如 Intranet 站点,直接从应用服务器提供静态资源是可以的。
¥In standalone mode, assets in your dist/client/ folder are served via the standalone server. You might be deploying these assets to a CDN, in which case the server will never actually be serving them. But in some cases, such as intranet sites, it’s fine to serve static assets directly from the application server.
dist/client/_astro/ 文件夹中的资源是 Astro 构建的资源。这些资源都以哈希命名,因此可以给予长缓存标头。适配器在内部为这些资源添加此标头:
¥Assets in the dist/client/_astro/ folder are the ones that Astro has built. These assets are all named with a hash and therefore can be given long cache headers. Internally the adapter adds this header for these assets:
Cache-Control: public, max-age=31536000, immutable¥Sessions
Astro 会话 API 允许你轻松地在请求之间存储用户数据。这可用于处理用户数据和偏好设置、购物车和身份验证凭据等。与 Cookie 存储不同,数据没有大小限制,并且可以在不同设备上恢复。
¥The Astro Sessions API allows you to easily store user data between requests. This can be used for things like user data and preferences, shopping carts, and authentication credentials. Unlike cookie storage, there are no size limits on the data, and it can be restored on different devices.
Astro 使用 Node 适配器时,使用本地文件系统进行会话存储。如果你希望使用其他会话存储驱动程序,你可以在 Astro 配置中指定。详细信息请参见 session 配置参考。
¥Astro uses the local filesystem for session storage when using the Node adapter. If you would prefer to use a different session storage driver, you can specify it in your Astro config. See the session configuration reference for more details.
¥Environment variables
运行时使用 astro:env 密钥或 process.env 时,Astro 和适配器都不会自动加载环境变量。
¥When using the astro:env secrets or process.env at runtime, neither Astro nor the adapter loads environment variables for you.
某些主机可能会在构建期间和运行时通过其控制面板公开你配置的环境变量。请查阅主机文档,了解如何在特定平台上设置和使用环境变量。
¥Some hosts may expose the environment variables you configure through their dashboard during the build and at runtime. Check your host’s documentation for setting and using environment variables within the specific platform.
在自托管时,你可以根据需要通过 CLI 命令或配置文件加载环境变量:
¥When self-hosting, you can load environment variables through CLI commands or configuration files as appropriate:
DB_HOST=... DB_PASSWORD=... node ./dist/server/entry.mjsnpx dotenvx run -- node ./dist/server/entry.mjsFROM node:lts AS runtimeWORKDIR /app
COPY . .
RUN npm installRUN npm run build
ENV DB_HOST=...ENV DB_PASSWORD=...CMD node ./dist/server/entry.mjs