Skip to content

@astrojs/ cloudflare

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

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

如果你使用 Astro 作为静态站点构建器,则不需要适配器。

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

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

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

为什么选择 Astro Cloudflare

标题部分 为什么选择 Astro Cloudflare

¥Why Astro Cloudflare

Cloudflare 提供 CDN、网络安全和其他服务。此适配器增强了 Astro 构建过程,以准备通过 Cloudflare 部署你的项目。

¥Cloudflare provides CDNs, web security, and other services. This adapter enhances the Astro build process to prepare your 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

类型:'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 allows you to define your Wrangler configuration file, relative to the root of your Astro project.

platformProxy.experimentalJsonConfig

标题部分 platformProxy.experimentalJsonConfig

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

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

experimentalJsonConfig 属性定义实用程序是否读取 JSON 配置文件(例如 wrangler.json)。

¥The experimentalJsonConfig property defines whether the utility reads a JSON config file (e.g. wrangler.json).

类型:{ 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 (experimental). 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',
experimentalJsonConfig: true,
persist: './.cache/wrangler/v3',
},
}),
});

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

¥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
}
},
}),
});

类型: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.

¥Cloudflare runtime

Cloudflare 运行时使你可以访问环境变量和 Cloudflare 绑定。Cloudflare 运行时使用 wrangler.dev.vars 配置文件中的绑定。

¥The Cloudflare runtime gives you access to environment variables and Cloudflare bindings. The Cloudflare runtime uses bindings found in the wrangler and .dev.vars configuration files.

¥Usage

例如,如果你在 wrangler.toml 中设置了 环境变量 配置:

¥For example, if you have an environment variable configuration set up in wrangler.toml:

wrangler.toml
[vars]
MY_VARIABLE = "test"

如果除了环境变量之外,你还需要定义 secrets,则需要将 .dev.vars 文件添加到 Astro 项目的根目录中:

¥If you also need to define secrets in addition to environment variables, you need to add a .dev.vars file to the root of the Astro project:

.dev.vars
DB_PASSWORD=myPassword

你可以使用 Astro 本地变量访问绑定,如下所示:

¥You can access the bindings by using Astro locals like this:

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');
}

要访问 MY_VARIABLE 绑定的值,请将以下内容添加到你的代码中:

¥To access the value of the MY_VARIABLE binding add the following to your code:

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

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

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

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

¥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

你可以使用 Cloudflare Pages 声明 自定义重定向。这允许你将请求重定向到不同的 URL。你可以在 Astro 项目的 public/ 文件夹中添加 _redirects 文件。该文件将被复制到你的构建输出目录。

¥You can declare custom redirects using Cloudflare Pages. This allows you to redirect requests to a different URL. You can add a _redirects file in your Astro project’s public/ folder. This file will be copied to your build output directory.

¥Routes

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

¥Cloudflare routing uses a _routes.json file to determine which requests are routed to the SSR 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.

¥Custom _routes.json

创建自定义 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.

¥Cloudflare Module Imports

Cloudflare 工作器运行时支持导入某些 非标准模块类型。大多数其他文件类型也可在 astro 中使用:

¥The Cloudflare worker 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:

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

wrangler 允许你访问 Cloudflare 绑定环境变量cf 对象。获取 astro dev 服务器的热重载以与 Wrangler 配合使用可能需要自定义设置。参见 社区例子

¥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 中文网 - 粤ICP备13048890号