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

main
mdx 249 lines 7.57 KB
Raw
1 ---
2 title: React Router
3 description: Deploy React Router v8 — including React Server Components — to Cloudflare with Cloudflare.Website.Vite and viteEnvironments.
4 sidebar:
5 order: 6
6 ---
7
8 import PackageManagers from "../../../../components/PackageManagers.astro";
9
10 export const deps = `react react-dom react-router`;
11 export const devDeps = `vite @vitejs/plugin-react @vitejs/plugin-rsc`;
12
13 [React Router](https://reactrouter.com) v8 builds through Vite, so
14 [`Cloudflare.Website.Vite`](/cloudflare/frontend/vite) deploys it — one
15 resource, no Wrangler config, no manual entrypoint. In React Server
16 Components mode the build emits **multiple server environments** (`rsc`
17 and `ssr`) instead of the single `ssr` environment most SSR frameworks
18 produce, and `viteEnvironments` is the prop that tells Alchemy how those
19 environments assemble into one Worker. The configuration on this page is
20 a supported, live-tested shape: Alchemy's test suite deploys it to real
21 Cloudflare and asserts that server-rendered HTML and client routes both
22 serve.
23
24 ## Project layout
25
26 React Router's RSC mode is wired directly on `@vitejs/plugin-rsc`, so
27 the per-environment entry modules live in your project:
28
29 ```
30 .
31 ├── alchemy.run.ts # the Stack
32 ├── vite.config.ts
33 ├── app/ # root.tsx, routes.ts, routes/
34 └── react-router-vite/ # entry.browser.tsx, entry.ssr.tsx,
35 # entry.worker.tsx, worker-ssr.tsx
36 ```
37
38 `app/` holds ordinary React Router routes; `react-router-vite/` holds
39 one entry module per Vite environment — the browser bundle, the SSR
40 renderer, and the Worker handler.
41
42 ## Install the dependencies
43
44 React Server Components need React Router 8+ and the RSC Vite
45 plugin:
46
47 <PackageManagers add={deps} dev={devDeps} />
48
49 `@vitejs/plugin-rsc` is what splits the build into `client`, `ssr`, and
50 `rsc` environments; `@vitejs/plugin-react` handles the usual JSX/HMR
51 transform.
52
53 ## Configure the RSC plugin
54
55 Point `rsc()` at one entry per environment:
56
57 ```typescript
58 // vite.config.ts
59 import react from "@vitejs/plugin-react";
60 import rsc from "@vitejs/plugin-rsc";
61 import { defineConfig } from "vite";
62
63 export default defineConfig({
64 plugins: [
65 react(),
66 rsc({
67 serverHandler: false,
68 entries: {
69 client: "./react-router-vite/entry.browser.tsx",
70 ssr: "./react-router-vite/entry.ssr.tsx",
71 rsc: "./react-router-vite/entry.worker.tsx",
72 },
73 }),
74 ],
75 optimizeDeps: {
76 include: ["react-router", "react-router/internal/react-server-client"],
77 },
78 });
79 ```
80
81 `client` is the browser bundle, `ssr` renders HTML, and `rsc` is the
82 Worker entry — a module that default-exports the `{ fetch }` handler
83 Cloudflare invokes, which is also why `serverHandler` is off: the Worker
84 serves requests itself. Alchemy injects its Cloudflare Vite plugin on
85 top of this config at build and dev time, so there is nothing
86 Cloudflare-specific to add here.
87
88 ## Declare the environment inputs
89
90 Give each server environment its own build input:
91
92 ```diff lang="typescript"
93 // vite.config.ts
94 export default defineConfig({
95 plugins: [react(), rsc({ ... })],
96 + environments: {
97 + // The Worker is the RSC environment.
98 + rsc: {
99 + build: {
100 + rollupOptions: {
101 + input: { "entry.worker": "./react-router-vite/entry.worker.tsx" },
102 + },
103 + },
104 + },
105 + // A second ssr input the Worker loads on demand.
106 + ssr: {
107 + build: {
108 + rollupOptions: {
109 + input: { "worker-ssr": "./react-router-vite/worker-ssr.tsx" },
110 + },
111 + },
112 + },
113 + },
114 });
115 ```
116
117 The `rsc` input is the Worker entry, and the extra `ssr` input
118 (`worker-ssr`) is a chunk the Worker loads across environments at
119 runtime via `import.meta.viteRsc.loadModule("ssr", "worker-ssr")` — the
120 pattern for Worker code that needs a non-`react-server` module such as
121 `react-dom/server`, which must not be imported directly from the `rsc`
122 entry.
123
124 ## Declare the Website
125
126 Declare the site as a module-level const (rather than inline in the
127 Stack) and describe the environment topology with `viteEnvironments`:
128
129 ```typescript
130 // alchemy.run.ts
131 import * as Cloudflare from "@alchemy.run/cloudflare";
132
133 export const Website = Cloudflare.Website.Vite("Website", {
134 viteEnvironments: {
135 entry: "rsc",
136 children: ["ssr"],
137 },
138 });
139
140 export type WebsiteEnv = Cloudflare.InferEnv<typeof Website>;
141 ```
142
143 No asset routing config is needed: the RSC build emits no
144 `index.html` (HTML is server-rendered), so page requests match no
145 static asset and fall through to the RSC handler, while the
146 hydration bundles serve directly from the asset layer. The server
147 bundle's Node APIs are covered by the `nodejs_compat` compatibility
148 flag, which is enabled by default for every Worker.
149
150 ## Add it to the Stack
151
152 Yield the Website from your Stack and return its URL:
153
154 ```typescript
155 // alchemy.run.ts
156 import * as Alchemy from "alchemy";
157 import * as Effect from "effect/Effect";
158
159 export default Alchemy.Stack(
160 "ReactRouterApp",
161 {
162 providers: Cloudflare.providers(),
163 state: Cloudflare.state(),
164 },
165 Effect.gen(function* () {
166 const website = yield* Website;
167 return { url: website.url };
168 }),
169 );
170 ```
171
172 ## Add bindings
173
174 The resource returns a plain `Worker`, so `env` accepts the full
175 binding vocabulary — KV namespaces, R2 buckets, Durable Objects,
176 secrets:
177
178 ```diff lang="typescript"
179 // alchemy.run.ts
180 +import * as Config from "effect/Config";
181
182 +export const Uploads = Cloudflare.R2.Bucket("Uploads");
183
184 export const Website = Cloudflare.Website.Vite("Website", {
185 + env: {
186 + UPLOADS: Uploads,
187 + API_KEY: Config.Redacted("API_KEY"),
188 + },
189 viteEnvironments: {
190 entry: "rsc",
191 children: ["ssr"],
192 },
193 });
194 ```
195
196 `Uploads` is a description, not a deploy — Alchemy provisions the
197 real bucket because the Website binds it. `Config.Redacted` reads
198 `API_KEY` from your environment at deploy time and binds it as a
199 Worker secret — see [Secrets & env](/cloudflare/security/secrets-env).
200
201 The Worker entry receives `env` as the standard second argument of
202 the module-worker `fetch` contract — type it with the inferred
203 shape:
204
205 ```typescript
206 // react-router-vite/entry.worker.tsx
207 import type { WebsiteEnv } from "../alchemy.run.ts";
208
209 export default {
210 async fetch(request: Request, env: WebsiteEnv, ctx: ExecutionContext) {
211 // env.UPLOADS and env.API_KEY are fully typed here
212 // ... hand off to the RSC request handler
213 },
214 };
215 ```
216
217 ## How viteEnvironments maps to the deploy
218
219 `viteEnvironments` selects which of the build's environments make up
220 the deployed Worker:
221
222 ```typescript
223 viteEnvironments: {
224 entry: "rsc", // this environment's output is the Worker entry chunk
225 children: ["ssr"], // these environments' chunks are bundled alongside it
226 }
227 ```
228
229 The `entry` environment produces the chunk the Worker boots from, every
230 environment listed in `children` has its chunks bundled alongside so
231 cross-environment `loadModule` calls resolve inside the deployed Worker,
232 and the `client` environment is always deployed as static assets — it is
233 never listed. The default is `{ entry: "ssr", children: [] }`, so a
234 React Router app that doesn't use Server Components — a
235 single-environment SSR build — needs no `viteEnvironments` at all.
236
237 ## Deploy and verify
238
239 ```sh
240 bun alchemy deploy
241 ```
242
243 This exact shape is exercised by Alchemy's live test suite ("Vite:
244 React Router RSC deploys from a distilled manifest"): the test deploys
245 the app to real Cloudflare and asserts the home route serves
246 server-rendered HTML, the `/about` client route resolves, and a
247 `/worker-render` route returns HTML rendered through the `ssr`
248 environment's chunk — server rendering and client navigation are both
249 verified against the deployed Worker.