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

main
mdx 682 lines 20.4 KB
Raw
1 ---
2 title: Add a React SPA
3 description: Ship a React single-page app from the same Stack as your Worker — built with Vite and deployed to Cloudflare in one command.
4 sidebar:
5 label: React SPA
6 order: 4
7 ---
8
9 import { Code, Tabs, TabItem } from "@astrojs/starlight/components";
10 import PackageManagers from "../../../../components/PackageManagers.astro";
11
12 export const deps = `react react-dom`;
13 export const devDeps = `@types/react @types/react-dom @vitejs/plugin-react`;
14 export const typesDep = `@cloudflare/workers-types`;
15
16 This is the walkthrough for a plain React single-page app on
17 [`Cloudflare.Website.Vite`](/cloudflare/frontend/vite): build the
18 client assets, ship them to Cloudflare, and serve them through a
19 Worker so your frontend and backend share one URL surface and one
20 deploy. For the resource itself — what it does, its props, `memo`
21 semantics, and dev mode — see the
22 [Vite resource page](/cloudflare/frontend/vite).
23
24 Pick the path that fits where you're starting from:
25
26 1. [Set it up manually](#set-it-up-manually) — start from an
27 empty project; the bare minimum is an `index.html` and an
28 entry module.
29 2. [Use the `create-vite` template](#use-the-create-vite-template)
30 — start from Vite's official React + TS scaffold.
31 3. [Deploy an existing Vite project](#deploy-an-existing-vite-project)
32 — point Alchemy at a SPA you already have.
33
34 ## Set it up manually
35
36 The bare minimum is **an `index.html` with a script tag** — no
37 `package.json` `build` script, no `main` entry; Alchemy runs Vite
38 for you, merging its Cloudflare integration on top of your
39 `vite.config.ts`.
40
41 A minimal React SPA looks like:
42
43 ```
44 .
45 ├── index.html # entry HTML, references the client bundle
46 ├── vite.config.ts # your plugins — react() here
47 └── src/
48 └── main.tsx # client entry imported by index.html
49 ```
50
51 ### Install React
52
53 <PackageManagers add={deps} dev={devDeps} />
54
55 ### Create vite.config.ts
56
57 Register the React plugin — Alchemy runs Vite with your config and
58 its plugins intact:
59
60 ```typescript
61 // vite.config.ts
62 import { defineConfig } from "vite";
63 import react from "@vitejs/plugin-react";
64
65 export default defineConfig({
66 plugins: [react()],
67 });
68 ```
69
70 ### Create index.html
71
72 `index.html` just needs to load your entry module:
73
74 ```html
75 <!doctype html>
76 <html lang="en">
77 <head>
78 <meta charset="UTF-8" />
79 <title>My App</title>
80 </head>
81 <body>
82 <div id="root"></div>
83 <script type="module" src="/src/main.tsx"></script>
84 </body>
85 </html>
86 ```
87
88 :::caution[index.html must be at rootDir]
89 Vite resolves `index.html` relative to its project root. Alchemy's
90 `rootDir` defaults to `process.cwd()` — so place `index.html`
91 next to your `alchemy.run.ts`, or set `rootDir` to the folder
92 that contains it. See Vite's
93 [project structure docs](https://vite.dev/guide/#index-html-and-project-root).
94 :::
95
96 ### Create src/main.tsx
97
98 Mount a React component into the `#root` div:
99
100 ```tsx
101 // src/main.tsx
102 import React from "react";
103 import ReactDOM from "react-dom/client";
104
105 function App() {
106 return (
107 <main>
108 <h1>Hello from Alchemy + Vite</h1>
109 <p>Edit <code>src/main.tsx</code> and redeploy.</p>
110 </main>
111 );
112 }
113
114 ReactDOM.createRoot(document.getElementById("root")!).render(
115 <React.StrictMode>
116 <App />
117 </React.StrictMode>,
118 );
119 ```
120
121 ### Add it to the Stack
122
123 Yield `Cloudflare.Website.Vite("Website")` from your Stack:
124
125 ```diff lang="typescript"
126 // alchemy.run.ts
127 import * as Alchemy from "alchemy";
128 import * as Cloudflare from "@alchemy.run/cloudflare";
129 import * as Effect from "effect/Effect";
130 import Worker from "./src/worker.ts";
131
132 export default Alchemy.Stack(
133 "MyApp",
134 {
135 providers: Cloudflare.providers(),
136 state: Cloudflare.state(),
137 },
138 Effect.gen(function* () {
139 const worker = yield* Worker;
140 + const web = yield* Cloudflare.Website.Vite("Website");
141 return {
142 url: worker.url,
143 + webUrl: web.url,
144 };
145 }),
146 );
147 ```
148
149 ### Configure the deep-link fallback
150
151 If your SPA uses client-side routing (React Router, TanStack
152 Router), configure the not-found fallback explicitly so a deep
153 link like `/about` serves `index.html` instead of a 404 and your
154 router handles the path on the client:
155
156 ```diff lang="typescript"
157 // alchemy.run.ts
158 -const web = yield* Cloudflare.Website.Vite("Website");
159 +const web = yield* Cloudflare.Website.Vite("Website", {
160 + assets: {
161 + notFoundHandling: "single-page-application",
162 + },
163 +});
164 ```
165
166 `assets` accepts the standard Cloudflare Worker static-assets
167 config; `single-page-application` not-found handling serves
168 `index.html` for unmatched paths so the client router takes over.
169 A site that ships a real error page uses
170 `notFoundHandling: "404-page"` instead (Cloudflare serves the
171 built `404.html`).
172
173 ### Inject the Worker URL at build time
174
175 A pure SPA needs the backend's URL baked into the JS bundle at
176 build time — there's no server to resolve it on each request. Pass
177 `env` to `Cloudflare.Website.Vite` and any `VITE_`-prefixed entry is
178 inlined as `import.meta.env.<KEY>` during the Vite build, the same
179 as if you'd run `VITE_API_URL=https://… vite build`:
180
181 ```diff lang="typescript"
182 // alchemy.run.ts
183 const worker = yield* Worker;
184 const web = yield* Cloudflare.Website.Vite("Website", {
185 + env: {
186 + VITE_API_URL: worker.url.as<string>(),
187 + },
188 });
189 ```
190
191 Then read it from the SPA:
192
193 ```tsx
194 // src/main.tsx
195 const apiUrl = import.meta.env.VITE_API_URL;
196
197 await fetch(`${apiUrl}/api/hello`);
198 ```
199
200 Only `VITE_`-prefixed keys are inlined into the bundle, and
201 `Output` values like `worker.url.as<string>()` resolve at deploy
202 time before the build runs. For the full semantics — `Redacted`
203 unwrapping, what happens to non-prefixed keys, redeploys on
204 env-only changes — see the
205 [Vite resource's environment section](/cloudflare/frontend/vite#environment).
206
207 To inject the site's *own* URL — for canonical links, OG tags, or
208 OAuth redirect URIs — use `Cloudflare.Worker.URL`. A site can't
209 reference its own `url` Output, so Alchemy resolves the URL before
210 the build and inlines it the same way:
211
212 ```diff lang="typescript"
213 const web = yield* Cloudflare.Website.Vite("Website", {
214 env: {
215 VITE_API_URL: worker.url.as<string>(),
216 + VITE_PUBLIC_URL: Cloudflare.Worker.URL,
217 },
218 });
219 ```
220
221 ## Use the create-vite template
222
223 If you'd rather start from a real framework scaffold (React + TS
224 with HMR, ESLint, etc.), use Vite's official template:
225
226 <Tabs syncKey="pkgManager">
227 <TabItem label="pnpm" icon="pnpm">
228 <Code code={`pnpm create vite web --template react-ts\ncd web && pnpm install && cd ..`} lang="sh" />
229 </TabItem>
230 <TabItem label="bun" icon="bun">
231 <Code code={`bun create vite@latest web -- --template react-ts\ncd web && bun install && cd ..`} lang="sh" />
232 </TabItem>
233 <TabItem label="npm" icon="npm">
234 <Code code={`npm create vite@latest web -- --template react-ts\ncd web && npm install && cd ..`} lang="sh" />
235 </TabItem>
236 <TabItem label="yarn" icon="seti:yarn">
237 <Code code={`yarn create vite web --template react-ts\ncd web && yarn install && cd ..`} lang="sh" />
238 </TabItem>
239 </Tabs>
240
241 That drops a complete project into `./web/` with its own
242 `package.json`, `tsconfig.json`, and `vite.config.ts`.
243
244 ### Point Cloudflare.Website.Vite at the subfolder
245
246 Since the SPA isn't at the project root, set `rootDir`:
247
248 ```diff lang="typescript"
249 // alchemy.run.ts
250 Effect.gen(function* () {
251 const worker = yield* Worker;
252 + const web = yield* Cloudflare.Website.Vite("Website", {
253 + rootDir: "./web",
254 + });
255 return {
256 url: worker.url,
257 webUrl: web.url,
258 };
259 }),
260 ```
261
262 `rootDir` defaults to `process.cwd()`, so you only set it when
263 your `index.html` isn't next to `alchemy.run.ts`.
264
265 ## Deploy an existing Vite project
266
267 Already have a Vite SPA? Point `Cloudflare.Website.Vite` at it with
268 `rootDir` and you're done:
269
270 ```ts
271 // alchemy.run.ts
272 const web = yield* Cloudflare.Website.Vite("Website", {
273 rootDir: "./path/to/your/spa",
274 });
275 ```
276
277 Your existing `vite.config.ts`, plugins, aliases, and `tsconfig`
278 are all preserved — Alchemy merges its Cloudflare integration on
279 top of your config (the [Vite resource page](/cloudflare/frontend/vite)
280 covers how). One thing to check first:
281
282 :::caution[Remove @cloudflare/vite-plugin if present]
283 Alchemy ships its own Cloudflare integration and is **not
284 compatible** with `@cloudflare/vite-plugin` — remove it from your
285 `vite.config.ts`:
286
287 ```diff lang="typescript"
288 // vite.config.ts
289 import { defineConfig } from "vite";
290 import react from "@vitejs/plugin-react";
291 -import cloudflare from "@cloudflare/vite-plugin";
292
293 export default defineConfig({
294 - plugins: [react(), cloudflare()],
295 + plugins: [react()],
296 });
297 ```
298 :::
299
300 ## Deploy
301
302 ```sh
303 bun alchemy deploy
304 ```
305
306 Alchemy runs Vite on `rootDir`, uploads the assets, creates a
307 Worker that serves them, and prints the new `webUrl` stack output:
308
309 ```
310 {
311 url: "https://myapp-worker-dev-you.workers.dev",
312 webUrl: "https://myapp-web-dev-you.workers.dev",
313 }
314 ```
315
316 ## Verify
317
318 Hit it with `curl`:
319
320 ```sh
321 curl -s https://myapp-web-dev-you.workers.dev | head -5
322 # <!doctype html>
323 # <html lang="en">
324 # <head>
325 # <meta charset="UTF-8" />
326 # ...
327 ```
328
329 Or add an integration test alongside the existing ones:
330
331 ```diff lang="typescript"
332 // test/integ.test.ts
333 import * as Cloudflare from "@alchemy.run/cloudflare";
334 import * as Test from "@alchemy.run/test/Bun";
335 import { expect } from "bun:test";
336 import * as Effect from "effect/Effect";
337 import * as HttpClient from "effect/http/HttpClient";
338 import Stack from "../alchemy.run.ts";
339
340 const { test, beforeAll, deploy } = Test.make({
341 providers: Cloudflare.providers(),
342 state: Cloudflare.state(),
343 });
344
345 const stack = beforeAll(deploy(Stack));
346
347 +test(
348 + "Web SPA serves index.html",
349 + Effect.gen(function* () {
350 + const { webUrl } = yield* stack;
351 +
352 + const response = yield* HttpClient.get(webUrl);
353 + expect(response.status).toBe(200);
354 + expect(yield* response.text).toContain("<!doctype html>");
355 + }),
356 +);
357 ```
358
359 ## Local dev
360
361 ```sh
362 bun alchemy dev
363 ```
364
365 `alchemy dev` runs the whole Stack locally with hot reloading.
366 For a `Cloudflare.Website.Vite` worker that means Alchemy boots
367 Vite's dev server (HMR, instant module updates) behind Alchemy's
368 local proxy; each Worker gets its own local URL:
369
370 ```
371 {
372 url: "http://localhost:1337",
373 webUrl: "http://localhost:1338",
374 }
375 ```
376
377 Edit `src/main.tsx`, save, and the browser updates without a full
378 reload. Backend resources (R2 buckets, D1 databases, service
379 bindings) are the **real** cloud resources — only your application
380 code runs locally, so there's no emulation fidelity gap.
381
382 The build-time env injection works the same in dev — `VITE_`-prefixed
383 entries are inlined as `import.meta.env.<KEY>`, and `Output` values
384 like `worker.url.as<string>()` resolve before the dev server starts.
385
386 By default the dev server picks an available port. Set `dev.port`
387 only if you want the local URL to stay the same across runs:
388
389 ```diff lang="typescript"
390 // alchemy.run.ts
391 const web = yield* Cloudflare.Website.Vite("Website", {
392 + dev: { port: 3000 },
393 });
394 ```
395
396 See [Local Development](/environments/local-development) for the full
397 model — how Workers run in `workerd`, how to attach a debugger, and
398 how `dev` differs from `deploy`.
399
400 ## Use a different framework
401
402 This page is the plain React SPA path. Other frameworks have
403 their own landing pages, each flowing from the same
404 [`Cloudflare.Website.Vite` resource](/cloudflare/frontend/vite):
405
406 - [TanStack Start](/cloudflare/frontend/tanstack-start) — full-stack
407 React with server routes and runtime bindings
408 - [React Router](/cloudflare/frontend/react-router) — SPA or React
409 Server Components
410 - [Vue](/cloudflare/frontend/vue) — Vue 3 SPA
411 - [Foldkit](/cloudflare/frontend/foldkit) — client-only,
412 server-rendered, or prerendered Foldkit
413 - [SolidStart](/cloudflare/frontend/solidstart) — SSR Solid
414
415 For frameworks whose build isn't driven by Vite alone, deploy the
416 built output with
417 [`Cloudflare.Website.StaticSite`](/cloudflare/frontend/static-site).
418 The [Frontend overview](/cloudflare/frontend/frontends) lays out
419 which resource fits which framework.
420
421 ## Add a backend resource
422
423 Most SPAs need to talk to a real backing service — a bucket for
424 uploads, a database for state. Bindings give your Worker a typed
425 handle to those resources.
426
427 The walkthrough below uses a TanStack Start route handler because
428 a pure SPA only ships static assets — there's no server-side `env`
429 to call. The same `env` map and the same three call patterns work
430 in any Vite framework that exposes server routes (TanStack Start,
431 SolidStart, React Router).
432
433 Start with the simplest backend: an R2 bucket.
434
435 ```typescript
436 // src/backend.ts
437 import * as Cloudflare from "@alchemy.run/cloudflare";
438
439 export const Bucket = Cloudflare.R2.Bucket("Bucket");
440 ```
441
442 `Cloudflare.R2.Bucket("Bucket")` is a description, not a deploy.
443 Alchemy provisions the real bucket on the next run as soon as
444 something binds to it.
445
446 ## Bind the bucket to your worker
447
448 Add the bucket to the Vite worker's `bindings` map:
449
450 ```diff lang="typescript"
451 // alchemy.run.ts
452 +import { Bucket } from "./src/backend.ts";
453
454 const web = yield* Cloudflare.Website.Vite("Website", {
455 + env: {
456 + BUCKET: Bucket,
457 + },
458 });
459 ```
460
461 The key (`BUCKET`) is the field name on `env`; the value identifies
462 the resource. `env.BUCKET` is now typed as `Bucket` end to end.
463
464 ## Pull in Cloudflare's binding types
465
466 `InferEnv` maps each binding to a Cloudflare runtime type
467 (`Bucket`, `Service`, `Namespace`, …) — those types live in
468 `@cloudflare/workers-types`. Add it to your `tsconfig.json` so the
469 TypeScript checker can find them:
470
471 <PackageManagers dev={typesDep} />
472
473 ```diff lang="json"
474 // tsconfig.json
475 {
476 "compilerOptions": {
477 "types": [
478 "bun",
479 - "vite/client"
480 + "vite/client",
481 + "@cloudflare/workers-types"
482 ]
483 }
484 }
485 ```
486
487 Without this you'll see `Cannot find name 'Bucket'` (or `Service`,
488 etc.) the moment you reference `env.BUCKET` inside a route handler.
489
490 ## Option 1 — call the binding directly
491
492 Inside a server route, `env.BUCKET` is the standard Cloudflare R2
493 client. Use it as a regular `async`/`await` API:
494
495 ```typescript
496 // src/routes/api.hello.ts
497 import { createFileRoute } from "@tanstack/react-router";
498 import { env } from "../env.ts";
499
500 export const Route = createFileRoute("/api/hello")({
501 server: {
502 handlers: {
503 GET: async ({ request }) => {
504 const key = new URL(request.url).searchParams.get("key");
505 if (!key) return new Response("Missing 'key'", { status: 400 });
506
507 // option 1 — use the async binding directly
508 const object = await env.BUCKET.get(key);
509 if (!object) return new Response("Not found", { status: 404 });
510 return new Response(object.body);
511 },
512 },
513 },
514 });
515 ```
516
517 This is the most direct path — no extra workers, no extra code.
518 Reach for it when the route handler owns all the logic itself.
519
520 ## Add an Effect-native Worker
521
522 When the work is shared across routes, deserves typed errors, or
523 needs Effect-native primitives (retries, layers, structured
524 concurrency), factor it into its own Worker:
525
526 ```diff lang="typescript"
527 // src/backend.ts
528 import * as Cloudflare from "@alchemy.run/cloudflare";
529 +import * as Effect from "effect/Effect";
530 +import { HttpServerRequest } from "effect/http/HttpServerRequest";
531 +import * as HttpServerResponse from "effect/http/HttpServerResponse";
532
533 export const Bucket = Cloudflare.R2.Bucket("Bucket");
534 +
535 +export default class Backend extends Cloudflare.Worker<Backend>()(
536 + "Backend",
537 + { main: import.meta.url },
538 + Effect.gen(function* () {
539 + const bucket = yield* Cloudflare.R2.ReadWriteBucket(Bucket);
540 +
541 + return {
542 + hello: Effect.fn("Backend.hello")(function* (key: string) {
543 + const object = yield* bucket.get(key);
544 + if (object === null) return null;
545 + return yield* object.text();
546 + }),
547 + fetch: Effect.gen(function* () {
548 + const request = yield* HttpServerRequest;
549 + const key = new URL(request.url, "http://x").searchParams.get("key");
550 + if (!key) {
551 + return HttpServerResponse.text("Missing 'key'", { status: 400 });
552 + }
553 + const object = yield* bucket.get(key);
554 + if (object === null) {
555 + return HttpServerResponse.text("Not found", { status: 404 });
556 + }
557 + return HttpServerResponse.stream(object.body);
558 + }),
559 + };
560 + }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
561 +) {}
562 ```
563
564 `hello` is a typed RPC method — any worker bound to `Backend` can
565 call it across worker boundaries. `fetch` is the standard HTTP
566 handler. The R2 binding lives once on the Backend; the Vite worker
567 no longer needs to bind it directly unless it also wants to call
568 R2 itself.
569
570 ## Bind the Backend as a service
571
572 Add `Backend` next to (or instead of) `BUCKET` in the Vite worker's
573 `env`:
574
575 ```diff lang="typescript"
576 // alchemy.run.ts
577 -import { Bucket } from "./src/backend.ts";
578 +import Backend, { Bucket } from "./src/backend.ts";
579
580 const web = yield* Cloudflare.Website.Vite("Website", {
581 env: {
582 BUCKET: Bucket,
583 + BACKEND: Backend,
584 },
585 });
586 ```
587
588 `env.BACKEND` is a Cloudflare service binding, typed for the wire
589 shape Alchemy emits — Effect/Stream return values come back as
590 encoded envelopes (more on that in option 3).
591
592 ## Option 2 — call the worker's `fetch`
593
594 `env.BACKEND.fetch(input, init?)` is the standard Cloudflare
595 service-binding `fetch`. Use it like any other HTTP service:
596
597 ```diff lang="typescript"
598 // src/routes/api.hello.ts
599 GET: async ({ request }) => {
600 const key = new URL(request.url).searchParams.get("key");
601 if (!key) return new Response("Missing 'key'", { status: 400 });
602
603 - // option 1 — use the async binding directly
604 - const object = await env.BUCKET.get(key);
605 - if (!object) return new Response("Not found", { status: 404 });
606 - return new Response(object.body);
607 + // option 2 — call the worker's fetch handler
608 + return env.BACKEND.fetch(
609 + `https://backend/?key=${encodeURIComponent(key)}`,
610 + );
611 },
612 ```
613
614 The Backend already handles the R2 lookup behind its own `fetch`,
615 so the response flows straight through. Reach for this when the
616 backend logic is HTTP-shaped (REST endpoints, streaming responses)
617 and you don't want to duplicate it in the route handler.
618
619 ## Wrap the binding for typed RPC
620
621 Effect-native workers serialize their results as wire envelopes:
622 `Effect.fail` becomes an `RpcErrorEnvelope`, `Stream` becomes an
623 encoded `ReadableStream`. `toRpcAsync` is the consumer-side
624 wrapper that auto-decodes those envelopes into a clean `Promise<T>`
625 API:
626
627 ```diff lang="typescript"
628 // src/routes/api.hello.ts
629 import { createFileRoute } from "@tanstack/react-router";
630 +import * as Cloudflare from "@alchemy.run/cloudflare/Bridge";
631 +import type Backend from "../backend.ts";
632 import { env } from "../env.ts";
633
634 +const backend = Cloudflare.toRpcAsync<Backend>(env.BACKEND);
635 ```
636
637 Error envelopes are thrown so `await` rejects; stream envelopes
638 unwrap to their raw `ReadableStream<Uint8Array>` body.
639 `Service.fetch` and `Service.connect` pass through unchanged so the
640 returned proxy is still a usable `Service` binding.
641
642 ## Option 3 — call the worker's RPC method
643
644 Now `hello` is a normal typed `await`:
645
646 ```diff lang="typescript"
647 // src/routes/api.hello.ts
648 GET: async ({ request }) => {
649 const key = new URL(request.url).searchParams.get("key");
650 if (!key) return new Response("Missing 'key'", { status: 400 });
651
652 - // option 2 — call the worker's fetch handler
653 - return env.BACKEND.fetch(
654 - `https://backend/?key=${encodeURIComponent(key)}`,
655 - );
656 + // option 3 — call the worker's RPC method
657 + const value = await backend.hello(key);
658 + if (value === null) return new Response("Not found", { status: 404 });
659 + return new Response(value);
660 },
661 ```
662
663 RPC keeps you off the HTTP detour — the call is a typed function,
664 not a request, and the return value is the value itself (no
665 `.json()`, no status codes to plumb).
666
667 `toRpcAsync` is the async-consumer face of
668 [Schemaless RPC](/apis/schemaless) — the same typed methods `Backend`
669 exposes, decoded into `Promise`s instead of Effects.
670
671 :::tip[Calling RPC from another Effect-native Worker?]
672 Use [`Cloudflare.Workers.bindWorker(Backend)`](/providers/cloudflare/workers/worker)
673 instead of `toRpcAsync`. It returns the same shape with `Effect`
674 return values, preserving typed errors and decoded streams instead
675 of throwing them away.
676 :::
677
678 Your app now ships a Worker backend and a Vite frontend from the
679 same `alchemy.run.ts`, deploying together with one command. Next
680 you'll [run a Container](/cloudflare/compute/run-a-container) so each
681 Durable Object instance has its own long-lived process for
682 executing untrusted code or running binaries.