# Deploy to Cloudflare

> Deploy EmDash to Cloudflare Workers with D1 and R2.

Source: https://emdashcmseverything.com/official-docs/deployment/cloudflare/

This guide deploys an EmDash site to Cloudflare Workers with D1 for its database and R2 for media. Start with an EmDash Cloudflare template or apply the same configuration to an existing Astro site.

## Prerequisites

- A Cloudflare account
- The project dependencies installed
- Wrangler authenticated with Cloudflare (`pnpm wrangler login`)

## Configure bindings

The Cloudflare templates include the complete Worker entry point, named D1 and R2 bindings, and the Durable Object binding for co-editing. On the first deploy, Wrangler creates the D1 database and R2 bucket if their configured names do not already exist. Keep the names in `wrangler.jsonc`; Wrangler reconnects later deploys to the same resources.

The template uses the following bindings:

```jsonc title="wrangler.jsonc"
{
	"$schema": "node_modules/wrangler/config-schema.json",
	"name": "my-emdash-site",
	"main": "./src/worker.ts",
	"compatibility_date": "2026-02-24",
	"compatibility_flags": ["nodejs_compat"],

	"d1_databases": [
		{
			"binding": "DB",
			"database_name": "my-emdash-site",
		},
	],

	"r2_buckets": [
		{
			"binding": "MEDIA",
			"bucket_name": "my-emdash-media",
		},
	],
	"durable_objects": {
		"bindings": [{ "name": "EMDASH_ROOMS", "class_name": "EmDashRoom" }],
	},
	"exports": {
		"EmDashRoom": { "type": "durable-object", "storage": "sqlite" },
	},
	"worker_loaders": [{ "binding": "LOADER" }],
	"triggers": { "crons": ["* * * * *"] },
}
```

The `DB`, `MEDIA`, and `LOADER` names must match the EmDash adapters. `EMDASH_ROOMS` binds the `EmDashRoom` Durable Object class, which runs [co-editing](#co-editing) rooms, and EmDash finds it by that binding name. The Cron Trigger runs scheduled publishing, plugin tasks, backups, and maintenance. See [Plugin sandbox](https://emdashcmseverything.com/official-docs/deployment/plugin-sandbox/#cloudflare-workers) if the site uses sandboxed plugins.

## Configure EmDash

The following Astro configuration uses the D1 and R2 bindings.

```js title="astro.config.mjs"
import { defineConfig } from "astro/config";
import cloudflare from "@astrojs/cloudflare";
import react from "@astrojs/react";
import emdash from "emdash/astro";
import { d1, r2, sandbox } from "@emdash-cms/cloudflare";

export default defineConfig({
	output: "server",
	adapter: cloudflare(),
	integrations: [
		react(), // Required — the admin UI is a React app
		emdash({
			database: d1({ binding: "DB" }),
			storage: r2({ binding: "MEDIA" }),
			sandboxRunner: sandbox(),
		}),
	],
});
```

If the site does not use marketplace, registry, or `sandboxed` plugins, omit `sandboxRunner` and the `LOADER` binding.

## Add the Worker entry point

The Worker entry point connects Astro to the Cron Trigger, forwards co-editing connections to their rooms, and exports the plugin bridge and the room classes:

```ts title="src/worker.ts"
import handler, {
	createScheduledHandler,
	EmDashRoom,
	EmDashRoomSite,
	PluginBridge,
} from "@emdash-cms/cloudflare/worker";

export { EmDashRoom, EmDashRoomSite, PluginBridge };

export default {
	...handler,
	scheduled: createScheduledHandler(),
} satisfies ExportedHandler;
```

The spread `handler` includes a `fetch` that sends room connections to their Durable Object before Astro runs. A Worker with its own `fetch` must [call `handleRoomUpgrade` first](#a-custom-fetch-handler).

The `PluginBridge` export is harmless when no sandboxed plugin is installed. Keep it if the same project may enable plugins later.

To run general maintenance on a schedule other than every minute, pass the same Cron expression to `createScheduledHandler({ generalCron: "..." })` and to `triggers.crons`. If they differ, the handler logs and ignores the unexpected trigger.

## Build and deploy

Build and deploy the site once to let Wrangler provision the named D1 database and R2 bucket. Wrangler uses the local login created by `pnpm wrangler login`.

```bash
pnpm build
pnpm wrangler deploy
```

With the default `auto` migration mode, EmDash applies pending core migrations when the deployed Worker receives its first request. The Worker leaves [large content migrations](https://emdashcmseverything.com/official-docs/deployment/core-migrations/#apply-large-content-migrations-from-the-cli) to `emdash migrate` and answers with 503 until they are applied. Use [Manage core database migrations](https://emdashcmseverything.com/official-docs/deployment/core-migrations/) when a deployment pipeline must apply migrations before new code receives traffic or when you need to inspect, check, or recover a migration.

Until the setup wizard has been completed, EmDash also applies the schema and structure of a seed file once, on the first request. Sample content from the seed is applied only when an administrator chooses it in the setup wizard. The seed is read at build time from `.emdash/seed.json`, the path in `package.json#emdash.seed`, or `seed/seed.json` — whichever is found first — and inlined into the bundle. If none is present, a built-in default seed is used. Subsequent deploys against an existing database leave its content alone.

To change the schema or content model of a site that is already deployed, see [Evolving a Deployed Site](https://emdashcmseverything.com/official-docs/deployment/schema-evolution/).

## Scheduled publishing

On Cloudflare, EmDash publishes scheduled entries only from the Worker's `scheduled` handler, which Cloudflare calls on the schedule of a [Cron Trigger](https://developers.cloudflare.com/workers/configuration/cron-triggers/). The deployed Worker needs both of the following:

- A Cron Trigger in the `triggers.crons` list of `wrangler.jsonc`, as shown in [Configure bindings](#configure-bindings).
- The `scheduled` handler from `@emdash-cms/cloudflare/worker`, exported from the Worker entry point that `main` points to, as shown in [Add the Worker entry point](#add-the-worker-entry-point).

If either is missing, scheduled entries do not go live. In local development with `astro dev`, EmDash publishes scheduled entries on a timer, so a schedule that works locally does not confirm the deployed configuration.

When the Cron Trigger runs every minute (`* * * * *`, as in the starter templates), an entry scheduled about a minute or more ahead goes live at its scheduled time. Each run waits for entries scheduled up to 70 seconds after it starts and publishes each one at its time, so a trigger that starts late does not delay them. Waiting uses no CPU time, but a run that is waiting stays open for up to about a minute, so consecutive runs can overlap in Workers logs. An entry scheduled less than a minute ahead goes live on the next run. A Worker entry point that calls `runScheduledTasks()` from `emdash/middleware` instead of using `createScheduledHandler()` publishes only entries that are already due, unless it passes `publishUpcomingWithinMs` with the number of milliseconds to wait.

Run `emdash doctor` from the project root to check the Cron Trigger and the `scheduled` handler in the local project files:

```bash
pnpm emdash doctor
```

When `emdash doctor` finds both, the output includes a passing `scheduler wiring` check. A failed scheduler check describes the problem and prints the fix. The check recognizes the Worker entry point shown on this page and the one-line re-export it prints as a fix, so an entry point written another way can fail the check even when it works.

If no scheduler check appears, `emdash doctor` found no Wrangler configuration in the current directory, or it found neither the Cron Trigger nor the `scheduled` handler. On a D1 project, the `database` check fails because it looks for a local SQLite file (`./data.db` by default). That failure does not affect the scheduler checks.

Deploy after adding or changing the Cron Trigger or the `scheduled` handler. Cloudflare can take up to 15 minutes to start running a new or changed Cron Trigger. Once the trigger starts running, EmDash publishes entries whose scheduled time has already passed.

To watch the trigger, run `pnpm wrangler tail`. Each run prints a line such as `"* * * * *" @ 9/29/2026, 10:01:00 AM - Ok`. `Ok` means the run ended without an uncaught error. EmDash catches and logs publishing errors, so `Ok` does not confirm that entries were published. A run that publishes entries also logs a message such as `[scheduled] Published 1 scheduled item(s)`, and errors from the run appear in the same output.

After deployment, the admin dashboard shows **Scheduled publishing needs attention** when a scheduled entry is past its scheduled time and no scheduler run has completed in the last five minutes. If the Cron Trigger runs less often than every five minutes, the notice can also appear between runs until the next run publishes the entry.

## Co-editing

[Co-editing](https://emdashcmseverything.com/official-docs/guides/working-with-content/#edit-with-other-people) is off by default. Set [`coEditing: true`](https://emdashcmseverything.com/official-docs/reference/configuration/#coediting) to turn it on. On Cloudflare, each entry's room is an `EmDashRoom` Durable Object, which keeps the room's state in its own SQLite storage. Rooms need the following, which the Cloudflare templates include:

- The `EMDASH_ROOMS` binding and the `exports` entry for `EmDashRoom`, as shown in [Configure bindings](#configure-bindings).
- `EmDashRoom` and `EmDashRoomSite` exported from the Worker entry point, as shown in [Add the Worker entry point](#add-the-worker-entry-point). Rooms load and save entries through `EmDashRoomSite`, a named entrypoint that isn't reachable from the internet.
- A `fetch` handler that forwards room connections. The default export of `@emdash-cms/cloudflare/worker` has one.

Without the `EMDASH_ROOMS` binding, the editor uses [single-editor mode](https://emdashcmseverything.com/official-docs/guides/working-with-content/#single-editor-mode), with edit locks. That includes Worker Previews and named environments that don't list the binding. If the Worker doesn't forward room connections, they never open, and each browser session switches to single-editor mode after its first three connections fail.

Under `astro dev`, rooms run in a local Durable Object.

### Workers that use `migrations`

The `exports` field can't be combined with the `migrations` array. If `wrangler.jsonc` already has a `migrations` array, declare `EmDashRoom` there instead, and add the binding beside any other Durable Object bindings:

```jsonc title="wrangler.jsonc"
{
	"durable_objects": {
		"bindings": [{ "name": "EMDASH_ROOMS", "class_name": "EmDashRoom" }],
	},
	"migrations": [
		// Your existing migrations come first
		{ "tag": "emdash-rooms", "new_sqlite_classes": ["EmDashRoom"] },
	],
}
```

### A custom `fetch` handler

A Worker entry point with its own `fetch` must call `handleRoomUpgrade` before anything else. It returns the room's response for a room connection, and `null` for any other request:

```ts title="src/worker.ts"
import handler, {
	createScheduledHandler,
	EmDashRoom,
	EmDashRoomSite,
	handleRoomUpgrade,
	PluginBridge,
} from "@emdash-cms/cloudflare/worker";

export { EmDashRoom, EmDashRoomSite, PluginBridge };

export default {
	...handler,
	fetch(request, env, ctx) {
		const upgrade = handleRoomUpgrade(request, env);
		if (upgrade) return upgrade;
		// Your own routing
		return handler.fetch(request, env, ctx);
	},
	scheduled: createScheduledHandler(),
} satisfies ExportedHandler;
```

### Turn co-editing off

Remove `coEditing: true` from the `emdash()` options, and leave the binding, the `exports` entry and the room exports in place. The Worker then leaves the room engine out of its upload. A room that still holds unsaved edits keeps them in its storage until co-editing is on again, and then saves them as a recovery revision.

## Place the Worker near D1

Cloudflare runs a Worker near the visitor by default. EmDash server-rendered requests make several D1 round trips, so use [Targeted Placement](https://developers.cloudflare.com/workers/configuration/smart-placement/) to run the Worker near the D1 primary and make those requests faster.

Wrangler accepts `placement.mode: "targeted"` with exactly one selector: `region`, `host`, or `hostname`. Select the value that targets the D1 primary location, and add the resulting `placement` object to `wrangler.jsonc`. Do not enable D1 read replicas with Targeted Placement. Without replicas, every query uses the nearby primary, including with `session: "auto"` and `coalesce: true`.

## Object cache

To reduce read load on D1, cache content and configuration query results in Cloudflare KV. Reads are served from KV instead of querying the database on every request:

```js title="astro.config.mjs"
import { d1, r2, kvCache } from "@emdash-cms/cloudflare";

emdash({
	database: d1({ binding: "DB" }),
	storage: r2({ binding: "MEDIA" }),
	objectCache: kvCache({ binding: "CACHE" }),
}),
```

See [Object Cache](https://emdashcmseverything.com/official-docs/deployment/object-cache/) for KV setup, options, and invalidation behavior.

## Workers Cache

Cloudflare's [Workers Cache](https://developers.cloudflare.com/workers/cache/) puts an edge cache **in front of** your Worker: matching requests are served without running your Worker at all.

### Enable it

Use Astro's Cloudflare cache provider so route rules and `Astro.cache` set cache headers and the provider can invalidate entries when content changes.

```js title="astro.config.mjs"
import { cacheCloudflare } from "@astrojs/cloudflare/cache";

export default defineConfig({
	adapter: cloudflare(),
	cache: {
		provider: cacheCloudflare(),
	},
	routeRules: {
		"/": { maxAge: 300, swr: 86400, tags: ["posts", "pages"] },
		// Other public routes can use different cache lifetimes.
	},
});
```

The `@astrojs/cloudflare` adapter detects `cacheCloudflare()` and enables Workers Cache in the generated deployment configuration.

EmDash invalidates cached entries automatically when content changes (see [Route Caching](https://emdashcmseverything.com/official-docs/deployment/route-caching/) for the tag convention). You only need to purge yourself for custom tags, for example a manual "clear everything" switch, using the platform's [purge API](https://developers.cloudflare.com/workers/cache/purge/) from your Worker. It needs no Cloudflare REST credentials.

Public pages control their own caching through `routeRules` and `Astro.cache`. Keep route rules to your public routes: a rest parameter at the site root, such as `/[...slug]`, also matches the admin and API routes under `/_emdash/`.

Two things to know before enabling it:

1. **A response with any cache hint is cacheable, even without a route rule.** The adapter marks responses that no route rule or `Astro.cache.set()` call made cacheable as `no-store`. A hint with tags but no `maxAge`, such as the site settings and menu hints a layout sets on every page, produces `Cloudflare-CDN-Cache-Control: public` without a lifetime, so Workers Cache falls back to its [default cache lifetimes](https://developers.cloudflare.com/workers/cache/configuration/#cache-control-semantics) (2 hours for a `200` response). Give every public route a rule, and keep session-dependent routes free of cache hints.
2. **Cached pages are shared with logged-in editors.** The cache runs before your Worker, so it cannot bypass based on request cookies. With the default server-rendered toolbar, a logged-in editor may receive the cached anonymous variant of a public page, without the visual editing toolbar, until the entry expires. Set [`toolbar: "client"`](https://emdashcmseverything.com/official-docs/reference/configuration/#toolbar) to keep the toolbar reliable on cached pages. Pages rendered for a signed-in user are never stored in the route cache.

For a deeper guide covering route rules, cache tags, EmDash's built-in invalidation on publish, and the responses that must stay out of the cache, see [Route Caching](https://emdashcmseverything.com/official-docs/deployment/route-caching/).

Workers Caching is separate from the **object cache** (`objectCache: kvCache({ binding: "CACHE" })`), which caches database query results in KV under the Worker.

## Custom domains

The first deployment receives a `workers.dev` URL. The custom domain must already be an active domain managed by Cloudflare in the same account as the Worker. After the Worker responds successfully at its `workers.dev` URL, add the production domain as a Wrangler route:

```jsonc title="wrangler.jsonc"
{
	"routes": [{ "pattern": "www.example.com", "custom_domain": true }],
}
```

Deploy again and verify both addresses. Keeping the `workers.dev` address available while testing DNS helps distinguish a routing problem from an application problem. To make the new domain the address in sitemaps and search metadata, and in emails and plugins when `siteUrl`, `EMDASH_SITE_URL`, or `SITE_URL` is not set, use **Change domain** in **Settings > General**; see [Move to a New Domain](https://emdashcmseverything.com/official-docs/guides/change-domain/).

Without `siteUrl`, `EMDASH_SITE_URL`, or `SITE_URL`, setup records the address it runs on as the site's origin, and passkeys created during setup only work on that address. Run setup on the production domain, or set `EMDASH_SITE_URL` to it before setup. Setting `EMDASH_SITE_URL` to another domain after setup moves sign-in to that domain, and passkeys created on the old address stop working there.

## Public R2 access

By default, media is served through EmDash's authenticated media route. If the bucket has a public custom domain, set that origin as `publicUrl` so generated media URLs use it:

```js title="astro.config.mjs"
storage: r2({
	binding: "MEDIA",
	publicUrl: "https://media.example.com",
}),
```

Public bucket access applies to every reachable object, not only media. Automatic JSON backups use the `backups/` prefix in the same storage backend, so do not expose that prefix through the public domain. [Choose media storage](https://emdashcmseverything.com/official-docs/deployment/storage/#public-access) explains the safe boundary.

## Image transformation

EmDash resizes and re-encodes R2 media inside the Worker, through Cloudflare's `IMAGES` binding. The `Image` component from `emdash/ui` and images in rich text both render through the image endpoint EmDash installs under the Cloudflare adapter. For media on the internal `/_emdash/api/media/file/…` route, that endpoint reads the source bytes straight from the R2 binding, without an HTTP fetch. Those transforms keep working behind Cloudflare Access and with `global_fetch_strictly_public`. Media served from a bucket URL — see [Public R2 Access](#public-r2-access) — takes the adapter's own transform endpoint instead, which fetches the file over HTTP before transforming it.

You do not have to declare the binding. `@astrojs/cloudflare` adds it to the Worker config it generates during `astro build`, the same way it adds `cache` for Workers Caching. It does so whenever the runtime image service is `cloudflare-binding`: `imageService` unset, the string itself, or `{ runtime: "cloudflare-binding" }`. Every other value — `"passthrough"`, `"compile"`, `"cloudflare"`, `"custom"` — leaves the binding out. Listing it in your own `wrangler.jsonc` keeps the intent obvious:

```jsonc title="wrangler.jsonc"
{
	"images": {
		"binding": "IMAGES",
	},
}
```

To see what a deploy actually gets, read the generated config rather than `wrangler.jsonc`. A build writes `.wrangler/deploy/config.json`, which points `wrangler deploy` at the merged file (`dist/server/wrangler.json` by default). Look for an `images` entry there.

> **Caution**
>
> What a missing binding looks like depends on the media URL. On the internal route the endpoint
> serves the original file unchanged: pages still render and nothing is logged, but every image is
> the full-size original rather than a variant scaled to the space it occupies. From a bucket URL
> the request fails with a 500 instead, because the adapter's transform endpoint calls the binding
> without a fallback. `imageService: "passthrough"` is the deliberate way out — EmDash then leaves
> the adapter's passthrough endpoint in place rather than wrapping it.

Cloudflare bills these transforms as [Images transformations](https://developers.cloudflare.com/images/pricing/#images-transformed). Each unique combination of source image and parameters is billed once per calendar month, and repeat requests within that month are free. If a site has 500 source images and requests one thumbnail size and one hero size for every image, those two parameter sets count as 1,000 transformed images for that month. The Images Free plan covers 5,000 unique transformations per month. Past that limit, cached transformations are still served, but new ones return a `9422` error and the image request fails.

## Cloudflare Access authentication

Cloudflare Access can replace passkey authentication with the identity provider attached to an Access application. The audience value is a secret runtime setting; keep it out of `astro.config.mjs` by naming its environment variable:

```js title="astro.config.mjs"
import { access } from "@emdash-cms/cloudflare";

emdash({
	auth: access({
		teamDomain: "myteam.cloudflareaccess.com",
		audienceEnvVar: "CF_ACCESS_AUDIENCE",
		roleMapping: {
			Admins: 50,
			Editors: 40,
		},
	}),
}),
```

Set `CF_ACCESS_AUDIENCE` with `pnpm wrangler secret put CF_ACCESS_AUDIENCE`. The [authentication guide](https://emdashcmseverything.com/official-docs/guides/authentication/#cloudflare-access) explains user provisioning, default roles, and role synchronization.

## Email

Production Workers have no default email delivery service. Magic-link sign-in returns **Email is not configured** until an email provider is active.

The Cloudflare email plugin uses a `send_email` binding. First [onboard and verify the sender domain](https://developers.cloudflare.com/email-routing/email-workers/send-email-workers/) with Cloudflare Email Sending. Cloudflare rejects messages whose From address is not an accepted sender.

Add the binding and register the provider:

```jsonc title="wrangler.jsonc"
{
	"send_email": [{ "name": "EMAIL" }],
}
```

```js title="astro.config.mjs"
import { cloudflareEmail } from "@emdash-cms/cloudflare/plugins";

emdash({
	plugins: [
		cloudflareEmail({
			from: { email: "cms@mails.example.com", name: "My Site CMS" },
			replyTo: "hello@example.com",
		}),
	],
}),
```

The plugin is active from its first deployment. **Settings → Email** shows the selected provider and can send a test email. Sending fails until the sender is accepted and the binding exists.

The plugin uses the binding named `EMAIL` unless its `binding` option names another one. If it is the only active email provider, EmDash selects it automatically. If more than one provider is active, choose the Cloudflare provider under **Settings → Email**. The optional `replyTo` address receives replies without changing the accepted From address. A plugin can set `replyTo` on an individual message, which overrides this option for that message.

### Built-in SMTP transport

If you already have SMTP credentials, you can use the [SMTP transport built into EmDash](https://emdashcmseverything.com/official-docs/guides/email/#production-built-in-smtp-transport) instead of Cloudflare Email Sending. It connects through `node:net` and `node:tls`, so the Worker needs the `nodejs_compat` compatibility flag. Set the `EMAIL_SMTP_*` values with `wrangler secret put`, or configure SMTP under **Settings → Email**. EmDash reads both the SMTP variables and `EMDASH_ENCRYPTION_KEY` through `process.env`, which needs a compatibility date on or after `2025-04-01` or the `nodejs_compat_populate_process_env` flag.

> **Caution**
>
> Cloudflare blocks outbound port 25, so the transport refuses it. Use port 465 (implicit TLS) or 587 (STARTTLS). Other ports use STARTTLS unless you set the security mode to `tls`.

## Cloudflare AI Search

To add Cloudflare AI Search to the site, install the [AI Search plugin](https://emdashcmseverything.com/official-docs/plugins/ai-search/).

## Worker secrets

Store secret values with `pnpm wrangler secret put <NAME>`. Do not put them in `wrangler.jsonc` or read them from build-time `import.meta.env` values.

`EMDASH_ENCRYPTION_KEY` encrypts plugin settings declared as secrets. Set it before saving a plugin secret, and preserve it separately from D1 backups. During rotation, provide the new key first and retain older keys after commas until every plugin secret has been saved again. [Secrets and key management](https://emdashcmseverything.com/official-docs/deployment/secrets/#the-encryption-key) describes rotation and recovery.

The plugin bridge reads this Worker secret binding directly. The generated admin settings route reads it through `process.env`. With `nodejs_compat`, Cloudflare populates `process.env` by default for compatibility dates on or after `2025-04-01`. Projects pinned to an earlier date must also add `nodejs_compat_populate_process_env` before saving encrypted settings.

EmDash reads its secrets from `process.env` at runtime. Worker code reads bindings from `env`, imported from `cloudflare:workers`. Never read secrets through `import.meta.env`: Vite replaces those values at build time and can write them into the server bundle.

The preview HMAC secret and commenter-IP salt are generated and stored in the database unless you provide runtime overrides. [Secrets and key management](https://emdashcmseverything.com/official-docs/deployment/secrets/) lists the exact variables, storage locations, and rotation effects.

## Preview deployments

A preview can run as a [Worker Preview](https://developers.cloudflare.com/workers/previews/), which gives each branch its own URL on the production Worker, or as a separate Worker in a named Wrangler environment. Either way, the preview needs a database and bucket separate from production. Never point a preview binding at a production database or bucket.

### Worker Previews

Worker Previews require Wrangler 4.135.0 or later in the project's dependencies. Projects created from an older EmDash template may pin an earlier version; upgrade it with `pnpm add -D wrangler@latest`. Previews do not inherit bindings or `vars` from the top-level configuration; list every binding the preview uses in a `previews` block.

The Astro Cloudflare adapter adds a `SESSION` KV binding. `wrangler deploy` provisions it automatically, but `wrangler preview` rejects it without a namespace ID. Create the preview resources, including a KV namespace for sessions:

```bash
pnpm wrangler d1 create my-emdash-site-preview
pnpm wrangler r2 bucket create my-emdash-media-preview
pnpm wrangler kv namespace create my-emdash-site-preview-session
```

Add the resource identifiers that Wrangler prints to `wrangler.jsonc`:

```jsonc title="wrangler.jsonc"
{
	"previews": {
		"d1_databases": [
			{
				"binding": "DB",
				"database_name": "my-emdash-site-preview",
				"database_id": "00000000-0000-0000-0000-000000000000",
			},
		],
		"r2_buckets": [
			{
				"binding": "MEDIA",
				"bucket_name": "my-emdash-media-preview",
			},
		],
		"kv_namespaces": [{ "binding": "SESSION", "id": "00000000000000000000000000000000" }],
		"worker_loaders": [{ "binding": "LOADER" }],
	},
}
```

Repeat `send_email`, AI Search, `vars`, and other bindings when the preview uses those features.

The setup wizard and passkeys need the site URL of the preview. Without `siteUrl` or `EMDASH_SITE_URL`, setup fails with `SITE_URL_REQUIRED`. Pass the preview URL, `https://<preview-name>-<worker-name>.<subdomain>.workers.dev`, on every preview deployment:

```bash
pnpm build
pnpm wrangler preview --name my-branch \
  --var EMDASH_SITE_URL:https://my-branch-my-emdash-site.example.workers.dev
```

Use the same preview name in `--name` and in the URL. A `siteUrl` in `astro.config.mjs` overrides `EMDASH_SITE_URL` and is built into every preview, so passkeys on the preview are bound to the production domain and neither setup nor sign-in works there. Set the production URL with `EMDASH_SITE_URL` in the top-level `vars` instead.

If the Worker sets `workers_dev` to `false`, previews have no URL until you set `"preview_urls": true` at the top level of `wrangler.jsonc` and run `wrangler deploy` once. `wrangler preview` does not apply this setting. `wrangler deploy` publishes the code in your current checkout to production, not only the setting, so commit the change and deploy from a clean checkout of your production branch. Then return to your branch and run `wrangler preview` again.

Set a secret for one preview with `pnpm wrangler preview secret put <NAME> --name my-branch`. `pnpm wrangler preview base-config secret put <NAME>` sets a secret for previews created afterwards; existing previews keep their secrets.

Keep these differences from production in mind:

- **Previews share the resources in the `previews` block.** `wrangler preview` reads the `previews` block of the branch it deploys, so every branch that keeps the base branch's configuration uses the same database. The first request to a preview applies pending core migrations, so a branch that upgrades EmDash also migrates the database the other previews use. To [isolate a branch](https://developers.cloudflare.com/workers/previews/resources/#d1-migrations), create another D1 database and change `database_name` and `database_id` in that branch's `previews` block before deploying it.
- **An empty preview database shows the setup wizard.** Preview URLs are public, and the first visitor to finish the wizard becomes the administrator. Finish setup immediately after creating the preview, or protect preview URLs with [Cloudflare Access](https://developers.cloudflare.com/workers/configuration/cloudflare-access/).
- **Cron Triggers do not run.** Scheduled posts are not published, and plugin cron tasks and scheduled backups do not run on a preview.
- **Passkeys work only on the hostname that registered them.** Production passkeys do not work on a preview, and the administrator created on the first preview can sign in with a passkey only on that preview URL. On another preview that shares the database, sign in with a magic link, which needs an email provider and its binding in the `previews` block, and add a passkey there. Alternatively, isolate the branch with its own database as described above and run setup on it.

### Named environments

Named Wrangler environments do not inherit bindings. Create separate preview resources and write them to the `preview` environment before building:

```bash
pnpm wrangler d1 create my-emdash-site-preview \
  --binding DB --env preview --update-config
pnpm wrangler r2 bucket create my-emdash-media-preview \
  --binding MEDIA --env preview --update-config
```

The preview environment must repeat every binding the preview Worker uses. The core D1, R2, and sandbox bindings have this shape after Wrangler writes the resource identifiers:

```jsonc title="wrangler.jsonc"
{
	"env": {
		"preview": {
			"d1_databases": [
				{
					"binding": "DB",
					"database_name": "my-emdash-site-preview",
					"database_id": "00000000-0000-0000-0000-000000000000",
				},
			],
			"r2_buckets": [
				{
					"binding": "MEDIA",
					"bucket_name": "my-emdash-media-preview",
				},
			],
			"worker_loaders": [{ "binding": "LOADER" }],
		},
	},
}
```

Use the preview UUID written by Wrangler. Repeat optional KV, AI Search, email, and other bindings when the preview uses those features. Add preview-only secrets with `pnpm wrangler secret put <NAME> --env preview`.

Build and deploy the preview environment. Its first request applies pending core migrations through the default `auto` mode.

```bash
pnpm build
pnpm wrangler deploy --env preview
```

Verify the preview URL, admin sign-in, media upload, and any optional binding before sharing it.

## Verify the deployment

After deployment, request one public page, sign in to `/_emdash/admin`, upload and retrieve a test media file, and confirm the scheduled handler appears in `pnpm wrangler tail`. If co-editing is on, open one entry in two browser windows and type in one; the text must appear in the other.

A site created through the setup wizard starts in staging, hidden from search engines. When it's ready to be found, [go live](https://emdashcmseverything.com/official-docs/guides/seo/#hide-a-site-until-it-goes-live).

## Troubleshooting

### "D1 binding not found"

Verify the binding name in `wrangler.jsonc` matches your database configuration:

```js
// Must match: d1({ binding: "DB" })
"binding": "DB"
```

### "R2 binding not found"

Check that the R2 bucket is correctly bound:

```js
// Must match: r2({ binding: "MEDIA" })
"binding": "MEDIA"
```

### "[co-editing] The Worker doesn't export EmDashRoomSite"

Rooms load and save entries through `EmDashRoomSite`. Export it from the Worker entry point, as shown in [Add the Worker entry point](#add-the-worker-entry-point), and deploy again.

### Migration errors

If you see schema errors, tail the Worker logs (`wrangler tail`) and reproduce the error to capture the underlying message — then file an issue with that output.
