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

main
mdx 244 lines 7.39 KB
Raw
1 ---
2 title: Federated APIs
3 description: Serve one API at one URL from many Workers — each path handled by its own least-privilege Worker, routed by Cloudflare's zone routes with no gateway Worker, and emulated locally by alchemy dev.
4 sidebar:
5 order: 10
6 ---
7
8 Serve one API from several Workers at a single URL. Each Worker handles
9 its own paths and binds only what those paths need. Cloudflare routes
10 each request straight to the right Worker, so there is no gateway
11 Worker in the request path.
12
13 ```
14 api.example.com/products* → Products reads the catalog
15 api.example.com/orders* → Orders reads the catalog, writes orders
16 api.example.com/admin/* → Admin writes the catalog
17 api.example.com/* → Home binds nothing
18 ```
19
20 The full code is in the
21 [federated API example](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-federated-api).
22
23 ## Define the API once
24
25 Declare one `HttpApi` and give each group a path prefix. The prefix
26 becomes the route each Worker claims:
27
28 ```typescript
29 // src/Api.ts
30 import * as HttpApi from "effect/http-api/HttpApi";
31 import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint";
32 import * as HttpApiGroup from "effect/http-api/HttpApiGroup";
33 import * as Schema from "effect/Schema";
34
35 export class ProductsGroup extends HttpApiGroup.make("products")
36 .add(HttpApiEndpoint.get("list", "/", { success: Schema.Array(Product) }))
37 .add(HttpApiEndpoint.get("get", "/:id", { params: Id, success: Product }))
38 .prefix("/products") {}
39
40 export class OrdersGroup extends HttpApiGroup.make("orders")
41 .add(HttpApiEndpoint.post("create", "/", { payload: NewOrder, success: Order }))
42 .prefix("/orders") {}
43
44 // What clients see at the one URL.
45 export class StoreApi extends HttpApi.make("StoreApi")
46 .add(ProductsGroup)
47 .add(OrdersGroup) {}
48
49 // What each Worker serves.
50 export class ProductsApi extends HttpApi.make("ProductsApi").add(ProductsGroup) {}
51 export class OrdersApi extends HttpApi.make("OrdersApi").add(OrdersGroup) {}
52 ```
53
54 ## Serve one group per Worker
55
56 Claim the group's prefix with `routes`, and bind only what its
57 handlers use. `Products` only reads the catalog:
58
59 ```typescript
60 // src/Products.ts
61 import * as Cloudflare from "@alchemy.run/cloudflare";
62 import * as Http from "alchemy/Http";
63 import * as Effect from "effect/Effect";
64 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
65 import * as HttpRouter from "effect/http/HttpRouter";
66 import * as Layer from "effect/Layer";
67 import { ProductsApi } from "./Api.ts";
68 import { Catalog } from "./Store.ts";
69
70 export default class Products extends Cloudflare.Worker<Products>()(
71 "Products",
72 {
73 main: import.meta.url,
74 routes: [{ pattern: "api.example.com/products*" }],
75 },
76 Effect.gen(function* () {
77 const catalog = yield* Cloudflare.KV.ReadNamespace(Catalog);
78
79 const handlers = HttpApiBuilder.group(ProductsApi, "products", (h) =>
80 h
81 .handle("list", () => listProducts(catalog))
82 .handle("get", ({ params }) => getProduct(catalog, params.id)),
83 );
84
85 return {
86 fetch: yield* HttpRouter.toHttpEffect(
87 HttpApiBuilder.layer(ProductsApi).pipe(
88 Layer.provide(handlers),
89 Layer.provide(Http.Platform),
90 ),
91 ),
92 };
93 }).pipe(Effect.provide(Cloudflare.KV.ReadNamespaceBinding)),
94 ) {}
95 ```
96
97 `Orders` follows the same shape with `routes: [{ pattern: "api.example.com/orders*" }]`
98 and binds `ReadNamespace(Catalog)` plus `ReadWriteNamespace(OrderBook)`.
99 A bug in `Products` can never write to the catalog or touch orders.
100
101 ## Own the hostname
102
103 Give one Worker the hostname as its `domain`. It gets the DNS record
104 and certificate, and answers every path no route claims:
105
106 ```typescript
107 // src/Home.ts
108 import * as Cloudflare from "@alchemy.run/cloudflare";
109 import * as Effect from "effect/Effect";
110 import * as HttpServerResponse from "effect/http/HttpServerResponse";
111
112 export default class Home extends Cloudflare.Worker<Home>()(
113 "Home",
114 {
115 main: import.meta.url,
116 domain: "api.example.com",
117 },
118 Effect.succeed({
119 fetch: HttpServerResponse.json({ endpoints: ["/products", "/orders"] }),
120 }),
121 ) {}
122 ```
123
124 ## Deploy the Workers together
125
126 Add every Worker to the Stack and return the domain Worker's URL:
127
128 ```typescript
129 // alchemy.run.ts
130 import * as Alchemy from "alchemy";
131 import * as Cloudflare from "@alchemy.run/cloudflare";
132 import * as Effect from "effect/Effect";
133 import Home from "./src/Home.ts";
134 import Orders from "./src/Orders.ts";
135 import Products from "./src/Products.ts";
136
137 export default Alchemy.Stack(
138 "StoreApi",
139 { providers: Cloudflare.providers(), state: Cloudflare.state() },
140 Effect.gen(function* () {
141 const home = yield* Home;
142 yield* Products;
143 yield* Orders;
144 return { url: home.url };
145 }),
146 );
147 ```
148
149 `url` is `https://api.example.com`. Every request to it goes straight
150 to the Worker that owns its path.
151
152 ## How requests are matched
153
154 Routes take precedence over the custom domain. When several patterns
155 match, the most specific one wins:
156
157 | Request | Worker | Why |
158 | ---------------- | ---------- | ------------------------------------ |
159 | `/products` | `Products` | `/products*` matches |
160 | `/orders/7` | `Orders` | `/orders*` matches |
161 | `/about` | `Home` | no route matches |
162
163 A trailing `*` matches any suffix, so `/orders/*` does not match
164 `/orders` itself — use `/orders*` to claim both.
165
166 Opt a path out of a route with a route that has no `script`. Matching
167 requests fall through to the domain Worker:
168
169 ```typescript
170 yield* Cloudflare.Workers.WorkerRoute("ProductsHealth", {
171 zoneId: zone.zoneId,
172 pattern: "api.example.com/products/health",
173 });
174 ```
175
176 ## Call it from a client
177
178 Use `StoreApi` against the one URL. The client doesn't know the API is
179 split across Workers:
180
181 ```typescript
182 const client = yield* HttpApiClient.make(StoreApi, { baseUrl: url });
183
184 const product = yield* client.products.get({ params: { id: "widget" } });
185 const order = yield* client.orders.create({
186 payload: { productId: product.id, quantity: 3 },
187 });
188 ```
189
190 ## Run it locally
191
192 `alchemy dev` applies the same routes locally:
193
194 ```sh
195 alchemy dev
196 ```
197
198 The `url` output is now a local URL, and requests to it reach the
199 local `Products`, `Orders`, and `Home` Workers by the same rules as
200 `api.example.com`:
201
202 ```sh
203 curl $URL/products # runs the local Products Worker
204 curl $URL/about # runs the local Home Worker
205 ```
206
207 Each routed Worker sees the original request URL, just as it does when
208 deployed.
209
210 ## Without a custom domain
211
212 Use only `routes` when no Worker should own the whole hostname. Add a
213 proxied placeholder record so the hostname resolves through Cloudflare:
214
215 ```typescript
216 yield* Cloudflare.DNS.Record("ApiPlaceholder", {
217 zoneId: zone.zoneId,
218 name: "api.example.com",
219 type: "AAAA",
220 content: "100::",
221 proxied: true,
222 });
223 ```
224
225 Read the hostname's URL from any route. It's `https://api.example.com`
226 when deployed and a local URL under `alchemy dev`:
227
228 ```typescript
229 const products = yield* Products;
230 return { url: products.routes[0].url };
231 ```
232
233 Paths no route claims return a 404 locally.
234
235 ## Where next
236
237 - [Custom domains & routes](/cloudflare/networking/custom-domains) — domains,
238 routes, and DNS records in detail.
239 - [Workers](/cloudflare/compute/workers) — bindings and the Worker runtime.
240
241 Reference:
242
243 - [Worker API reference](/providers/cloudflare/workers/worker)
244 - [WorkerRoute API reference](/providers/cloudflare/workers/workerroute)