@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 323 lines 9.44 KB
Raw
1 ---
2 title: React Router
3 description: Deploy React Router v8 (framework mode) to AWS with AWS.Website.ReactRouter — SSR on a Lambda Web Function, client assets on S3 + CloudFront, and React Router's own Vite dev server under alchemy dev.
4 sidebar:
5 order: 7
6 ---
7
8 import PackageManagers from "../../../../components/PackageManagers.astro";
9
10 export const devDeps = "@alchemy.run/frontend-frameworks";
11
12 `AWS.Website.ReactRouter` deploys a
13 [React Router](https://reactrouter.com) v8 app in framework mode to AWS.
14 React Router builds through Vite, so Alchemy runs your project's own
15 build: the SSR server runs on a
16 [Lambda Web Function](/aws/compute/web-functions) and streams its
17 responses, and client assets are served from a private S3 bucket through
18 CloudFront. A CloudFront Function routes each request at the edge —
19 uploaded files go to S3, everything else streams from the server.
20
21 ## Install
22
23 The build integration is not bundled with alchemy. Install
24 `@alchemy.run/frontend-frameworks`; the resource loads its
25 `/react-router` and `/react-router/node` exports from your project at
26 deploy time. It is only used at build time, so a dev dependency is
27 enough:
28
29 <PackageManagers dev={devDeps} />
30
31 The React Router side is whatever `npx create-react-router@latest`
32 scaffolds — `react-router`, `@react-router/dev`, `@react-router/node`,
33 `isbot`, and `vite`. Keep `@react-router/node` and `isbot` in
34 `dependencies`: React Router picks its default `entry.server` by reading
35 them from your `package.json`, and installs `isbot` on the fly if it is
36 missing.
37
38 ## Configure Vite
39
40 Your `vite.config.ts` stays exactly what the React Router scaffold gives
41 you — no adapter, no server preset:
42
43 ```typescript
44 // vite.config.ts
45 import { reactRouter } from "@react-router/dev/vite";
46 import { defineConfig } from "vite";
47
48 export default defineConfig({
49 plugins: [reactRouter()],
50 });
51 ```
52
53 `reactRouter()` owns routing, typegen, and both build environments.
54 Alchemy drives the same two passes `react-router build` runs, forces the
55 SSR bundle to be self-contained, and serves its fetch handler from a
56 Node server.
57
58 :::caution[Remove @cloudflare/vite-plugin if present]
59 The React Router CLI adds `@cloudflare/vite-plugin` when you pick the
60 Cloudflare template. It builds for workerd, not Node, so an AWS deploy
61 needs it gone:
62
63 ```diff lang="typescript"
64 // vite.config.ts
65 -import { cloudflare } from "@cloudflare/vite-plugin";
66 import { reactRouter } from "@react-router/dev/vite";
67 import { defineConfig } from "vite";
68
69 export default defineConfig({
70 - plugins: [cloudflare({ viteEnvironment: { name: "ssr" } }), reactRouter()],
71 + plugins: [reactRouter()],
72 });
73 ```
74
75 :::
76
77 ## Declare the Website
78
79 Declare the site as a module-level const (rather than inline in the
80 Stack):
81
82 ```typescript
83 // alchemy.run.ts
84 import * as AWS from "@alchemy.run/aws";
85
86 export const Website = AWS.Website.ReactRouter("Website");
87 ```
88
89 `rootDir` is the project root — the directory holding `package.json`,
90 `vite.config.*`, and `react-router.config.ts`. It defaults to `"."`, so
91 set it only when the app does not sit next to `alchemy.run.ts`:
92
93 ```typescript
94 export const Website = AWS.Website.ReactRouter("Website", {
95 rootDir: "./web",
96 });
97 ```
98
99 ## Add it to the Stack
100
101 Yield the site from your Stack and return its URL:
102
103 ```typescript
104 // alchemy.run.ts
105 import * as Alchemy from "alchemy";
106 import * as Effect from "effect/Effect";
107
108 export default Alchemy.Stack(
109 "MyReactRouterSite",
110 {
111 providers: AWS.providers(),
112 state: AWS.state(),
113 },
114 Effect.gen(function* () {
115 const site = yield* Website;
116 return { url: site.url };
117 }),
118 );
119 ```
120
121 Requests matching a built client asset are served straight from S3;
122 everything else — SSR routes, loaders, actions, resource routes — falls
123 through to the server.
124
125 ## How the two build outputs are deployed
126
127 `react-router build` writes two directories, and each one becomes a
128 different piece of AWS infrastructure:
129
130 ```
131 build/
132 ├── client/ -> uploaded to S3, served through CloudFront
133 └── server/ -> the Web Function deployment package
134 ```
135
136 `build/client` holds the hashed browser bundles plus everything you put
137 in `public/`. `build/server/index.js` is a `ServerBuild` manifest, not a
138 request handler, so Alchemy wraps it with `createRequestHandler` during
139 the build and emits `build/server/serve-node.mjs` beside it — that
140 module is the deployed server entry.
141
142 If you set Vite's `base`, set React Router's `basename` to the same
143 prefix: the client directory maps onto the site root one-for-one, so the
144 paths the SSR document emits have to be the paths S3 was given.
145
146 ## Add environment variables
147
148 The server function's environment is configured under `env`:
149
150 ```diff lang="typescript"
151 // alchemy.run.ts
152 export const Website = AWS.Website.ReactRouter("Website", {
153 + env: {
154 + API_BASE: "https://api.example.com",
155 + },
156 });
157 ```
158
159 `env` values are set on the server on deploy and injected into
160 the dev server's process environment under `alchemy dev`, so server code
161 reads the same values in both modes. Sibling props tune the
162 server itself (`timeout`, `maxConcurrencyPerEnvironment`,
163 `maxEnvironments`).
164
165 An output from another resource only exists once that resource is
166 yielded, so declare the site inside the Stack generator instead:
167
168 ```typescript
169 // alchemy.run.ts
170 Effect.gen(function* () {
171 const api = yield* Api;
172
173 const site = yield* AWS.Website.ReactRouter("Website", {
174 env: { API_BASE: api.url },
175 });
176
177 return { url: site.url };
178 });
179 ```
180
181 ## Read the environment in a loader
182
183 The React Router server is a plain Node server, so loaders and
184 actions read the environment from `process.env`:
185
186 ```typescript
187 // app/routes/home.tsx
188 export function loader() {
189 return { apiBase: process.env.API_BASE ?? "unset" };
190 }
191 ```
192
193 Values prefixed `VITE_` are inlined into the client bundle at build time
194 instead, as `import.meta.env.VITE_*` — set those in the shell that runs
195 `alchemy deploy`, not in `env`.
196
197 ## Read the environment in a resource route
198
199 A route module with no default export is a resource route, served by the
200 same server:
201
202 ```typescript
203 // app/routes/api.hello.ts
204 export function loader() {
205 return new Response(process.env.API_BASE ?? "unset");
206 }
207 ```
208
209 ## Call AWS services from server code
210
211 The composite creates and owns the server Lambda's execution role, and
212 exposes no prop to add permissions to it. Server code that needs to
213 reach AWS goes behind its own Lambda, where capabilities are bound
214 explicitly:
215
216 ```typescript
217 // alchemy.run.ts
218 Effect.gen(function* () {
219 const api = yield* Api;
220
221 const site = yield* AWS.Website.ReactRouter("Website", {
222 env: { API_BASE: api.url },
223 });
224
225 return { url: site.url };
226 });
227 ```
228
229 A loader then calls that API over HTTP with the URL it was handed:
230
231 ```typescript
232 // app/routes/home.tsx
233 export async function loader() {
234 const res = await fetch(`${process.env.API_BASE}/hello`);
235 return { body: await res.text() };
236 }
237 ```
238
239 See [Effect HTTP API](/aws/apis/effect-http-api) for building that
240 Lambda and binding it to the resources it reads.
241
242 ## Build configuration
243
244 The build runs through your project's own `vite.config.ts` and
245 `react-router.config.ts`. A custom `buildDirectory` just works — the
246 integration observes the directory from the resolved Vite config, so
247 there is nothing to mirror on the resource.
248
249 ## Run on a Lambda Function
250
251 Web Functions run in a subset of Regions. Elsewhere, set
252 `server: "function"`: the app builds with the `/react-router/aws` deploy target
253 and runs on a Lambda Function behind a streaming Function URL, tuned with
254 `memorySize`, `architecture`, and `runtime`:
255
256 ```diff lang="typescript"
257 // alchemy.run.ts
258 export const Website = AWS.Website.ReactRouter("Website", {
259 + server: "function",
260 + memorySize: 2048,
261 });
262 ```
263
264 ## Local dev
265
266 ```sh
267 bun alchemy dev
268 ```
269
270 `alchemy dev` runs React Router's own Vite dev server (native HMR)
271 instead of deploying anything; `site.url` is the dev server's
272 `http://localhost:<port>` address and no AWS resources are created. Wrap
273 the site in `Alchemy.remote()` to deploy the real infrastructure even
274 during dev.
275
276 ## React Server Components
277
278 RSC is not supported on AWS yet. React Router's `unstable` RSC plugin —
279 and the `future.v8_viteEnvironmentApi` flag — emit more than one server
280 environment, and this resource assembles a single one. A build that
281 produces no single server entry fails with an actionable error rather
282 than deploying something broken. For RSC today, deploy to Cloudflare
283 with [`Cloudflare.Website.Vite`](/cloudflare/frontend/react-router),
284 which takes a `viteEnvironments` description of the environment
285 topology.
286
287 ## Custom domain
288
289 ```typescript
290 // alchemy.run.ts
291 export const Website = AWS.Website.ReactRouter("Website", {
292 domain: { name: "app.example.com" },
293 });
294 ```
295
296 The certificate is created in `us-east-1` (required by CloudFront), DNS
297 validation records and the alias record are managed through Route 53.
298 The hosted zone is inferred from the hostname — pass `hostedZoneId` to
299 pin it when several zones could match.
300
301 ## Share a distribution with Router
302
303 CloudFront distributions take minutes to create. To serve several sites
304 (or a site plus an API) from one distribution, attach the site to an
305 [`AWS.Website.Router`](/aws/frontend/static-site#compose-sites-with-a-router):
306
307 The site takes the Router's outputs, so both are yielded inside the
308 Stack generator:
309
310 ```typescript
311 // alchemy.run.ts
312 Effect.gen(function* () {
313 const router = yield* AWS.Website.Router("FrontDoor", {
314 domain: { name: "example.com" },
315 });
316
317 const site = yield* AWS.Website.ReactRouter("Website", {
318 domain: { router },
319 });
320
321 return { url: site.url };
322 });
323 ```