Astro Node.js 适配器 @astrojs/node

此适配器让 Astro 将按需渲染的路由和功能部署到 Node 目标,包括服务器岛屿、actions 和 sessions。

如果只把 Astro 用作静态站点生成器,就不需要适配器。

为什么使用 Astro Node.js

Node.js 是用于服务端代码的 JavaScript 运行时。@astrojs/node 既可独立运行,也可作为 Express 等 HTTP 服务器的中间件。

安装

Astro 的 astro add 可自动安装和配置官方集成,也可以手动安装。

运行以下命令之一,安装 Node 适配器并一步修改 astro.config.*:

npm:

npx astro add node

pnpm:

pnpm astro add node

Yarn:

yarn astro add node

然后可以逐页启用按需渲染,或者设置 output: 'server',让所有页面默认由服务器渲染。

手动安装

使用包管理器添加依赖。

npm:

npm install @astrojs/node

pnpm:

pnpm add @astrojs/node

Yarn:

yarn add @astrojs/node

然后在 astro.config.mjs 添加适配器:

import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  adapter: node({
    mode: 'standalone',
  }),
});

配置

向适配器函数传入选项进行配置。

mode

类型为 'middleware' | 'standalone',控制构建为中间件还是独立服务器。

middleware 让输出作为 Express.js、Fastify 等 Node.js 服务器的中间件。

standalone 构建独立服务器,运行入口模块时自动启动,无需额外代码即可部署。

import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  adapter: node({
    mode: 'middleware',
  }),
});

staticHeaders

布尔值,默认 false,新增于 @astrojs/node@10.0.0。

启用后,当 Astro 的内容安全策略等功能为预渲染页面提供响应头时,适配器通过 Response 对象发送这些头。

例如启用 CSP 时,可以让其使用响应头,而非创建 <meta>:

import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  security: {
    csp: true
  },
  adapter: node({
    mode: 'standalone',
    staticHeaders: true,
  })
});

experimentalDisableStreaming

布尔值,默认 false,新增于 @astrojs/node@9.3.0。

禁用按需渲染页面默认的 HTML 流式传输。流式传输通常有助于性能和访客体验,大多数情况下不建议关闭。

如果托管平台只支持 CDN 层面的非流式 HTML 缓存等情况,确实需要禁用,可以配置:

import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  adapter: node({
    mode: 'standalone',
    experimentalDisableStreaming: true,
  }),
});

bodySizeLimit

数字,默认 1073741824,即 1 GB,新增于 @astrojs/node@10.0.0。

设置请求体最大字节数。传入请求超过限制时,在读取请求体时抛出错误。

设为 Infinity 或 0 可完全禁用限制,适用于视频上传等大请求体场景。

import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
  adapter: node({
    mode: 'standalone',
    bodySizeLimit: 5 * 1024 * 1024 * 1024, // 5 GB
  }),
});

使用

先执行构建,再按照所选模式操作。

中间件模式

默认服务器入口为 ./dist/server/entry.mjs。模块导出 handler,可用于支持 Node request 与 response 对象的框架。

Express 的 run-server.mjs 示例:

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 以上版本示例:

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 中间件访问:

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/。

独立模式

运行服务器入口就会启动服务,默认入口为 ./dist/server/entry.mjs:

node ./dist/server/entry.mjs

独立模式除页面和 API 路由外,还负责文件服务。

自定义主机与端口

在运行时通过环境变量覆盖:

HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjs

HTTPS

独立服务器默认使用 HTTP,适合前面已有 HTTPS 代理的场景。如果需要它自己提供 HTTPS,必须提供 SSL 密钥和证书。

通过 SERVER_CERT_PATH 与 SERVER_KEY_PATH 传入路径,例如 bash:

SERVER_KEY_PATH=./private/key.pem SERVER_CERT_PATH=./private/cert.pem node ./dist/server/entry.mjs

静态资源

独立服务器提供 dist/client/ 中的资源。如果资源部署到 CDN,服务器实际不会提供它们;对于内网站点等情况,直接由应用服务器提供静态资源也可以。

dist/client/_astro/ 中是 Astro 构建的带哈希文件名资源,可使用长期缓存。适配器为它们添加:

Cache-Control: public, max-age=31536000, immutable

Sessions

Astro Sessions API 可以在请求之间保存用户数据,例如用户偏好、购物车和身份验证凭据。与 Cookie 存储不同,数据没有同样的大小限制,也可在不同设备上恢复。

Node 适配器默认使用本地文件系统保存 session。如果希望使用其他驱动,可以在 Astro 配置中指定,详情见 session 配置参考。

项目不使用 session 时,可以设置 session: false。适配器不会配置文件系统驱动,session 运行时代码也不会进入服务器包。

环境变量

运行时使用 astro:env 秘密值或 process.env 时,Astro 和适配器都不会自动加载环境变量。

某些托管平台会将控制台配置的变量暴露给构建和运行时,具体查阅平台文档。

自行托管时,可根据需要使用命令行或配置文件加载。

内联变量:

DB_HOST=... DB_PASSWORD=... node ./dist/server/entry.mjs

dotenvx:

npx @dotenvx/dotenvx run -- node ./dist/server/entry.mjs

Dockerfile:

FROM node:lts AS runtime
WORKDIR /app

COPY . .

RUN npm install
RUN npm run build

ENV DB_HOST=...
ENV DB_PASSWORD=...
CMD node ./dist/server/entry.mjs

原文:@astrojs/ node。作者/维护方:Astro 文档维护者。本文为中文翻译,代码及命令保留原文。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容