Спросите свой вопрос и получите сводку документа, используя эту страницу и выбранного вами поставщика AI
Содержимое этой страницы было переведено с помощью ИИ.
Смотреть последнюю версию оригинального контента на английскомЕсли у вас есть идея по улучшению этой документации, не стесняйтесь внести свой вклад, подав запрос на вытягивание на GitHub.
Ссылка на документацию GitHubКопировать Markdown документа в буфер обмена
import PackageManagerTabs from '/components/tabs/PackageManagerTabs.astro'
import ReadMore from '/components/ReadMore.astro';
import Since from '~/components/Since.astro';
import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';
This adapter allows Astro to deploy your on-demand rendered routes and features to Cloudflare, including server islands, actions, and sessions.
If you're using Astro as a static site builder, you don't need an adapter.
Learn how to deploy your Astro site in our Cloudflare deployment guide.
Why 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 includes an astro add command to automate the setup of official integrations. If you prefer, you can install integrations manually instead.
Add the Cloudflare adapter to enable server-rendering 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.
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
First, add the @astrojs/cloudflare adapter to your project's dependencies using your preferred package manager.
Then, add the adapter to your astro.config.mjs file:
Копировать код в буфер обмена
import { defineConfig } from 'astro/config';import cloudflare from '@astrojs/cloudflare';export default defineConfig({ adapter: cloudflare(),});
Options
The Cloudflare adapter accepts the following options:
cloudflareModules
Enables imports of .wasm, .bin, and .txt modules.
This functionality is enabled by default. If you'd like to disable, set cloudflareModules to false.
imageService
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: Uses the Cloudflare Image Resizing service.
- passthrough: Uses the existing noop service.
- compile: Uses Astro's default service (sharp), but only on pre-rendered routes at build time. For pages rendered on-demand, all astro:assets features are disabled.
- custom: Always uses the image service configured in Image Options. This option will not check to see whether the configured image service works in Cloudflare's workerd runtime.
Копировать код в буфер обмена
import { defineConfig } from "astro/config";import cloudflare from '@astrojs/cloudflare';export default defineConfig({ adapter: cloudflare({ imageService: 'cloudflare' }),})
platformProxy
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.
:::note Proxies provided by this are a best effort emulation of the real production. Although they are designed to be as close as possible to the real thing, there might be a slight differences and inconsistencies between the two. :::
platformProxy.enabled
Determines whether to enable the Cloudflare runtime in development mode.
platformProxy.configPath
Defines the path to the Wrangler configuration file. If no value is set, it tracks wrangler.toml, wrangler.json, and wrangler.jsonc in the project root.
platformProxy.environment
Sets the Cloudflare environment to use. You must select an environment defined in the Wrangler configuration file, otherwise an error occurs.
platformProxy.persist
Sets whether and where to save binding data locally to the file system.
- If set to true, binding data is stored in .wrangler/state/v3/. It is the same as the default setting for wrangler.
- If set to false, binding data is not stored in file system.
- If set to { path: string }, binding data is stored in the specified path.
:::note wrangler's --persist-to option adds a sub directory called v3 under the hood while the @astrojs/cloudflare persist property does not. For example, to reuse the same location as running wrangler dev --persist-to ./my-directory, you must specify: persist: { path: "./my-directory/v3" }. :::
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' }, }, }),});
routes.extend
On Cloudflare Workers, this option is not applicable. Refer to Routing on Cloudflare Workers for more information.
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.
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.
routes.extend.include
Configures additional routes to be generated on demand by the Cloudflare adapter in the routes.extend.include array.
routes.extend.exclude
Configures 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 server 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 server function.
Копировать код в буфер обмена
export default defineConfig({ adapter: cloudflare({ routes: { extend: { include: [{ pattern: '/static' }], // Route a prerended page to the server function for on-demand rendering exclude: [{ pattern: '/pagefind/*' }], // Use Starlight's pagefind search, which is generated statically at build time } }, }),});
sessionKVBindingName
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.
Копировать код в буфер обмена
export default defineConfig({ adapter: cloudflare({ sessionKVBindingName: 'MY_SESSION_BINDING', }),});
workerEntryPoint
Type: { path: string | URL, namedExports: string[] } Default: { path: '@astrojs/cloudflare/entrypoints/server.js', namedExports: [] }
A configuration object to specify the workerEntryPoint for your Cloudflare Worker when you use the astro build command.
It allows you to optionally specify both a custom file path and namedExports:
Копировать код в буфер обмена
import cloudflare from '@astrojs/cloudflare';import { defineConfig } from 'astro/config';export default defineConfig({ adapter: cloudflare({ workerEntryPoint: { path: 'src/worker.ts', namedExports: ['MyDurableObject'] } }),});
workerEntryPoint.path
Type: string Default: @astrojs/cloudflare/entrypoints/server.js
The path to the entry file. This should be a relative path from the root of your Astro project.
By default, the adapter uses a generic entry file, which only supports the fetch handler.
To support other Cloudflare invocation handlers, you can create a custom file to use as the entry point. This is useful if you want to use features that require other handlers (e.g. Durable Objects, Cloudflare Queues, Scheduled Invocations).
workerEntryPoint.namedExports
Type: [] Default: []
An array of named exports to use for the entry file.
Provide any additional defined named exports of your custom entry file (e.g. DurableObject). If not provided, only default exports will be included.
Creating a custom Cloudflare Worker entry file
The custom entry file must export the createExports() function with a default export including all the handlers you need.
The following example entry file registers a Durable Object and a queue handler:
Копировать код в буфер обмена
import type { SSRManifest } from 'astro';import { App } from 'astro/app';import { handle } from '@astrojs/cloudflare/handler'import { DurableObject } from 'cloudflare:workers';class MyDurableObject extends DurableObject<Env> { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env) }}export function createExports(manifest: SSRManifest) { const app = new App(manifest); return { default: { async fetch(request, env, ctx) { await env.MY_QUEUE.send("log"); return handle(manifest, app, request, env, ctx); }, async queue(batch, _env) { let messages = JSON.stringify(batch.messages); console.log(`consumed from our queue: ${messages}`); } } satisfies ExportedHandler<Env>, MyDurableObject: MyDurableObject, }}
Cloudflare runtime
Usage
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.
You can access the bindings from Astro.locals.runtime:
Копировать код в буфер обмена
---const { env } = Astro.locals.runtime;---
You can access the runtime from API endpoints through context.locals:
Копировать код в буфер обмена
export function GET(context) { const runtime = context.locals.runtime; return new Response('Some body');}
See the list of all supported bindings in the Cloudflare documentation.
Environment variables and secrets
The Cloudflare runtime treats environment variables as a type of binding.
For example, you can define an environment variable in wrangler.json as follows:
Копировать код в буфер обмена
{ "vars" : { "MY_VARIABLE": "test" }}
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.
To define secrets, add them through the Wrangler CLI rather than in your Wrangler config file.
Копировать код в буфер обмена
npx wrangler secret put <KEY>
To set secrets for local development, you also need to add a .dev.vars file to the root of the Astro project:
Копировать код в буфер обмена
DB_PASSWORD=myPassword
You can then access environment variables, including secrets, from the env object available from Astro.locals.runtime:
Копировать код в буфер обмена
---const { env } = Astro.locals.runtime;const myVariable = env.MY_VARIABLE;const secret = env.DB_PASSWORD;---
Cloudflare environment variables and secrets are compatible with the astro:env API.
Typing
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.
Every time you change your configuration files (e.g. wrangler.toml, .dev.vars) you need to run wrangler types.
:::note You can create a pnpm script to run wrangler types automatically before other commands.
Копировать код в буфер обмена
{ "scripts": { "dev": "wrangler types && astro dev", "start": "wrangler types && astro dev", "build": "wrangler types && astro check && astro build", "preview": "wrangler types && astro preview", "astro": "astro" }}
:::
You can type the runtime object using Runtime:
Копировать код в буфер обмена
type Runtime = import('@astrojs/cloudflare').Runtime<Env>;declare namespace App { interface Locals extends Runtime { otherLocals: { test: string; }; }}
Cloudflare Platform
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.
This is available on Cloudflare Workers and Pages.
Assets
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
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.
This is available on Cloudflare Workers and Pages.
Routes
Routing on 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 on-demand rendering. Read more about static asset routing with Cloudflare Workers.
Unlike Cloudflare Pages, with Workers, you do not need a _routes.json file.
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:
Копировать код в буфер обмена
_worker.js_routes.json
Routing on Cloudflare Pages
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.
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.
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
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 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.
-
Create a KV namespace using the Wrangler CLI and make note of the ID of the new namespace:
shКопировать кодКопировать код в буфер обмена
npx wrangler kv namespace create "SESSION"
-
Declare the KV namespace in your Wrangler config, setting the namespace ID to the one returned by the previous command:
-
You can then use sessions in your server code:
astroКопировать кодКопировать код в буфер обмена
---export const prerender = false;const cart = await Astro.session?.get('cart');---<a href="/checkout">🛒 {cart?.length ?? 0} items</a>
:::note Writes to Cloudflare KV are eventually consistent between regions. This means that changes are available immediately within the same region but may take up to 60 seconds to propagate globally. This won't affect most users as they are unlikely to switch regions between requests, but it may be a consideration for some use cases, such as VPN users. :::
Cloudflare Module Imports
The Cloudflare workerd runtime supports imports of some non-standard module types. Most additional file types are also available in Astro:
- .wasm or .wasm?module: exports a WebAssembly.Module that can then be instantiated
- .bin: exports an ArrayBuffer of the raw binary contents of the file
- .txt: exports a string of the file contents
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.
The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together.
Копировать код в буфер обмена
// Import the WebAssembly moduleimport mod from '../util/add.wasm';// Instantiate first in order to use itconst 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)}`);}
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
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.
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.
Копировать код в буфер обмена
export const prerender = false;import { Buffer } from 'node:buffer';
You'll also need to modify the vite configuration in your Astro config to allow for the node:* import syntax:
Копировать код в буфер обмена
import {defineConfig} from "astro/config";import cloudflare from '@astrojs/cloudflare';export default defineConfig({ adapter: cloudflare({}), vite: { ssr: { external: ['node:buffer'], }, },})
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.
:::note[Package Compatibility Implications] If a project imports a package into the server that uses the Node.js runtime APIs, this can cause issues when deploying to Cloudflare. This issue arises with package that do not use the node:* import syntax. It is recommended that you contact the authors of the package to determine if the package supports the above import syntax. If the package does not support this, you may need to use a different package. :::
Preview with Wrangler
To use wrangler to run your application locally, update the preview script.
For Workers:
Копировать код в буфер обмена
"preview": "wrangler dev ./dist"
For Pages:
Копировать код в буфер обмена
"preview": "wrangler pages dev ./dist"
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
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.
Копировать код в буфер обмена
export default defineConfig({ adapter: cloudflare(), vite: { build: { minify: false, }, },});