@astrojs/ cloudflare
هذا المحتوى غير متوفر بلغتك بعد.
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.
Astro 6 requires an upgrade to v13 of this adapter. See the Cloudflare adapter upgrade instructions for Astro 6 for breaking changes and migration guidance.
Why Astro Cloudflare
Section titled “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
Section titled “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.
npx astro add cloudflarepnpm astro add cloudflareyarn astro add cloudflareNow, 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
Section titled “Manual Install”-
Add the
@astrojs/cloudflareadapter to your project’s dependencies using your preferred package manager.Terminal window npm install @astrojs/cloudflareTerminal window pnpm add @astrojs/cloudflareTerminal window yarn add @astrojs/cloudflare -
Add the adapter to your
astro.config.mjsfile:astro.config.mjs import { defineConfig } from 'astro/config';import cloudflare from '@astrojs/cloudflare';export default defineConfig({adapter: cloudflare(),}); -
Astro will automatically generate a default configuration, using the package.json name field or the folder name as the Worker name. You can optionally create a Wrangler configuration file if you need custom settings. This example declares Cloudflare KV bindings:
wrangler.jsonc {"name": "my-astro-app",// Add your bindings here, e.g.:// "kv_namespaces": [{ "binding": "MY_KV", "id": "<namespace_id>" }]}
Options
Section titled “Options”The Cloudflare adapter accepts the following options:
cloudflareModules
Section titled “cloudflareModules”Type: boolean
Default: true
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
Section titled “imageService”Type: 'passthrough' | 'cloudflare' | 'cloudflare-binding' | 'compile' | 'custom'
Default: '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: Uses the Cloudflare Image Resizing service.cloudflare-binding: Uses the Cloudflare Images binding for image transformation. The binding is automatically provisioned when you deploy.passthrough: Uses the existingnoopservice.compile: Uses Astro’s default service (Sharp), but only on pre-rendered routes at build time. For pages rendered on demand, allastro:assetsfeatures 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’sworkerdruntime.
import { defineConfig } from 'astro/config';import cloudflare from '@astrojs/cloudflare';
export default defineConfig({ adapter: cloudflare({ imageService: 'cloudflare-binding', }),});sessionKVBindingName
Section titled “sessionKVBindingName”Type: string
Default: SESSION
astro@5.6.0
Sets the name of the KV binding used for session storage. By default, the KV namespace is automatically provisioned when you deploy, and is named SESSION. You can change this name by setting the binding manually in your wrangler config. See Sessions for more information.
export default defineConfig({ adapter: cloudflare({ sessionKVBindingName: 'MY_SESSION_BINDING', }),});{ "kv_namespaces": [ { "binding": "MY_SESSION_BINDING", } ]}imagesBindingName
Section titled “imagesBindingName”Type: string
Default: IMAGES
Sets the name of the Images binding used when imageService is set to cloudflare-binding. By default, the binding is automatically provisioned with the name IMAGES when you deploy. You can change it by setting the binding manually in your wrangler config:
export default defineConfig({ adapter: cloudflare({ imageService: 'cloudflare-binding', imagesBindingName: 'MY_IMAGES', }),});{ "images": { "binding": "MY_IMAGES" }}Cloudflare runtime
Section titled “Cloudflare runtime”The Cloudflare runtime gives you access to environment variables, bindings to Cloudflare resources, and other Cloudflare-specific APIs.
Environment variables and bindings
Section titled “Environment variables and bindings”Environment variables and bindings are defined in your wrangler.jsonc configuration file.
Define environment variables that do not store sensitive information in wrangler.jsonc:
{ "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 within Wrangler or Cloudflare dashboard 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, add a .dev.vars file to the root of the Astro project:
DB_PASSWORD=myPasswordCloudflare environment variables and secrets can be imported from "cloudflare:workers":
---import { env } from 'cloudflare:workers';
const myVariable = env.MY_VARIABLE;const myKVNamespace = env.MY_KV;---They are also compatible with the astro:env API:
import { MY_VARIABLE } from 'astro:env/server';See the list of all supported bindings in the Cloudflare documentation.
The cf object
Section titled “The cf object”The Cloudflare cf object contains request metadata such as geolocation information. Access it directly from the request:
---const cf = Astro.request.cf;const country = cf?.country;---Execution context
Section titled “Execution context”Access the Cloudflare ExecutionContext through Astro.locals.cfContext. This is useful for operations like waitUntil(), or accessing Durable Object exports within your page.
---const cfContext = Astro.locals.cfContext;cfContext.exports.Greeter.greet('Astro');cfContext.waitUntil(someAsyncOperation());---Typing
Section titled “Typing”wrangler provides a types command to generate TypeScript types for your bindings. This allows you to type your environment without the need for manual type definitions.
Run wrangler types every time you change your configuration files (e.g. wrangler.jsonc, .dev.vars).
The following example shows a script configuration 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" }}Cloudflare Platform
Section titled “Cloudflare Platform”Headers
Section titled “Headers”Add custom headers for static assets by creating a _headers file in your Astro project’s public/ folder. This file will be copied to the build output directory. Headers in _headers are not applied to responses generated by your Worker code.
Assets
Section titled “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
Section titled “Redirects”Declare custom redirects for static assets by adding a _redirects file in your Astro project’s public/ folder. This file will be copied to your build output directory. For dynamic routes, configure redirects in Astro directly instead.
Routes
Section titled “Routes”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.
Sessions
Section titled “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. Wrangler can automatically provision the KV namespace when you deploy, so no manual setup is required. Alternatively, you can define the KV binding manually in your wrangler.jsonc file and set a custom binding name using the sessionKVBindingName adapter option.
---export const prerender = false; // Not needed in 'server' modeconst cart = await Astro.session?.get('cart');---
<a href="/checkout">🛒 {cart?.length ?? 0} items</a>By default, the KV binding is named SESSION. To use a different name, set the sessionKVBindingName option in the adapter config.
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
Section titled “Cloudflare Module Imports”The Cloudflare workerd runtime supports imports of some non-standard module types. Most additional file types are also available in Astro:
.wasmor.wasm?module: exports aWebAssembly.Modulethat can then be instantiated.bin: exports anArrayBufferof 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
Section titled “Node.js compatibility”Cloudflare Workers support most Node.js runtime APIs through the nodejs_compat compatibility flag. This includes commonly used modules like node:buffer, node:crypto, node:path, and many others. See the full list of supported Node.js APIs in Cloudflare’s documentation.
To enable Node.js compatibility, add the nodejs_compat flag to your Wrangler configuration:
{ "compatibility_flags": ["nodejs_compat"],}Then use the node:* import syntax in your server-side code:
export const prerender = false; // Not needed in 'server' modeimport { Buffer } from 'node:buffer';For Node.js APIs not yet supported in the Workers runtime, Wrangler can inject polyfills (requires nodejs_compat and a compatibility date of 2024-09-23 or later).
Local preview
Section titled “Local preview”After building your project with astro build, use astro preview to test your Cloudflare Workers application locally. The preview runs using Cloudflare’s workerd runtime, closely mirroring production behavior.
Meaningful error messages
Section titled “Meaningful error messages”By default, errors occurring while running your application in Wrangler are minified. For better debugging, add vite.build.minify = false to your astro.config.mjs:
export default defineConfig({ adapter: cloudflare(), vite: { build: { minify: false, }, },});Using with Cloudflare Pages
Section titled “Using with Cloudflare Pages”The Cloudflare adapter deploys to Cloudflare Workers by default. To deploy to Cloudflare Pages instead, additional manual configuration is required.
Cloudflare recommends using Workers for new projects. See Cloudflare’s migration guide from Pages to Workers for more information if you have an existing project using Pages.
-
Configure your build output directories in
astro.config.mjs:astro.config.mjs import { defineConfig } from 'astro/config';import cloudflare from '@astrojs/cloudflare';export default defineConfig({adapter: cloudflare(),build: {client: './',server: './_worker.js',},}); -
Create a
_routes.jsonfile in yourpublic/folder to route requests to your Worker:public/_routes.json {"version": 1,"include": ["/*"], // Alternatively, specify specific routes"exclude": ["/static/*"] // Exclude static assets if needed}See the Cloudflare documentation on routing with Pages for more details.
Upgrading to v13 and Astro 6
Section titled “Upgrading to v13 and Astro 6”Astro 6 brings significant improvements to the Cloudflare development experience and requires @astrojs/cloudflare v13 or later. Now, astro dev uses Cloudflare’s Vite plugin and workerd runtime to closely mirror production behavior.
Development server now uses workerd
Section titled “Development server now uses workerd”The biggest change for Cloudflare users in Astro 6 is that astro dev and astro preview now use the Cloudflare Vite plugin to run your site using the real Workers runtime (workerd) instead of Node.js. This means your development environment is now a much closer replica of your production environment, with the same runtime, APIs, and behavior.
This change helps you catch issues during development that would have previously only appeared in production, and features like Durable Objects, R2 bindings, and Workers AI now work exactly as they do when deployed to Cloudflare’s platform.
This change is transparent for most projects. If your project had special configuration for astro dev or was relying on Node.js-specific behavior in development, adjust your code or configuration accordingly.
Changed: Wrangler entrypoint configuration
Section titled “Changed: Wrangler entrypoint configuration”Previously, the main field in your Wrangler configuration pointed to the built worker file (e.g. dist/_worker.js/index.js). With Astro 6, this has changed to point to a new unified entrypoint provided by the Cloudflare adapter: @astrojs/cloudflare/entrypoints/server.
Update your wrangler.jsonc to use the new entrypoint:
{ "main": "dist/_worker.js/index.js", "main": "@astrojs/cloudflare/entrypoints/server", "name": "my-astro-app", // ... rest of config}This single entrypoint handles both astro dev and production deployments.
Removed: Astro.locals.runtime API
Section titled “Removed: Astro.locals.runtime API”The Astro.locals.runtime object has been removed in favor of direct access to Cloudflare Workers APIs. Access environment variables, the cf object, caches, and execution context directly through the provided interfaces.
Accessing environment variables:
Previously, environment variables were accessed through Astro.locals.runtime.env. Now import env directly instead:
const { env } = Astro.locals.runtime;import { env } from 'cloudflare:workers';Accessing the cf object:
Previously, the cf object was accessed through Astro.locals.runtime.cf. Now access it directly from the request:
const { cf } = Astro.locals.runtime;const cf = Astro.request.cf;Accessing the caches API:
Previously, the caches API was accessed through Astro.locals.runtime.caches. Now use the global caches object directly:
const { caches } = Astro.locals.runtime;
caches.default.put(request, response);Accessing the execution context:
The Astro.locals.runtime.ctx object is replaced with Astro.locals.cfContext, which contains the Cloudflare ExecutionContext:
const ctx = Astro.locals.runtime.ctx;const ctx = Astro.locals.cfContext;Changed: Wrangler configuration file is now optional
Section titled “Changed: Wrangler configuration file is now optional”The Wrangler configuration file is now optional for simple projects. If you don’t have custom configuration, such as Cloudflare bindings (KV, D1, Durable Objects, etc.), Astro will automatically generate a default configuration for you.
If your wrangler.jsonc only contains basic configuration like this:
{ "main": "@astrojs/cloudflare/entrypoints/server", "compatibility_date": "2025-05-21", "assets": { "directory": "./dist", "binding": "ASSETS", },}You can safely delete this file. Astro handles this configuration automatically. Alternatively, create a minimal wrangler.jsonc with just your project name and other custom settings:
{ "name": "my-astro-app",}Changed: Custom entrypoint API
Section titled “Changed: Custom entrypoint API”If you were using a custom workerEntryPoint configuration in the adapter options, this has been removed. Instead, specify your custom entrypoint in your Wrangler configuration and create a standard Cloudflare Worker export object directly, rather than using the createExports() function.
-
Remove the
workerEntryPointoption from your adapter config:astro.config.mjs import { defineConfig } from 'astro/config';import cloudflare from '@astrojs/cloudflare';export default defineConfig({adapter: cloudflare({workerEntryPoint: {path: 'src/worker.ts',namedExports: ['MyDurableObject'],},}),}); -
Specify the entrypoint in
wrangler.jsoncinstead:wrangler.jsonc {"main": "./src/worker.ts"} -
Update your custom worker entry file to use standard Worker syntax. Import the handler from
@astrojs/cloudflare/entrypoints/serverand export a standard Cloudflare Worker object, alongside any custom exports like Durable Objects:src/worker.ts import handler from '@astrojs/cloudflare/entrypoints/server';import { DurableObject } from 'cloudflare:workers';export class MyDurableObject extends DurableObject<Env> {// ...}export default {async fetch(request, env, ctx) {await env.MY_QUEUE.send('log');return handler.fetch(request, env, ctx);},async queue(batch, _env) {let messages = JSON.stringify(batch.messages);console.log(`consumed from our queue: ${messages}`);},} satisfies ExportedHandler<Env>;
The manifest is now created internally by the adapter, so it does not need to be passed to your handler.
New: astro preview support
Section titled “New: astro preview support”Use astro preview to test your Cloudflare Workers application locally before deploying. The preview runs using Cloudflare’s workerd runtime, closely mirroring production behavior. Run astro build followed by astro preview to start the preview server.
Deprecated: Cloudflare Pages support
Section titled “Deprecated: Cloudflare Pages support”The Astro Cloudflare adapter now only supports deploying to Cloudflare Workers by default. If you are currently deploying to Cloudflare Pages, consider migrating to Workers for the best experience and feature support.
If you need to continue using Cloudflare Pages, see Using with Cloudflare Pages for the required manual configuration.