@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 182 lines 6.25 KB
Raw
1 ---
2 title: "Part 4: A Vite Frontend"
3 description: Connect a Vite frontend to your Prisma API, develop locally, and destroy the tutorial resources.
4 sidebar:
5 order: 4
6 ---
7
8 import PackageManagers from "../../../../components/PackageManagers.astro";
9
10 Continue from [Part 3](/prisma/tutorial/part-3). Add a browser button that
11 queries the API, then run the frontend locally against the deployed backend.
12
13 ## Install the frontend tooling
14
15 <PackageManagers dev="vite @vercel/nft" />
16
17 Vite builds the frontend. `@vercel/nft` traces the server dependencies that
18 Alchemy includes in the deployment archive.
19
20 ## Allow the frontend origin
21
22 The frontend and API have separate origins. Add a response-header variable
23 inside the API's `fetch` Effect:
24
25 ```diff lang="typescript"
26 // src/Api.ts
27 const request = yield* HttpServerRequest;
28 + const headers = { "access-control-allow-origin": "*" };
29 ```
30
31 This tutorial exposes only a public, read-only timestamp query. For a real
32 application, restrict allowed origins and add authentication before exposing
33 private data. CORS is a browser policy, not an authorization mechanism.
34
35 ## Attach the response headers
36
37 ```diff lang="typescript"
38 // src/Api.ts
39 status: 405,
40 - headers: { allow: "GET" },
41 + headers: { ...headers, allow: "GET" },
42
43 - return yield* HttpServerResponse.json({ ok: true });
44 + return yield* HttpServerResponse.json({ ok: true }, { headers });
45
46 - return yield* HttpServerResponse.json(rows[0]);
47 + return yield* HttpServerResponse.json(rows[0], { headers });
48
49 - return HttpServerResponse.text("Not found", { status: 404 });
50 + return HttpServerResponse.text("Not found", { status: 404, headers });
51
52 status: 503,
53 + headers: { "access-control-allow-origin": "*" },
54 ```
55
56 All explicitly constructed API responses now use the same CORS policy.
57 The frontend sends a simple GET without credentials or custom headers.
58
59 ## Create the page
60
61 Create `index.html` in the project root:
62
63 ```html
64 <!doctype html>
65 <html lang="en">
66 <head>
67 <meta charset="UTF-8" />
68 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
69 <title>Prisma tutorial</title>
70 </head>
71 <body>
72 <main>
73 <h1>Prisma database clock</h1>
74 <p>Read the current time from Prisma Postgres through an Effect API.</p>
75 <button id="refresh" type="button">Read database time</button>
76 <p id="result" role="status">No query yet.</p>
77 </main>
78 <script type="module" src="/src/main.ts"></script>
79 </body>
80 </html>
81 ```
82
83 The status element announces query results, while the button gives the user
84 control over when to send a request.
85
86 ## Query from the browser
87
88 Create `src/main.ts`:
89
90 ```typescript
91 const button = document.querySelector<HTMLButtonElement>("#refresh")!;
92 const result = document.querySelector<HTMLParagraphElement>("#result")!;
93
94 button.addEventListener("click", async () => {
95 button.disabled = true;
96 result.textContent = "Querying Postgres…";
97 try {
98 const response = await fetch(`${import.meta.env.VITE_API_URL}/api/time`);
99 if (!response.ok) throw new Error(`Request failed (${response.status})`);
100 const data: { time: string } = await response.json();
101 result.textContent = `Database time: ${data.time}`;
102 } catch {
103 result.textContent = "Could not read the database. Please try again.";
104 } finally {
105 button.disabled = false;
106 }
107 });
108 ```
109
110 The button is disabled during the request and re-enabled after either success
111 or failure. `VITE_API_URL` will contain a public API URL, never a database
112 credential. If your editor needs Vite's `import.meta.env` types, add
113 `/// <reference types="vite/client" />` to `src/vite-env.d.ts`.
114
115 ## Keep the backend remote during development
116
117 ```diff lang="typescript"
118 // alchemy.run.ts
119 - const project = yield* Project;
120 - const api = yield* Api;
121 + const project = yield* Project.pipe(Alchemy.remote());
122 + const api = yield* Api.pipe(Alchemy.remote());
123 ```
124
125 `Alchemy.remote()` keeps this backend on Prisma when running `alchemy dev`.
126 It is a no-op during deployment. This tutorial deliberately uses real
127 Postgres during frontend development, so credentials and cloud charges still
128 apply. The Project is also remote because it is shared with the website.
129
130 ## Add the website
131
132 ```diff lang="typescript"
133 // alchemy.run.ts
134 const api = yield* Api.pipe(Alchemy.remote());
135 + const site = yield* Prisma.Website.Vite("Website", {
136 + project,
137 + regionId: "eu-west-3",
138 + env: { VITE_API_URL: api.url },
139 + });
140 - return { projectId: project.projectId, apiUrl: api.url };
141 + return { url: site.url, apiUrl: api.url };
142 ```
143
144 The website uses the same Project. Its environment references the API output,
145 so Alchemy resolves the API URL before building the frontend. `VITE_` values
146 are embedded in the public browser bundle; only put public configuration there.
147
148 ## Deploy the frontend
149
150 <PackageManagers run="alchemy deploy" />
151
152 Open `url` and click **Read database time**. The response should display a
153 Postgres timestamp. Click again to execute a new query.
154
155 ## Develop locally
156
157 <PackageManagers run="alchemy dev" />
158
159 Open the local website URL that Alchemy prints. Edit the heading and confirm
160 Vite updates the page. Click the button to query the remote API. Provider-mode
161 changes can replace the deployed website with its local counterpart in this
162 stage; use a separate `--stage dev` when you want to keep a production site.
163 A separate stage creates its own remote backend resources too.
164
165 ## Remove the resources
166
167 Stop the dev command, then destroy the Stack:
168
169 <PackageManagers run="alchemy destroy" />
170
171 Confirm the deletion. This removes the website, API, connection, database, and
172 Project. Use the same profile and stage used to deploy; destroy every extra
173 stage you created. Keep `.alchemy/` until cleanup completes so Alchemy can
174 find the resources it owns.
175
176 ## Where to go next
177
178 - [Complete tutorial example](https://github.com/alchemy-run/alchemy/tree/main/examples/prisma-tutorial)
179 - [Frontend frameworks](/prisma/frontend/websites) — Astro, Next.js, and the other Website helpers.
180 - [Postgres](/prisma/data/postgres) — database configuration and local development.
181 - [Connections](/prisma/data/connections) — runtime connection bindings.
182 - [Compute apps](/prisma/compute/apps) — deployment options and custom domains.