The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 334 lines 10.6 KB
Raw
1 ---
2 title: Custom domains & routes
3 description: Serve Workers from your own domain — create or adopt a Zone, attach custom domains, route hostname patterns, manage DNS records, and control the workers.dev subdomain.
4 sidebar:
5 order: 0
6 ---
7
8 Every Worker gets a `workers.dev` URL by default, but production apps
9 live on their own domain. This guide covers the pieces involved: the
10 Zone that holds your domain, the `domain` prop that attaches hostnames
11 to a Worker, Routes for pattern-based dispatch, plain DNS records, and
12 the account's `workers.dev` subdomain.
13
14 All the snippets below run inside a Stack's `Effect.gen` body:
15
16 ```typescript
17 // alchemy.run.ts
18 import * as Alchemy from "alchemy";
19 import * as Cloudflare from "@alchemy.run/cloudflare";
20 import * as Effect from "effect/Effect";
21
22 export default Alchemy.Stack(
23 "MyApp",
24 { providers: Cloudflare.providers(), state: Cloudflare.state() },
25 Effect.gen(function* () {
26 // resources go here
27 return {};
28 }),
29 );
30 ```
31
32 ## Create a Zone
33
34 A Zone is a domain managed by Cloudflare. Declaring one gives you the
35 zone's identifiers and the name servers to point your registrar at:
36
37 ```typescript
38 const zone = yield* Cloudflare.Zone.Zone("MyZone", {
39 name: "example.com",
40 });
41 // zone.zoneId, zone.nameServers, zone.accountId, zone.status, ...
42 ```
43
44 Zones default to **retain** on removal — destroying the stack does NOT
45 delete the zone in Cloudflare. Opt in to actual deletion by wrapping
46 the resource in `destroy()` from `alchemy/RemovalPolicy`:
47
48 ```typescript
49 import { destroy } from "alchemy/RemovalPolicy";
50
51 const zone = yield* Cloudflare.Zone.Zone("MyZone", {
52 name: "example.com",
53 }).pipe(destroy());
54 ```
55
56 ## Adopt an existing Zone
57
58 Most domains already exist in Cloudflare before Alchemy enters the
59 picture. A zone carries no ownership markers, so the engine refuses to
60 take over a pre-existing zone unless you opt in with `adopt(true)`:
61
62 ```typescript
63 import { adopt } from "alchemy/AdoptPolicy";
64
65 const zone = yield* Cloudflare.Zone.Zone("MyZone", {
66 name: "example.com",
67 }).pipe(adopt(true));
68 ```
69
70 Without `adopt(true)`, deploying against an existing zone fails with a
71 typed `OwnedBySomeoneElse` error instead of silently clobbering it.
72 Once adopted, the zone behaves like any other managed resource — and it
73 still retains on destroy unless you add `destroy()`.
74
75 ## Attach a custom domain to a Worker
76
77 Pass `domain` — Cloudflare provisions the DNS record and certificate;
78 the zone is inferred from the hostname and must already exist in the
79 account:
80
81 ```typescript
82 const worker = yield* Cloudflare.Worker("Api", {
83 main: "./src/api.ts",
84 domain: "api.example.com",
85 });
86 // worker.url === "https://api.example.com"
87 ```
88
89 `aliases` also serve the Worker; `redirects` answer with a 301 (path
90 and query preserved) to the canonical name, before the Worker runs —
91 ideal for domain migrations:
92
93 ```typescript
94 const worker = yield* Cloudflare.Worker("Api", {
95 main: "./src/api.ts",
96 domain: {
97 name: "api.example.com",
98 aliases: ["api-v2.example.com"],
99 redirects: ["api.old-example.com"], // 301 → https://api.example.com
100 },
101 workersDev: false,
102 });
103 // worker.url === "https://api.example.com"
104 // worker.urls === ["https://api.example.com", "https://api-v2.example.com"]
105 // worker.domain === { name: "api.example.com",
106 // aliases: ["api-v2.example.com"],
107 // redirects: ["api.old-example.com"] }
108 ```
109
110 The canonical domain leads `worker.urls` (ahead of `workers.dev`), and
111 redirect hostnames never appear there — they serve no content. Their
112 redirect rules live in the zone's `http_request_dynamic_redirect`
113 phase, which runs before Workers.
114
115 Set `previews: true` so [Worker Previews](/cloudflare/compute/previews)
116 of this Worker are served at `<preview-name>.api.example.com`. That is
117 a parent setting — enable it on the production Worker, not on the
118 Preview Worker. Use a dedicated hostname (`previews.example.com`) if
119 production already has subdomains, so the wildcard does not collide.
120
121 ## Serve a hostname whose DNS is elsewhere
122
123 A native custom domain needs the hostname in a Cloudflare zone of the
124 account. When the hostname's DNS lives in Route 53 or Hetzner DNS, pass
125 that host as `domain.dns`. The Worker then serves the hostname through
126 [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/start/advanced-settings/worker-as-origin/)
127 on a Cloudflare zone you own:
128
129 ```typescript
130 const worker = yield* Cloudflare.Worker("Api", {
131 main: "./src/api.ts",
132 domain: {
133 name: "app.example.com",
134 zoneId: saasZone.zoneId, // a Cloudflare zone with Cloudflare for SaaS enabled
135 cnameTarget: fallback.origin, // the zone's FallbackOrigin hostname
136 dns: AWS.Route53.Adapter(),
137 },
138 });
139 ```
140
141 Alchemy creates a custom hostname on the SaaS zone, publishes its
142 ownership and certificate `TXT` records and a `CNAME` to `cnameTarget` in
143 Route 53, and routes `app.example.com/*` on the SaaS zone to the Worker.
144 Declare the zone's `Cloudflare.CustomHostname.FallbackOrigin` once; several
145 Workers can share it. `redirects` and `previews` need a native custom
146 domain. See [DNS Adapters](/infrastructure-as-code/dns-adapters) for the
147 full setup.
148
149 ## Route a hostname pattern to a Worker
150
151 Routes are the classic alternative: a zone-level mapping from a URL
152 pattern to a Worker script. Unlike the `domain` prop, a route can match
153 paths (`example.com/api/*`), so different Workers can serve different
154 parts of one hostname:
155
156 ```typescript
157 const worker = yield* Cloudflare.Worker("Api", {
158 main: "./src/api.ts",
159 });
160
161 yield* Cloudflare.Workers.WorkerRoute("ApiRoute", {
162 zoneId: zone.zoneId,
163 pattern: "api.example.com/*",
164 script: worker.workerName,
165 });
166 ```
167
168 A route only fires on hostnames that resolve through Cloudflare's
169 proxy, so pair it with a proxied DNS record. When the Worker is the
170 only origin, an `AAAA 100::` placeholder is the conventional choice:
171
172 ```typescript
173 yield* Cloudflare.DNS.Record("ApiPlaceholder", {
174 zoneId: zone.zoneId,
175 name: "api.example.com",
176 type: "AAAA",
177 content: "100::",
178 proxied: true,
179 });
180 ```
181
182 Cloudflare enforces one route per pattern per zone, and routes carry no
183 ownership markers — so if the route already exists, Alchemy reports it
184 as unowned and refuses to take it over unless you opt in with
185 `adopt(true)` (the same policy as zones):
186
187 ```typescript
188 import { adopt } from "alchemy/AdoptPolicy";
189
190 yield* Cloudflare.Workers.WorkerRoute("ApiRoute", {
191 zoneId: zone.zoneId,
192 pattern: "api.example.com/*",
193 script: worker.workerName,
194 }).pipe(adopt(true));
195 ```
196
197 Both `pattern` and `script` are mutable — changing either updates the
198 same physical route in place. Changing `zoneId` triggers a replacement.
199
200 ## Split one hostname across Workers
201
202 Routes win over custom domains, so one Worker can own a hostname while
203 others claim paths under it:
204
205 ```typescript
206 yield* Cloudflare.Worker("Home", {
207 main: "./src/home.ts",
208 domain: "api.example.com",
209 });
210
211 yield* Cloudflare.Worker("Orders", {
212 main: "./src/orders.ts",
213 routes: [{ pattern: "api.example.com/orders*" }],
214 });
215 ```
216
217 `alchemy dev` applies the same routing locally. See
218 [Federated APIs](/cloudflare/networking/federated-apis) for the full
219 pattern.
220
221 ## DNS records for non-Worker targets
222
223 Not everything on your zone is a Worker. `Cloudflare.DNS.Record`
224 manages individual records — here a plain A record pointing at an
225 external server:
226
227 ```typescript
228 yield* Cloudflare.DNS.Record("ApiA", {
229 zoneId: zone.zoneId,
230 name: "api.example.com",
231 type: "A",
232 content: "203.0.113.42",
233 ttl: 300,
234 });
235 ```
236
237 Proxied records (orange-clouded) route through Cloudflare's edge —
238 `proxied: true` is only valid for `A`, `AAAA`, and `CNAME` records, and
239 requires the automatic TTL. A common shape is a proxied CNAME at a
240 Cloudflare Tunnel:
241
242 ```typescript
243 yield* Cloudflare.DNS.Record("AdminCname", {
244 zoneId: zone.zoneId,
245 name: "cluster-admin.example.com",
246 type: "CNAME",
247 content: `${tunnel.tunnelId}.cfargotunnel.com`,
248 proxied: true,
249 });
250 ```
251
252 DNS records get the same adoption safety as routes: if a record with
253 the same `(name, type)` already exists in the zone, Alchemy reports it
254 as unowned and requires `adopt(true)` to take it over. This protects
255 hand-edited records — especially apex `A`/`AAAA` and email
256 DKIM/SPF records the dashboard often manages — from being clobbered.
257
258 ## Disable Workers on a path
259
260 A route with no `script` opts matching requests out of Workers
261 entirely. Use it to punch a hole in a broader wildcard route — for
262 example, letting `/assets/*` bypass the Worker and hit the origin
263 directly:
264
265 ```typescript
266 yield* Cloudflare.Workers.WorkerRoute("AssetsBypass", {
267 zoneId: zone.zoneId,
268 pattern: "example.com/assets/*",
269 });
270 ```
271
272 ## Control the workers.dev subdomain
273
274 Per Worker, the `workersDev` prop toggles the `workers.dev` URLs (it
275 defaults to `true`). Once a custom domain serves production traffic,
276 you may want to switch them off — the custom domain then becomes
277 `worker.url`:
278
279 ```typescript
280 const worker = yield* Cloudflare.Worker("Api", {
281 main: "./src/api.ts",
282 domain: "api.example.com",
283 workersDev: false,
284 });
285 // worker.url === "https://api.example.com"
286 ```
287
288 The object form controls the stable URL and per-version preview URLs
289 independently. With the stable URL off and previews on, each deploy's
290 preview URL (`https://<version-prefix>-<name>.<subdomain>.workers.dev`)
291 becomes `worker.url`:
292
293 ```typescript
294 const worker = yield* Cloudflare.Worker("Api", {
295 main: "./src/api.ts",
296 workersDev: { enabled: false, previewsEnabled: true },
297 });
298 ```
299
300 Account-wide, the `<subdomain>` in
301 `https://<script>.<subdomain>.workers.dev` is a singleton you can pin
302 with the `Subdomain` resource:
303
304 ```typescript
305 const sub = yield* Cloudflare.Workers.Subdomain("Subdomain", {
306 subdomain: "my-team",
307 });
308 // Workers are now served from https://<script>.my-team.workers.dev
309 ```
310
311 Subdomain names are globally unique across all Cloudflare accounts;
312 claiming a taken name fails with a typed `SubdomainAlreadyExists`
313 error. Destroy is capture-and-restore: the subdomain is renamed back to
314 whatever the account had before Alchemy first managed it.
315
316 :::caution
317 Renaming the subdomain immediately changes the URL of **every**
318 deployed Worker on the account that relies on `workers.dev`. Only
319 manage this resource on accounts where that is acceptable.
320 :::
321
322 ## Where next
323
324 - [Domains & DNS](/cloudflare/networking/domains) — the full domain-management
325 surface: zone settings, DNSSEC, certificates, and more.
326 - [Workers](/cloudflare/compute/workers) — the Worker resource itself and its
327 binding system.
328
329 Reference:
330
331 - [Zone API reference](/providers/cloudflare/zone/zone)
332 - [WorkerRoute API reference](/providers/cloudflare/workers/workerroute)
333 - [Record API reference](/providers/cloudflare/dns/record)
334 - [Subdomain API reference](/providers/cloudflare/workers/subdomain)