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

main
mdx 306 lines 8.74 KB
Raw
1 ---
2 title: React SPA
3 description: Deploy a React single-page app to AWS with AWS.Website.Vite — the Vite build on S3 + CloudFront, deep links answered by index.html out of the box, and Vite's own dev server under alchemy dev.
4 sidebar:
5 order: 5
6 ---
7
8 import { Code, Tabs, TabItem } from "@astrojs/starlight/components";
9 import PackageManagers from "../../../../components/PackageManagers.astro";
10
11 export const devDeps = "@alchemy.run/frontend-frameworks";
12 export const routerDep = "react-router-dom";
13
14 This is the walkthrough for a plain React single-page app on
15 [`AWS.Website.Vite`](/aws/frontend/vite): scaffold the project, run
16 its own `vite build`, and serve the output from a private S3 bucket
17 through CloudFront. The composite is assets-only — it never creates a
18 Lambda — and `spa` defaults on, so client-side routes deep-link
19 correctly with nothing to configure. For the resource itself and
20 every prop, see the
21 [Vite resource page](/aws/frontend/vite).
22
23 ## Install
24
25 The build integration is not bundled with alchemy. Install
26 `@alchemy.run/frontend-frameworks`; the resource loads its `/vite` and
27 `/vite/aws` exports from your project at deploy time. It is only used
28 at build time, so a dev dependency is enough:
29
30 <PackageManagers dev={devDeps} />
31
32 ## Scaffold the app
33
34 Start from Vite's official React + TypeScript template:
35
36 <Tabs syncKey="pkgManager">
37 <TabItem label="pnpm" icon="pnpm">
38 <Code code={`pnpm create vite web --template react-ts\ncd web && pnpm install && cd ..`} lang="sh" />
39 </TabItem>
40 <TabItem label="bun" icon="bun">
41 <Code code={`bun create vite@latest web -- --template react-ts\ncd web && bun install && cd ..`} lang="sh" />
42 </TabItem>
43 <TabItem label="npm" icon="npm">
44 <Code code={`npm create vite@latest web -- --template react-ts\ncd web && npm install && cd ..`} lang="sh" />
45 </TabItem>
46 <TabItem label="yarn" icon="seti:yarn">
47 <Code code={`yarn create vite web --template react-ts\ncd web && yarn install && cd ..`} lang="sh" />
48 </TabItem>
49 </Tabs>
50
51 That drops a complete project into `./web/` with its own
52 `index.html`, `package.json`, and `vite.config.ts`.
53
54 ## Configure Vite
55
56 Your `vite.config.*` loads natively — plugins, aliases, and every
57 other non-serializable option work exactly as they do outside
58 Alchemy. The React template already registers the React plugin:
59
60 ```typescript
61 // web/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 There is no adapter to install and no build command to wire up:
71 Alchemy runs this config programmatically.
72
73 ## Declare the Website
74
75 Declare the site as a module-level const (rather than inline in the
76 Stack). `rootDir` points at the project directory — the one holding
77 `index.html` and `vite.config.ts`:
78
79 ```typescript
80 // alchemy.run.ts
81 import * as AWS from "@alchemy.run/aws";
82
83 export const Website = AWS.Website.Vite("Website", {
84 rootDir: "./web",
85 });
86 ```
87
88 `rootDir` defaults to `"."`, so you only set it when the app isn't
89 next to your `alchemy.run.ts`.
90
91 ## Add it to the Stack
92
93 Yield the site from your Stack and return its URL:
94
95 ```typescript
96 // alchemy.run.ts
97 import * as Alchemy from "alchemy";
98 import * as Effect from "effect/Effect";
99
100 export default Alchemy.Stack(
101 "MyReactApp",
102 {
103 providers: AWS.providers(),
104 state: AWS.state(),
105 },
106 Effect.gen(function* () {
107 const site = yield* Website;
108 return { url: site.url };
109 }),
110 );
111 ```
112
113 ```sh
114 bun alchemy deploy
115 ```
116
117 Alchemy runs `vite build` in `rootDir`, uploads `dist/` to a private
118 S3 bucket, and serves it through CloudFront. `site.url` is the
119 distribution's URL (or `https://<your-domain>` once you pass
120 `domain`).
121
122 ## Client-side routing
123
124 Deep links work with no configuration. `spa` defaults to `true`, so a
125 request that matches no uploaded file is answered with the index page
126 and a `200` — the client router then handles the path.
127
128 Add React Router and route on the client:
129
130 <PackageManagers add={routerDep} />
131
132 ```tsx
133 // web/src/main.tsx
134 import React from "react";
135 import ReactDOM from "react-dom/client";
136 import { BrowserRouter, Link, Route, Routes } from "react-router-dom";
137
138 function App() {
139 return (
140 <BrowserRouter>
141 <Link to="/about">About</Link>
142 <Routes>
143 <Route path="/" element={<h1>Home</h1>} />
144 <Route path="/about" element={<h1>About</h1>} />
145 </Routes>
146 </BrowserRouter>
147 );
148 }
149
150 ReactDOM.createRoot(document.getElementById("root")!).render(
151 <React.StrictMode>
152 <App />
153 </React.StrictMode>,
154 );
155 ```
156
157 Loading `https://<your-site>/about` directly serves `index.html` and
158 React Router renders the About page — no rewrite rule, no edge
159 function to write.
160
161 Pretty URLs still win over the fallback: `/about` serves
162 `about.html` or `about/index.html` when the build produced one.
163
164 ## Serve a real 404 instead
165
166 Multi-page Vite projects (an `index.html` per route) want a status
167 code, not the shell. Set `errorPage` and turn the SPA fallback off —
168 the two are mutually exclusive:
169
170 ```diff lang="typescript"
171 // alchemy.run.ts
172 export const Website = AWS.Website.Vite("Website", {
173 rootDir: "./web",
174 + spa: false,
175 + errorPage: "404.html",
176 });
177 ```
178
179 ## Environment variables
180
181 A pure SPA has no server, so anything the client reads is inlined
182 into the bundle at build time. That is plain Vite: put `VITE_`-prefixed
183 keys in a `.env` file at the project root and read them from
184 `import.meta.env`.
185
186 ```sh
187 # web/.env
188 VITE_API_URL=https://api.example.com
189 ```
190
191 ```tsx
192 // web/src/api.ts
193 const apiUrl = import.meta.env.VITE_API_URL;
194
195 export const hello = () => fetch(`${apiUrl}/hello`);
196 ```
197
198 Only `VITE_`-prefixed keys reach the client bundle. A committed
199 `.env` is hashed with the rest of the project, so editing one re-runs
200 the build on the next deploy. A gitignored one (`.env.local`) is not
201 — see [Skip unchanged builds](#skip-unchanged-builds) for how to
202 widen the hash.
203
204 ## Inject another resource's URL
205
206 `AWS.Website.Vite` takes no server environment (there is no server),
207 so a value that only exists after another resource deploys — an API's
208 Function URL, a bucket name — can't be passed to the build through
209 the composite. Deploy those apps with
210 [`AWS.Website.StaticSite`](/aws/frontend/static-site) instead, which
211 runs the build as a command and passes `build.env` to it:
212
213 ```typescript
214 // alchemy.run.ts
215 Effect.gen(function* () {
216 const api = yield* Api;
217
218 const site = yield* AWS.Website.StaticSite("Website", {
219 path: "./web",
220 build: {
221 command: "npm run build",
222 output: "dist",
223 env: {
224 VITE_API_URL: api.url,
225 },
226 },
227 spa: true,
228 });
229
230 return { url: site.url };
231 });
232 ```
233
234 Outputs like `api.url` resolve before the build command runs, so Vite
235 inlines the deployed URL exactly as it would a `.env` value.
236
237 ## Skip unchanged builds
238
239 Every file under `rootDir` (gitignore rules applied) plus the nearest
240 lockfile is content-hashed. A deploy whose inputs are unchanged skips
241 the build and the upload entirely. Narrow or widen the hash with
242 `memo`, or set `memo: false` to rebuild on every deploy:
243
244 ```diff lang="typescript"
245 // alchemy.run.ts
246 export const Website = AWS.Website.Vite("Website", {
247 rootDir: "./web",
248 + memo: {
249 + include: ["src/**", "index.html", "package.json"],
250 + lockfile: true,
251 + },
252 });
253 ```
254
255 Setting `include` (or `exclude`) drops the lockfile from the hash —
256 pass `lockfile: true` to keep rebuilding when dependencies change.
257
258 ## Local dev
259
260 ```sh
261 bun alchemy dev
262 ```
263
264 `alchemy dev` runs Vite's own dev server — native HMR, instant module
265 updates — instead of deploying. `site.url` is the local address and
266 no AWS resources are created at all: no bucket, no distribution.
267
268 The dev server picks an ephemeral port. Pin it when you want the
269 local URL stable across runs:
270
271 ```diff lang="typescript"
272 // alchemy.run.ts
273 export const Website = AWS.Website.Vite("Website", {
274 rootDir: "./web",
275 + dev: { port: 3000 },
276 });
277 ```
278
279 Wrap the site in `Alchemy.remote()` to deploy the real S3 +
280 CloudFront infrastructure even during dev.
281
282 ## Custom domain
283
284 ```typescript
285 // alchemy.run.ts
286 export const Website = AWS.Website.Vite("Website", {
287 rootDir: "./web",
288 domain: { name: "app.example.com" },
289 });
290 ```
291
292 The certificate and Route 53 records are managed for you — the hosted
293 zone is inferred from the hostname, and `hostedZoneId` pins it when
294 several zones could match. To serve
295 several sites from one front door, attach to an
296 [`AWS.Website.Router`](/aws/frontend/static-site#compose-sites-with-a-router)
297 with `domain: { router, path: "/app" }` instead.
298
299 ## Where next
300
301 - [Vite on AWS](/aws/frontend/vite) — the resource reference: every
302 prop, the `vite` override bag, invalidation, and Router composition
303 - [Websites on AWS](/aws/frontend/websites) — the full websites
304 surface, including server-side rendering
305 - [Static sites](/aws/frontend/static-site) — the build-command path
306 for any pre-built output