Skip to content

@astrojs/ cloudflare

此适配器允许 Astro 将你的 按需渲染路由 部署到 Cloudflare

¥This adapter allows Astro to deploy your on-demand rendered routes to Cloudflare.

如果你将 Astro 用作静态站点构建器,则无需适配器即可部署到 Cloudflare。

¥If you’re using Astro as a static site builder, you don’t need an adapter to deploy to Cloudflare.

了解如何在我们的 Cloudflare 部署指南 中部署 Astro 站点。

¥Learn how to deploy your Astro site in our Cloudflare deployment guide.

为什么选择 Astro Cloudflare

标题部分 为什么选择 Astro Cloudflare

¥Why Astro Cloudflare

Cloudflare 的 开发者平台 让你可以开发全栈应用,并访问存储和 AI 等资源,所有资源均部署到全球边缘网络。此适配器构建你的 Astro 项目,以便通过 Cloudflare 进行部署。

¥Cloudflare’s Developer Platform lets you develop full-stack applications with access to resources such as storage and AI, all deployed to a global edge network. This adapter builds your Astro project for deployment through Cloudflare.

¥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 命令添加 Cloudflare 适配器以在你的 Astro 项目中启用 SSR。这将安装 @astrojs/cloudflare 并在一个步骤中对你的 astro.config.mjs 文件进行适当的更改。

¥Add the Cloudflare adapter to enable SSR in your Astro project with the astro add command. This will install @astrojs/cloudflare and make the appropriate changes to your astro.config.mjs file in one step.

终端窗口
npx astro add cloudflare

¥Manual Install

首先,使用你首选的包管理器将 @astrojs/cloudflare 适配器添加到项目的依赖中。

¥First, add the @astrojs/cloudflare adapter to your project’s dependencies using your preferred package manager.

终端窗口
npm install @astrojs/cloudflare

然后,将适配器和所需的 按需渲染模式 添加到你的 astro.config.mjs 文件中:

¥Then, add the adapter and your desired on-demand rendering mode to your astro.config.mjs file:

astro.config.mjs
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
output: 'server',
adapter: cloudflare(),
});

¥Options

Cloudflare 适配器接受以下选项:

¥The Cloudflare adapter accepts the following options:

类型:true | false
默认:true

¥Type: true | false
Default: true

启用 imports of .wasm, .bin, and .txt modules

¥Enables imports of .wasm, .bin, and .txt modules.

此功能默认启用。如果你想禁用它,请设置 cloudflareModules: false

¥This functionality is enabled by default. If you’d like to disable it, set cloudflareModules: false.

类型:'passthrough' | 'cloudflare' | 'compile' | 'custom'
默认:'compile'

¥Type: 'passthrough' | 'cloudflare' | 'compile' | 'custom'
Default: 'compile'

确定适配器使用哪个图片服务。配置不兼容的影像服务时,适配器将默认为 compile 模式。否则,它将使用全局配置的图片服务:

¥Determines which image service is used by the adapter. The adapter will default to compile mode when an incompatible image service is configured. Otherwise, it will use the globally configured image service:

  • cloudflare:使用 Cloudflare 图片大小调整 服务。

  • passthrough:使用现有的 noop 服务。

  • compile:使用 Astro 的默认服务(sharp),但仅在构建时在预渲染的路由上使用。在按需渲染页面的 SSR 期间,所有 astro:assets 功能均被禁用。

  • custom:始终使用在 图片选项 中配置的图片服务。此选项不会检查配置的图片服务是否在 Cloudflare 的 workerd 运行时中工作。

astro.config.mjs
import {defineConfig} from "astro/config";
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
adapter: cloudflare({
imageService: 'cloudflare'
}),
output: 'server'
})

确定是否以及如何将 Cloudflare 运行时添加到 astro dev。它包含本地 workerd 绑定的代理和 Cloudflare 特定值的模拟,允许在 Node.js 开发过程中模拟运行时。阅读有关 Cloudflare 运行时 的更多信息。

¥Determines whether and how the Cloudflare runtime is added to astro dev. It contains proxies to local workerd bindings and emulations of Cloudflare specific values, allowing the emulation of the runtime in the Node.js dev process. Read more about the Cloudflare Runtime.

类型:{ enabled?: boolean }
默认:{ enabled: false }

¥Type: { enabled?: boolean }
Default: { enabled: false }

enabled 属性允许你在 astro dev 中启用 Cloudflare 运行时。

¥The enabled property allows you to enable the Cloudflare runtime in astro dev.

类型:{ configPath?: string }
默认:{ configPath: 'wrangler.toml' }

¥Type: { configPath?: string }
Default: { configPath: 'wrangler.toml' }

configPath 属性允许你定义 Wrangler 配置文件,相对于 Astro 项目的根目录。

¥The configPath property allows you to define your Wrangler configuration file, relative to the root of your Astro project.

类型:{ environment?: string }
默认:{ environment: undefined }

¥Type: { environment?: string }
Default: { environment: undefined }

environment 属性允许你定义在 Wrangler 配置中使用哪个 环境配置

¥The environment property allows you to define which environment configuration in your Wrangler configuration to use.

类型:{ persist?: boolean | { path: string } }
默认:{ persist: true }

¥Type: { persist?: boolean | { path: string } }
Default: { persist: true }

persist 属性定义绑定数据是否持久以及在何处持久。true 默认为 Wrangler 使用的相同位置,因此数据可以在两者之间共享。如果是 false,则不会将任何数据持久保存到文件系统或从文件系统读取。

¥The persist property defines if and where the bindings data is persistent. true defaults to the same location used by Wrangler so data can be shared between the two. If false, no data is persisted to or read from the filesystem.

以下配置展示了在运行开发服务器时启用 Cloudflare 运行时以及使用 wrangler.json 配置文件的示例。它还指定了一个自定义位置,用于将数据持久保存到文件系统:

¥The following configuration shows an example of enabling the Cloudflare runtime when running the development server, as well as using a wrangler.json config file. It also specifies a custom location for persisting data to the filesystem:

import cloudflare from '@astrojs/cloudflare';
import { defineConfig } from 'astro/config';
export default defineConfig({
adapter: cloudflare({
platformProxy: {
enabled: true,
configPath: 'wrangler.json',
persist: {
path: './.cache/wrangler/v3'
},
},
}),
});

在 Cloudflare Workers 上,此选项不适用。有关更多信息,请参阅 Cloudflare 上的路由 Workers

¥On Cloudflare Workers, this option is not applicable. Refer to Routing on Cloudflare Workers for more information.

在 Cloudflare Pages 上,此选项允许你将自定义模式(例如 /fonts/*)添加到生成的 _routes.json 文件中,该文件决定了哪些路由是按需生成的。如果需要添加无法自动生成的路由模式或排除预渲染路由,则此功能很有用。

¥On Cloudflare Pages, this option allows you to add or exclude custom patterns (e.g. /fonts/*) to the generated _routes.json file that determines which routes are generated on-demand. This can be useful if you need to add route patterns which cannot be automatically generated, or exclude prerendered routes.

有关自定义路由模式的更多信息,请参见 Cloudflare 的路由文档。指定的任何路由都不会自动数据去重,并将按原样附加到现有路由。

¥More information about the custom route patterns can be found in Cloudflare’s routing docs. Any routes specified are not automatically deduplicated and will be appended to the existing routes as is.

类型:{ pattern: string }[]
默认:undefined

¥Type: { pattern: string }[]
Default: undefined

routes.extend.include 数组中配置 Cloudflare 适配器按需生成的其他路由。

¥Configure additional routes to be generated on demand by the Cloudflare adapter in the routes.extend.include array.

类型:{ pattern: string }[]
默认:undefined

¥Type: { pattern: string }[]
Default: undefined

routes.extend.exclude 数组中配置要从按需渲染中排除的路由。这些路由将被预渲染并以静态方式提供,并且不会调用 SSR 函数。此外,你可以使用此选项直接提供任何静态资源(例如图片、字体、css、js、html、txt、json 等)文件,而无需通过 SSR 函数路由请求。

¥Configure routes to be excluded from on-demand rendering in the routes.extend.exclude array. These routes will be prerendered and served statically instead, and will not invoke the SSR function. Additionally you can use this option to serve any static asset (e.g. images, fonts, css, js, html, txt, json, etc.) files directly without routing the request through the SSR function.

astro.config.mjs
export default defineConfig({
adapter: cloudflare({
routes: {
extend: {
include: [{ pattern: '/static' }], // Route a prerended page to the SSR function for on-demand rendering
exclude: [{ pattern: '/pagefind/*' }], // Use Starlight's pagefind search, which is generated statically at build time
}
},
}),
});

类型:string
默认:SESSION

¥Type: string
Default: SESSION

Added in: astro@5.6.0

sessionKVBindingName 选项允许你指定用于会话存储的键值绑定的名称。默认情况下,此名称设置为 SESSION,但你可以将其更改为你自己的键值绑定名称。请参阅 会话 了解更多信息。

¥The sessionKVBindingName option allows you to specify the name of the KV binding used for session storage. By default, this is set to SESSION, but you can change it to match your own KV binding name. See Sessions for more information.

astro.config.mjs
export default defineConfig({
adapter: cloudflare({
sessionKVBindingName: 'MY_SESSION_BINDING',
}),
});

¥Cloudflare runtime

¥Usage

Cloudflare 运行时允许你访问环境变量以及与 Cloudflare 资源的绑定。Cloudflare 运行时使用在 wrangler.toml/wrangler.json 配置文件中找到的绑定。

¥The Cloudflare runtime gives you access to environment variables and bindings to Cloudflare resources. The Cloudflare runtime uses bindings found in the wrangler.toml/wrangler.json configuration file.

你可以从 Astro.locals.runtime 访问绑定:

¥You can access the bindings from Astro.locals.runtime:

src/pages/index.astro
---
const { env } = Astro.locals.runtime;
---

你可以通过 context.locals 从 API 端点访问运行时:

¥You can access the runtime from API endpoints through context.locals:

src/pages/api/someFile.js
export function GET(context) {
const runtime = context.locals.runtime;
return new Response('Some body');
}

请参阅 Cloudflare 文档中的 所有支持的绑定列表

¥See the list of all supported bindings in the Cloudflare documentation.

¥Environment variables and secrets

Cloudflare 运行时将环境变量视为一种绑定。

¥The Cloudflare runtime treats environment variables as a type of binding.

例如,你可以在 wrangler.json 中定义 环境变量,如下所示:

¥For example, you can define an environment variable in wrangler.json as follows:

wrangler.json
{
"vars" : {
"MY_VARIABLE": "test"
}
}

Secret 是一种特殊类型的环境变量,允许你将加密的文本值附加到 Worker。需要对它们进行不同的定义,以确保在设置它们后不可见。

¥Secrets are a special type of environment variable that allow you to attach encrypted text values to your Worker. They need to be defined differently to ensure they are not visible after you set them.

要定义 secrets,请通过 Wrangler CLI 添加它们,而不是在 Wrangler 配置文件中添加。

¥To define secrets, add them through the Wrangler CLI rather than in your Wrangler config file.

终端窗口
npx wrangler secret put <KEY>

要设置本地开发的机密信息,你还需要将 .dev.vars 文件添加到 Astro 项目的根目录:

¥To set secrets for local development, you also need to add a .dev.vars file to the root of the Astro project:

.dev.vars
DB_PASSWORD=myPassword

然后,你可以从 Astro.locals.runtime 提供的 env 对象访问环境变量(包括机密信息):

¥You can then access environment variables, including secrets, from the env object available from Astro.locals.runtime:

src/pages/index.astro
---
const { env } = Astro.locals.runtime;
const myVariable = env.MY_VARIABLE;
const secret = env.DB_PASSWORD;
---

Cloudflare 环境变量和密钥与 astro:env API 兼容。

¥Cloudflare environment variables and secrets are compatible with the astro:env API.

¥Typing

wrangler 提供 types 命令来为绑定生成 TypeScript 类型。这允许你键入本地变量,而无需手动键入。有关更多信息,请参阅 Cloudflare 文档

¥wrangler provides a types command to generate TypeScript types for the bindings. This allows you to type locals without the need to manually type them. Refer to the Cloudflare documentation for more information.

每次更改配置文件(例如 wrangler.toml.dev.vars)时,都需要运行 wrangler types

¥Every time you change your configuration files (e.g. wrangler.toml, .dev.vars) you need to run wrangler types.

你可以使用 Runtime 输​​入 runtime 对象:

¥You can type the runtime object using Runtime:

src/env.d.ts
type Runtime = import('@astrojs/cloudflare').Runtime<Env>;
declare namespace App {
interface Locals extends Runtime {
otherLocals: {
test: string;
};
}
}

¥Cloudflare Platform

¥Headers

你可以通过在 Astro 项目的 public/ 文件夹中添加 _headers 文件来将 自定义标头 附加到你的响应中。该文件将被复制到你的构建输出目录。

¥You can attach custom headers to your responses by adding a _headers file in your Astro project’s public/ folder. This file will be copied to your build output directory.

这在 Cloudflare Workers 和 Pages 上可用。

¥This is available on Cloudflare Workers and Pages.

¥Assets

Astro 构建的资源都以哈希命名,因此可以赋予长缓存标头。默认情况下,Cloudflare 上的 Astro 将为这些文件添加这样的标头。

¥Assets built by Astro are all named with a hash and therefore can be given long cache headers. By default, Astro on Cloudflare will add such a header for these files.

¥Redirects

你可以声明 自定义重定向 将请求重定向到其他 URL。为此,请在 Astro 项目的 public/ 文件夹中添加一个 _redirects 文件。该文件将被复制到你的构建输出目录。

¥You can declare custom redirects to redirect requests to a different URL. To do so, add a _redirects file in your Astro project’s public/ folder. This file will be copied to your build output directory.

这在 Cloudflare Workers 和 Pages 上可用。

¥This is available on Cloudflare Workers and Pages.

¥Routes

Cloudflare 上的路由 Workers

标题部分 Cloudflare 上的路由 Workers

¥Routing on Cloudflare Workers

静态资源的路由基于构建目录中的文件结构(例如 ./dist)。如果未找到匹配项,将回退到 Worker 进行 SSR。了解更多关于 使用 Cloudflare Workers 进行静态资源路由 的信息。

¥Routing for static assets is based on the file structure in the build directory (e.g. ./dist). If no match is found, this will fall back to the Worker for SSR. Read more about static asset routing with Cloudflare Workers.

Cloudflare Pages 不同,使用 Workers,你不需要 _routes.json 文件。

¥Unlike Cloudflare Pages, with Workers, you do not need a _routes.json file.

目前,Cloudflare 适配器始终会生成此文件。要解决此问题,请在 public/ 文件夹中创建一个 .assetsignore 文件,并向其中添加以下几行:

¥Currently, the Cloudflare adapter always generates this file. To work around this, create a .assetsignore file in your public/ folder, and add the following lines to it:

public/.assetsignore
_worker.js
_routes.json

Cloudflare 页面上的路由

标题部分 Cloudflare 页面上的路由

¥Routing on Cloudflare Pages

对于 Cloudflare Pages,routing 使用 _routes.json 文件来确定哪些请求路由到服务器函数,哪些请求作为静态资源提供。默认情况下,将根据其文件和配置为你的项目自动生成 _routes.json 文件。

¥For Cloudflare Pages, routing uses a _routes.json file to determine which requests are routed to the server function and which are served as static assets. By default, a _routes.json file will be automatically generated for your project based on its files and configuration.

你可以在适配器配置中使用 指定要遵循的其他路由模式,或者创建自己的自定义 _routes.json 文件以完全覆盖自动生成。

¥You can specify additional routing patterns to follow in your adapter config, or create your own custom _routes.json file to fully override the automatic generation.

创建自定义 public/_routes.json 将覆盖自动生成。详细信息请参见 Cloudflare 关于创建自定义 _routes.json 的文档

¥Creating a custom public/_routes.json will override the automatic generation. See Cloudflare’s documentation on creating a custom _routes.json for more details.

¥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.

使用 Cloudflare 适配器时,Astro 会自动将 Workers KV 配置为会话存储。在使用会话之前,你需要创建一个键值命名空间来存储数据,并在 Wrangler 配置文件中配置键值绑定。默认情况下,Astro 期望键值绑定名为 SESSION,但你可以根据需要通过在适配器配置中设置 sessionKVBindingName 选项来选择其他名称。

¥Astro automatically configures Workers KV for session storage when using the Cloudflare adapter. Before using sessions, you need to create a KV namespace to store the data and configure a KV binding in your Wrangler config file. By default, Astro expects the KV binding to be named SESSION, but you can choose a different name if you prefer by setting the sessionKVBindingName option in the adapter config.

  1. Create a KV namespace using the Wrangler CLI and make note of the ID of the new namespace:

    终端窗口
    npx wrangler kv namespace create "SESSION"
  2. Declare the KV namespace in your Wrangler config, setting the namespace ID to the one returned by the previous command:

    wrangler.json
    {
    "kv_namespaces": [
    {
    "binding": "SESSION",
    "id": "<KV_NAMESPACE_ID>"
    }
    ]
    }
  3. You can then use sessions in your server code:

    src/components/CartButton.astro
    ---
    export const prerender = false;
    const cart = await Astro.session?.get('cart');
    ---
    <a href="/checkout">🛒 {cart?.length ?? 0} items</a>

¥Cloudflare Module Imports

Cloudflare workerd 运行时支持导入部分 非标准模块类型。Astro 中也支持大多数其他文件类型:

¥The Cloudflare workerd runtime supports imports of some non-standard module types. Most additional file types are also available in Astro:

  • .wasm.wasm?module:导出一个可以实例化的 WebAssembly.Module

  • .bin:导出文件原始二进制内容的 ArrayBuffer

  • .txt:导出文件内容的字符串

所有模块类型都导出单个默认值。模块既可以从服务器端渲染的页面导入,也可以从预渲染的页面导入,以生成静态站点。

¥All module types export a single default value. Modules can be imported both from server-side rendered pages, or from prerendered pages for static site generation.

以下是导入 Wasm 模块的示例,该模块然后通过将请求的数字参数相加来响应请求。

¥The following is an example of importing a Wasm module that then responds to requests by adding the request’s number parameters together.

pages/add/[a]/[b].js
// Import the WebAssembly module
import mod from '../util/add.wasm';
// Instantiate first in order to use it
const addModule: any = new WebAssembly.Instance(mod);
export async function GET(context) {
const a = Number.parseInt(context.params.a);
const b = Number.parseInt(context.params.b);
return new Response(`${addModule.exports.add(a, b)}`);
}

虽然这个例子很简单,但 Wasm 可用于加速不涉及大量 I/O 的计算密集型操作,例如嵌入图片处理库,或嵌入小型预索引数据库以搜索只读数据集。

¥While this example is trivial, Wasm can be used to accelerate computationally intensive operations which do not involve significant I/O such as embedding an image processing library, or embedding a small pre-indexed database for search over a read-only dataset.

¥Node.js compatibility

开箱即用,Cloudflare 不支持 Node.js 运行时 API。通过一些配置,Cloudflare 确实支持 Node.js 运行时 API 的子集。你可以在 Cloudflare 的 documentation 中找到受支持的 Node.js 运行时 API。

¥Out of the box, Cloudflare does not support the Node.js runtime APIs. With some configuration, Cloudflare does support a subset of the Node.js runtime APIs. You can find supported Node.js runtime APIs in Cloudflare’s documentation.

要使用这些 API,你的页面或端点必须是服务器端渲染的(而不是预渲染的),并且必须使用 import {} from 'node:*' 导入语法。

¥To use these APIs, your page or endpoint must be server-side rendered (not pre-rendered) and must use the import {} from 'node:*' import syntax.

pages/api/endpoint.js
export const prerender = false;
import { Buffer } from 'node:buffer';

你还需要修改 Astro 配置中的 vite 配置,以允许使用 node:* 导入语法:

¥You’ll also need to modify the vite configuration in your Astro config to allow for the node:* import syntax:

astro.config.mjs
import {defineConfig} from "astro/config";
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
adapter: cloudflare({}),
output: 'server',
vite: {
ssr: {
external: ['node:buffer'],
},
},
})

此外,你需要按照 Cloudflare 的文档了解如何启用支持。详细指导请参阅 有关启用 Node.js 兼容性的 Cloudflare 文档

¥Additionally, you’ll need to follow Cloudflare’s documentation on how to enable support. For detailed guidance, please refer to the Cloudflare documentation on enabling Node.js compatibility.

使用 Wrangler 进行预览

标题部分 使用 Wrangler 进行预览

¥Preview with Wrangler

要使用 wrangler 在本地运行你的应用,请更新预览脚本。

¥To use wrangler to run your application locally, update the preview script.

用于 Workers:

¥For Workers:

package.json
"preview": "wrangler dev ./dist"

用于页面:

¥For Pages:

package.json
"preview": "wrangler pages dev ./dist"

使用 wrangler 进行开发可让你访问 Cloudflare 绑定环境变量cf 对象。要使 Astro 开发服务器的热重载与 Wrangler 配合使用,可能需要自定义设置。参见 社区例子

¥Developing with wrangler gives you access to Cloudflare bindings, environment variables, and the cf object. Getting hot reloading of the Astro dev server to work with Wrangler might require custom setup. See community examples.

¥Meaningful error messages

目前,由于代码的精简,在 Wrangler 中运行应用期间出现的错误并不是很有用。为了更好地调试,你可以将 vite.build.minify = false 设置添加到 astro.config.mjs

¥Currently, errors during running your application in Wrangler are not very useful, due to the minification of your code. For better debugging, you can add vite.build.minify = false setting to your astro.config.mjs.

astro.config.mjs
export default defineConfig({
adapter: cloudflare(),
output: 'server',
vite: {
build: {
minify: false,
},
},
});

更多集成

前端框架

SSR 适配器

其他集成

Astro v5.7 中文网 - 粤ICP备13048890号