To deploy Astro to Cloudflare, use Cloudflare Workers with static assets: build to dist/, add a small wrangler.jsonc that points at that folder, and run npx wrangler deploy, or connect your repository so Cloudflare builds on every push. Add the @astrojs/cloudflare adapter only when some routes render on demand. Astroโs Cloudflare deploy guide states that Cloudflare recommends Workers for new projects.
getastrothemes.com runs on Cloudflare Workers with @astrojs/cloudflare, so some notes come from our own production setup. Our own build is on Astro 7.2.2, @astrojs/cloudflare 14.2.1 and Wrangler 4.123.0. On November 9, 2026 the current npm releases were Astro 7.4.7, @astrojs/cloudflare 14.4.6 and Wrangler 4.158.0, and we reread six pages against this guide that day: Astroโs Cloudflare adapter and deploy guides, and Cloudflareโs static-assets, redirects, headers and billing pages. Every other section links its own source.
Deploying to Vercel, Netlify or GitHub Pages instead? This guide covers Cloudflare only. Astroโs deploy guides have a page for each host.
Cloudflare Pages vs Workers for Astro: which should you use?
Pick Workers unless you have a specific reason not to. This is how the two compare on the features that matter for an Astro site, based on Cloudflareโs Pages-to-Workers compatibility matrix and the Astro Cloudflare adapter docs:
| Feature | Workers | Pages |
|---|---|---|
Static assets, _headers, _redirects | Yes | Yes |
| Git-connected builds | Yes (Workers Builds) | Yes |
| Preview URLs for branches | Yes | Yes, more configurable |
| Deploy hooks | Yes | Yes |
| Cron Triggers | Yes | No |
| Custom domain on a zone you host elsewhere | No | Yes |
| Custom branch aliases | Yes, on your domain | Yes |
| On-demand rendering with the Astro adapter | Supported | Removed in adapter v13 |
Two Pages advantages are real. If your clientโs DNS has to stay at another provider, Pages can serve a custom domain outside a Cloudflare zone and Workers cannot. And Pages branch deploy controls are still more flexible. If neither applies to you, Workers is the better long-term home.
If you are already on Pages with a fully static site and it works, there is no emergency. Cloudflareโs migration guide does not call Pages deprecated. Plan the move when you next touch the deployment setup. The exception is a site that renders on request: the Astro adapter dropped Pages support in v13, so upgrading Astro past version 5 means moving that site to Workers.
How do you deploy a static Astro site to Cloudflare Workers?
A fully static Astro site (the default output) needs no adapter. Wrangler uploads your dist/ folder as static assets, and no Worker code runs.
1. Install Wrangler in the project
npm install wrangler@latest --save-dev
Keep Wrangler as a project dependency rather than a global install. Workers Builds uses the version in your package.json, and some newer commands (such as wrangler preview) need a recent Wrangler 4 release.
2. Add a wrangler config
Create wrangler.jsonc in the project root:
{
"name": "my-astro-site",
"compatibility_date": "2026-10-26", // use the date you first deploy
"assets": {
"directory": "./dist",
"not_found_handling": "404-page",
},
}
not_found_handling: "404-page" tells Cloudflare to serve your built 404.html for missing paths. Without it, a custom src/pages/404.astro will not be used on Workers.
If you prefer TOML, wrangler.toml works the same way:
name = "my-astro-site"
compatibility_date = "2026-10-26"
[assets]
directory = "./dist"
not_found_handling = "404-page"
3. Preview the built site locally
npx astro build && npx wrangler dev
This serves dist/ the way Cloudflare will, which catches routing and 404 problems that astro dev hides.
4. Deploy from your machine
npx astro build && npx wrangler deploy
The first run opens a browser to log in to Cloudflare. When the upload finishes, Wrangler prints a workers.dev URL you can check.
Add a script so nobody forgets the build step:
{
"scripts": {
"deploy": "astro build && wrangler deploy"
}
}
Set up Git-connected builds with Workers Builds
Manual deploys are fine for a personal site. For client work you want every push to main to build and deploy on its own. On Workers, that is Workers Builds.
- Commit the wrangler config from the previous section.
- In the Cloudflare dashboard, go to Compute > Workers & Pages and choose Create application.
- Under Import a repository, pick your GitHub or GitLab account and the repo.
- Set the build command to
npx astro build(ornpm run build) and the deploy command tonpx wrangler deploy. - Select Save and Deploy.
Things that trip people up:
- The Worker name must match. The name in the dashboard has to match
namein your wrangler config. On Wrangler v3 and newer, Workers Builds setsWRANGLER_CI_OVERRIDE_NAMEand matches the connected Worker for you, so this mostly bites projects pinned to an old Wrangler (Workers Builds troubleshooting). - Monorepos need the Root directory build setting pointed at the Astro project.
- No wrangler config? Workers Builds can detect the framework and open a pull request that adds one. Read that PR before merging it.
On Pages the flow is similar: connect the repo, use npm run build as the build command and dist as the output directory. You can also upload a local build with npx wrangler pages deploy dist.
When do you need the @astrojs/cloudflare adapter?
Add the adapter when any route renders on request: API endpoints, auth, a dashboard, export const prerender = false pages, server islands, actions, or sessions. Marketing pages can stay prerendered alongside them.
npx astro add cloudflare
This installs @astrojs/cloudflare and adds adapter: cloudflare() to astro.config.mjs. Since adapter v13 the wrangler file is optional for simple projects: without one, Astro generates a default config. You need your own file once you add bindings, routes or a custom domain. The SSR version looks like this:
{
"main": "@astrojs/cloudflare/entrypoints/server",
"name": "my-astro-site",
"compatibility_date": "2026-10-26",
"compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"],
"assets": {
"binding": "ASSETS",
"directory": "./dist",
},
"observability": {
"enabled": true,
},
}
What changes compared to the static setup:
mainpoints at the adapterโs Worker entrypoint, which renders on-demand routes.- The
ASSETSbinding lets that Worker serve prerendered files. nodejs_compatturns on support for most Node APIs (node:buffer,node:crypto,node:pathand others) when imported with thenode:prefix.
Requests that match a file in dist/ are served as static assets. Everything else falls through to the Worker.
Three adapter details worth knowing before you build anything:
astro devruns in workerd. Since Astro 6 and adapter v13, bothastro devandastro previewuse Cloudflareโs real runtime, so runtime bugs show up locally.- Prerendering also runs in workerd by default. If a prerendered page reads files with
node:fsor uses a Node-only package at build time, setprerenderEnvironment: 'node'in the adapter options. Astro.locals.runtimeis gone. It was removed in adapter v13. Import bindings fromcloudflare:workersand useAstro.locals.cfContextforwaitUntil().
Our production config: getastrothemes.com
Our site mixes static marketing pages with SSR checkout, auth, and dashboard routes. A trimmed version of the setup, with IDs and internal values removed:
name = "my-astro-site"
main = "src/worker.ts"
compatibility_date = "2026-02-01"
# disable_nodejs_process_v2 is here for the [object Object] bug below, not by default
compatibility_flags = [
"nodejs_compat",
"global_fetch_strictly_public",
"disable_nodejs_process_v2",
]
[assets]
directory = "./dist"
binding = "ASSETS"
[env.production]
name = "my-astro-site-production"
[env.production.assets]
directory = "./dist"
binding = "ASSETS"
run_worker_first = ["/*", "!/_astro/*", "!/favicon*", "!/*.xml", "!/*.txt"]
Two choices here might help you:
- A custom
mainentrypoint.src/worker.tsimports the adapterโs handler from@astrojs/cloudflare/entrypoints/serverand runs a few redirect checks before passing the request on. Use this pattern when you need logic in front of Astro. The current adapter docs show the same idea withimport { handle } from "@astrojs/cloudflare/handler"inside a standard Workerfetchexport; use that form for new projects. run_worker_firstwith negative patterns. HTML documents go through the Worker so request-level logic runs on every page view. Hashed assets under/_astro/and feeds skip the Worker and stay on the free static path. Leave this out if you donโt need it, because every matched request is a billed Worker request.
In astro.config.mjs we use cloudflare({ imageService: "compile", sessionKVBindingName: "..." }). That pairs image optimization at build time with an existing KV namespace for sessions.
Environment variables and secrets
This is where most Astro-on-Cloudflare confusion comes from, because there are two separate moments: build time and request time.
| What | Where to set it | Available |
|---|---|---|
PUBLIC_* and other import.meta.env | Workers Builds > build variables, or your CI environment | At build, inlined into the output |
| Non-secret runtime vars | vars in the wrangler config | At request time, in server code |
| Runtime secrets | npx wrangler secret put KEY | At request time, never in config |
| Local secrets | .dev.vars in the project root (add to .gitignore) | astro dev and wrangler dev |
Runtime variables go in the wrangler config:
{
"vars": {
"APP_ENV": "production",
},
}
Read them, along with secrets and bindings, in server code:
---
import { env } from "cloudflare:workers";
const appEnv = env.APP_ENV;
---
A D1 database is one more binding. Create it with npx wrangler d1 create my-site-db, then add the ID it prints to the wrangler config:
{
"d1_databases": [
{
"binding": "DB",
"database_name": "my-site-db",
"database_id": "<id from wrangler d1 create>",
},
],
}
Query it from an on-demand page or endpoint through the same env import. Use bind() for values instead of building the SQL string:
---
export const prerender = false;
import { env } from "cloudflare:workers";
const { results } = await env.DB.prepare(
"SELECT title, slug FROM posts WHERE status = ?",
)
.bind("published")
.run();
---
The config keys and the prepare().bind().run() pattern match Cloudflareโs D1 getting started guide, checked November 9, 2026, which also notes that bind() is what prevents SQL injection. KV and R2 work the same way: declare the binding, then read it from env.
Variables and secrets also work with Astroโs typed astro:env/server module. Run npx wrangler types after changing the wrangler config or .dev.vars so env stays typed.
The common mistake: a prerendered page reads import.meta.env.PUBLIC_API_URL, the value is set only as a runtime variable in the dashboard, and the deployed page renders undefined. Build variables in Workers Builds are not visible at runtime, and runtime variables are not visible to the build. If a value is needed in both places, set it in both.
If you use wrangler environments like our env.production above, note that vars are not inherited from the top level. Repeat them in each environment block.
Since Astro 6 the environment is picked at build time, so build once per environment and prefix the build with CLOUDFLARE_ENV:
CLOUDFLARE_ENV=production npx astro build && npx wrangler deploy
Add a custom domain
The domainโs zone must be on Cloudflare. Then either:
- Dashboard: open the Worker, go to Settings > Domains & Routes, choose Add > Custom Domain, and enter the hostname.
- Config: add a route with
custom_domain: trueand redeploy:
{
"routes": [
{ "pattern": "example.com", "custom_domain": true },
{ "pattern": "www.example.com", "custom_domain": true },
],
}
Cloudflare creates the DNS record and certificate for you. The hostname cannot already have a CNAME record, so delete any old record pointing at a previous host first.
Set site in astro.config.mjs to the final domain too. Astro uses it for canonical URLs, the sitemap, and RSS, and a leftover workers.dev value is easy to miss.
Redirects and headers
Put _redirects and _headers files in public/. Astro copies them into dist/, and Cloudflare applies them to static assets.
public/_redirects:
/old-pricing /pricing/ 301
/blog/category/* /blog/ 301
public/_headers:
/*
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Limits from Cloudflareโs docs, checked November 9, 2026: up to 2,000 static redirects plus 100 dynamic ones with splats or placeholders, each declaration capped at 1,000 characters (_redirects), and up to 100 header rules at 2,000 characters a line (_headers).
The catch with SSR: neither file applies to responses your Worker generates. That includes on-demand routes and anything matched by run_worker_first. For those:
- Use Astroโs
redirectsoption inastro.config.mjsfor fixed redirects. - Return
Astro.redirect()or aResponsefrom the route. - Set headers on the response in the page, in middleware, or in a custom Worker entrypoint.
Preview deployments for branches
With Workers Builds, pushes to non-production branches run a preview command. The default is npx wrangler preview, which creates or updates a Preview for that branch with its own URL, roughly <preview-name>-<worker-name>.<subdomain>.workers.dev. You can also run npx wrangler preview locally on a branch.
Know these details before relying on previews:
- Previews do not inherit production settings. Define preview variables and bindings in a
previewsblock, and set preview secrets withnpx wrangler preview secret put:
{
"previews": {
"vars": {
"APP_ENV": "preview",
},
},
}
- Bindings may not be isolated. KV, D1, and R2 are only separate when the preview binds a separate resource. Point previews at staging data, or a test checkout can write to production storage.
- Previews are public by default. The
workers.devpreview URL sendsX-Robots-Tag: noindex. For previews on a custom domain, Cloudflare suggests protecting them with Cloudflare Access.
If you set the preview command to npx wrangler versions upload, you get Version URLs instead. These are uploaded versions of the production Worker with no branch-specific resources.
Caching: what Cloudflare does for you
- Static assets are free. Cloudflareโs billing page for static assets says requests to static assets are free and unlimited. Requests that invoke your Worker are billed, and that includes every path matched by
run_worker_first. - Default asset headers revalidate. We could not find a documented default
Cache-Controlfor assets in Cloudflareโs static-assets, routing, headers or billing pages, so we measured ours. On November 9, 2026,curl -I https://getastrothemes.com/robots.txtreturnedcache-control: public, max-age=0, must-revalidatewith anETag. Browsers re-check each such file but skip the download when nothing changed. - Hashed files can cache for a long time. Everything Astro emits in
/_astro/has a content hash in its name. With the adapter, Astro already adds long cache headers for these. On a static site without the adapter, add them yourself:
/_astro/*
Cache-Control: public, max-age=31536000, immutable
- SSR HTML is your responsibility. Set
Cache-Controlon responses from on-demand routes deliberately, and never cache pages that show user data. Check the real headers withcurl -I https://your-domain/path/rather than assuming.
Common errors and fixes
| Symptom | Likely cause and fix |
|---|---|
Build fails with Could not resolve "X" and โis built into nodeโ | A server-side import uses a Node API. Add nodejs_compat, import it as node:X, or replace the package if it does not support the node: syntax. |
| Prerendered page fails when reading files or using a Node-only library | Prerendering runs in workerd by default. Set prerenderEnvironment: 'node' in the adapter options. |
require is not defined or similar CommonJS errors in dev or build | workerd does not support CommonJS. Pre-bundle the dependency with Viteโs optimizeDeps.include for server environments, as shown in the adapter docs, or switch packages. |
| Images fail or Sharp errors in on-demand routes | Sharp does not run in workerd. Pick an adapter imageService: compile (optimize at build, passthrough at runtime), cloudflare-binding (the default, uses the Images binding), cloudflare (Image Resizing), custom or passthrough. For optimized prerendered images plus the binding at runtime, use the object form: imageService: { build: 'compile', runtime: 'cloudflare-binding' }. |
| Custom 404 page never shows | Add "not_found_handling": "404-page" under assets. |
| Workers Builds fails right away | The dashboard Worker name does not match name in the wrangler config. Wrangler v3+ overrides the name in Workers Builds, so upgrade Wrangler or rename the Worker. |
_redirects or _headers ignored on some URLs | Those URLs are served by the Worker. Handle them in Astro or the Worker entrypoint. |
| Console shows โHydration completed but contains mismatchesโ | Astroโs docs point to Cloudflareโs legacy Auto Minify setting. Turn it off if your zone still has it. |
| Minified stack traces you cannot read | Temporarily set vite: { build: { minify: false } } in astro.config.mjs. |
One more from our own deployment. With nodejs_compat and a compatibility date from late 2025 onward, our SSR pages rendered as the literal text [object Object]. It was reported in withastro/astro#15434, still closed as not planned on March 13, 2026 when we rechecked the issue on November 9, so there is no upstream fix to wait for. Adding the disable_nodejs_process_v2 compatibility flag fixed it for us. Test without the flag first, since your versions may not hit the bug.
Publish future-dated posts on a schedule
A static Astro site only changes when it rebuilds, so a post dated next Tuesday will not appear by itself. You need two parts: a date filter and a scheduled rebuild. This is the short version; our guide to scheduling posts in Astro on Cloudflare covers time zones, testing, and a Worker that only builds when a post is due.
1. Hide posts dated after the build
Astro does not hide future-dated entries for you. Filter them when you query the collection:
import { getCollection } from "astro:content";
const now = new Date();
const posts = await getCollection(
"blog",
({ data }) => !data.draft && data.date <= now,
);
If you mix prerendered and on-demand routes, prerendered pages see the build time while SSR routes see the request time. A post can then appear in a listing but 404 on its own page, or the other way round. We avoid this by freezing one timestamp at build with Viteโs define and comparing every route against it:
// astro.config.mjs
export default defineConfig({
vite: {
define: {
__BUILD_TIME__: JSON.stringify(new Date().toISOString()),
},
},
});
2. Create a deploy hook
Workers Builds now supports deploy hooks, which are unique URLs that start a build when they receive a POST. Open the Worker, go to Settings > Builds > Deploy Hooks, name the hook, pick the branch, and copy the URL. Pages has its own deploy hooks under the projectโs build settings.
The URL needs no auth header, so treat it like a password. If it leaks, delete the hook and create a new one.
3a. Trigger it from a Cloudflare Cron Trigger
A tiny separate Worker can call the hook on a schedule. Store the hook URL as a secret named DEPLOY_HOOK_URL:
// rebuild-worker/index.js
export default {
async scheduled(controller, env, ctx) {
await fetch(env.DEPLOY_HOOK_URL, { method: "POST" });
},
};
// rebuild-worker/wrangler.jsonc
{
"name": "my-astro-site-rebuild",
"main": "index.js",
"compatibility_date": "2026-10-26",
"triggers": { "crons": ["0 6 * * *"] },
}
Cron Triggers run on UTC. Pick an hour shortly after your usual publish time.
3b. Or trigger it from GitHub Actions
If your team already lives in GitHub, a scheduled workflow does the same job:
# .github/workflows/scheduled-rebuild.yml
name: Scheduled rebuild
on:
schedule:
- cron: "0 6 * * *"
workflow_dispatch:
jobs:
rebuild:
runs-on: ubuntu-latest
steps:
- name: Call Cloudflare deploy hook
run: curl -fsS -X POST "$DEPLOY_HOOK_URL"
env:
DEPLOY_HOOK_URL: ${{ secrets.CLOUDFLARE_DEPLOY_HOOK_URL }}
GitHubโs scheduled runs can start late at busy times, and GitHub disables schedules in public repos after 60 days without activity. The Cloudflare Cron Trigger avoids both, so it is the more dependable option for a client site nobody commits to.
A deployment checklist
-
siteinastro.config.mjsset to the production domain - Wrangler installed as a dev dependency, config committed
-
not_found_handlingset if you have a custom 404 page - Adapter added only if routes render on demand
- Build-time and runtime variables set in the right places, secrets via
wrangler secret put -
.dev.varsin.gitignore - Custom domain added and old DNS records removed
-
_redirectsfor old URLs, with SSR redirects handled in Astro - Preview bindings pointed at staging resources
- Scheduled rebuild set up if you publish future-dated content
-
curl -Icheck on a page, an/_astro/file, and a 404
Where to go from here
If you are deploying a static Astro site, the whole job is a wrangler config and one command. Most of the complexity in this guide only arrives once you add on-demand routes. Start static and add the adapter when a feature really needs a server.
If you donโt have a site to deploy yet, start from a theme. Veltro, Techbyte and Techlo build to static output, so the Workers setup above works for them without an adapter. Browse the premium Astro themes, try a free theme first, or use the All Access Pass if you build several client sites.
For the steps before deployment, see how to install and customize an Astro theme. For multilingual sites, read the Astro multilingual website guide.