Black Friday: 50% off Pro All Access until Nov 30
All articles
Guides 12 min read

How to Deploy an Astro Site to Cloudflare Workers

Deploy Astro to Cloudflare Workers: static and SSR setups, wrangler config, env vars, custom domains, previews, caching, common errors and scheduled rebuilds.

Published

Updated

On this page

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:

FeatureWorkersPages
Static assets, _headers, _redirectsYesYes
Git-connected buildsYes (Workers Builds)Yes
Preview URLs for branchesYesYes, more configurable
Deploy hooksYesYes
Cron TriggersYesNo
Custom domain on a zone you host elsewhereNoYes
Custom branch aliasesYes, on your domainYes
On-demand rendering with the Astro adapterSupportedRemoved 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.

  1. Commit the wrangler config from the previous section.
  2. In the Cloudflare dashboard, go to Compute > Workers & Pages and choose Create application.
  3. Under Import a repository, pick your GitHub or GitLab account and the repo.
  4. Set the build command to npx astro build (or npm run build) and the deploy command to npx wrangler deploy.
  5. Select Save and Deploy.

Things that trip people up:

  • The Worker name must match. The name in the dashboard has to match name in your wrangler config. On Wrangler v3 and newer, Workers Builds sets WRANGLER_CI_OVERRIDE_NAME and 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:

  • main points at the adapterโ€™s Worker entrypoint, which renders on-demand routes.
  • The ASSETS binding lets that Worker serve prerendered files.
  • nodejs_compat turns on support for most Node APIs (node:buffer, node:crypto, node:path and others) when imported with the node: 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 dev runs in workerd. Since Astro 6 and adapter v13, both astro dev and astro preview use 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:fs or uses a Node-only package at build time, set prerenderEnvironment: 'node' in the adapter options.
  • Astro.locals.runtime is gone. It was removed in adapter v13. Import bindings from cloudflare:workers and use Astro.locals.cfContext for waitUntil().

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 main entrypoint. src/worker.ts imports the adapterโ€™s handler from @astrojs/cloudflare/entrypoints/server and 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 with import { handle } from "@astrojs/cloudflare/handler" inside a standard Worker fetch export; use that form for new projects.
  • run_worker_first with 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.

WhatWhere to set itAvailable
PUBLIC_* and other import.meta.envWorkers Builds > build variables, or your CI environmentAt build, inlined into the output
Non-secret runtime varsvars in the wrangler configAt request time, in server code
Runtime secretsnpx wrangler secret put KEYAt 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: true and 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 redirects option in astro.config.mjs for fixed redirects.
  • Return Astro.redirect() or a Response from 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 previews block, and set preview secrets with npx 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.dev preview URL sends X-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-Control for 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.txt returned cache-control: public, max-age=0, must-revalidate with an ETag. 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-Control on responses from on-demand routes deliberately, and never cache pages that show user data. Check the real headers with curl -I https://your-domain/path/ rather than assuming.

Common errors and fixes

SymptomLikely 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 libraryPrerendering runs in workerd by default. Set prerenderEnvironment: 'node' in the adapter options.
require is not defined or similar CommonJS errors in dev or buildworkerd 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 routesSharp 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 showsAdd "not_found_handling": "404-page" under assets.
Workers Builds fails right awayThe 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 URLsThose 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 readTemporarily 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

  • site in astro.config.mjs set to the production domain
  • Wrangler installed as a dev dependency, config committed
  • not_found_handling set 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.vars in .gitignore
  • Custom domain added and old DNS records removed
  • _redirects for 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 -I check 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.

Frequently asked questions

Should I use Cloudflare Pages or Workers for a new Astro site?

Use Workers. Astro's deploy guide states that Cloudflare recommends Workers for new projects. Pages still runs existing sites, but it has no Cron Triggers, and the Astro adapter dropped Pages support in v13.

Do I need the @astrojs/cloudflare adapter for a static Astro site?

No. A fully static site only needs a wrangler config that points assets.directory at ./dist. Add the adapter when you have on-demand rendered routes, server islands, actions, or sessions.

Why does my PUBLIC_ environment variable work locally but not on Cloudflare?

Variables read through import.meta.env are inlined when Astro builds. In Workers Builds they must be set as build variables, not runtime variables. Runtime variables and secrets only reach server code at request time.

Is serving static assets on Workers free?

Cloudflare's docs say requests to static assets are free and unlimited. Requests that invoke your Worker script, including paths matched by run_worker_first, count as normal Worker requests.

How do I publish future-dated Astro posts automatically on Cloudflare?

Filter out posts dated after the build time, then rebuild on a schedule. Create a Workers Builds deploy hook and call it from a Worker Cron Trigger or a scheduled GitHub Actions workflow.

Can I use a custom domain that is not on Cloudflare DNS?

Not with Workers. Workers Custom Domains need the zone on Cloudflare. Pages supports custom domains outside Cloudflare zones, which is one reason some projects stay on Pages.

Share this article

Every premium theme.
Future releases included. $99.

Premium theme collection preview
Premium theme collection preview