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

main
mdx 323 lines 8.86 KB
Raw
1 ---
2 title: Astro
3 description: Deploy an Astro site to Cloudflare Workers with Cloudflare.Website.Astro — SSR in the Worker, prerendered pages as static assets, sessions backed by an auto-provisioned KV namespace, and route caching on Workers Cache.
4 sidebar:
5 order: 9
6 ---
7
8 import PackageManagers from "../../../../components/PackageManagers.astro";
9
10 export const devDeps = "@alchemy.run/frontend-frameworks";
11
12 `Cloudflare.Website.Astro` deploys an [Astro](https://astro.build)
13 project as a Cloudflare Worker. It runs Astro's programmatic build
14 with a wrangler-free Cloudflare adapter: server-rendered pages
15 execute in the Worker, prerendered pages and client assets deploy as
16 static assets. Your `astro.config.*` loads natively — there is no
17 adapter to install into it and no Wrangler file to write.
18
19 ## Install
20
21 The build integration is not bundled with alchemy. Install
22 `@alchemy.run/frontend-frameworks`; the resource loads its `/astro`
23 export from your project at deploy time. It is only used at build time,
24 so a dev dependency is enough:
25
26 <PackageManagers dev={devDeps} />
27
28 ## Configure Astro
29
30 Your `astro.config.*` file loads natively — integrations, Vite
31 plugins, and any other non-serializable options work exactly as they
32 do outside Alchemy. Alchemy merges a programmatic config *over* it:
33 the Cloudflare adapter is injected for you (don't declare an
34 `adapter` in your config — that fails the build with an actionable
35 error), and options passed via the `astro` prop override the file's —
36 see [Astro configuration](#astro-configuration) below for the
37 details.
38
39 ## Declare the Website
40
41 Declare the site as a module-level const (rather than inline in the
42 Stack) and derive the typed shape of its bindings from it:
43
44 ```typescript
45 // alchemy.run.ts
46 import * as Cloudflare from "@alchemy.run/cloudflare";
47
48 export const Website = Cloudflare.Website.Astro("Website");
49
50 export type WebsiteEnv = Cloudflare.InferEnv<typeof Website>;
51 ```
52
53 `WebsiteEnv` is the typed shape of the Worker's bindings, derived
54 from the class — you'll import it into your Astro code in
55 [Read bindings in server code](#read-bindings-in-server-code).
56
57 ## Add it to the Stack
58
59 Yield the class from your Stack and return its URL:
60
61 ```typescript
62 // alchemy.run.ts
63 import * as Alchemy from "alchemy";
64 import * as Effect from "effect/Effect";
65
66 export default Alchemy.Stack(
67 "MyAstroSite",
68 {
69 providers: Cloudflare.providers(),
70 state: Cloudflare.state(),
71 },
72 Effect.gen(function* () {
73 const site = yield* Website;
74 return { url: site.url };
75 }),
76 );
77 ```
78
79 Pages are server-rendered by default. Pages that
80 `export const prerender = true` are served as static assets. Astro's
81 server runtime is built against Node APIs, so the `nodejs_compat`
82 compatibility flag is added automatically — you don't need to pass
83 it.
84
85 During `alchemy dev`, Astro's dev server runs with SSR executing in
86 workerd, so server code sees the same runtime and the same real
87 bindings it will have in production.
88
89 See
90 [examples/cloudflare-website-astro](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-website-astro)
91 for the checked-in example.
92
93 ## Add bindings
94
95 The resource returns a plain `Worker`, so `env` accepts the full
96 binding vocabulary — KV namespaces, R2 buckets, Durable Objects,
97 secrets:
98
99 ```diff lang="typescript"
100 // alchemy.run.ts
101 +import * as Config from "effect/Config";
102
103 +export const Cache = Cloudflare.KV.Namespace("Cache");
104
105 export const Website = Cloudflare.Website.Astro("Website", {
106 + env: {
107 + CACHE: Cache,
108 + API_KEY: Config.Redacted("API_KEY"),
109 + },
110 });
111 ```
112
113 `Cache` is a description, not a deploy — Alchemy provisions the real
114 namespace because the Website binds it. `Config.Redacted` reads
115 `API_KEY` from your environment at deploy time and binds it as a
116 Worker secret — see [Secrets & env](/cloudflare/security/secrets-env).
117
118 ## Read bindings in server code
119
120 Server code reads bindings from `env` in `cloudflare:workers`:
121
122 ```astro
123 ---
124 // src/pages/index.astro
125 import { env } from "cloudflare:workers";
126
127 const cached = await env.CACHE.get("greeting");
128 ---
129
130 <h1>{cached ?? "hello"}</h1>
131 ```
132
133 `Astro.locals.runtime.env` was removed in Astro 6 and throws if you
134 read it.
135
136 Type `env` once with the `WebsiteEnv` type from `alchemy.run.ts`:
137
138 ```typescript
139 // src/env.d.ts
140 import type { WebsiteEnv } from "../alchemy.run.ts";
141
142 declare module "cloudflare:workers" {
143 namespace Cloudflare {
144 interface Env extends WebsiteEnv {}
145 }
146 }
147 ```
148
149 `env.CACHE` is now a KV namespace and `env.API_KEY` a string.
150 Renaming a binding in `alchemy.run.ts` is a type error in your
151 pages.
152
153 ## Sessions
154
155 Astro's session API is backed by a KV namespace. One is provisioned
156 and bound as `SESSION` automatically, so `Astro.session` works with
157 zero configuration.
158
159 Bind your own namespace under that name to use it instead:
160
161 ```typescript
162 export const Sessions = Cloudflare.KV.Namespace("Sessions");
163
164 export const Website = Cloudflare.Website.Astro("Website", {
165 env: {
166 SESSION: Sessions,
167 },
168 });
169 ```
170
171 Or opt out of session provisioning entirely:
172
173 ```typescript
174 export const Website = Cloudflare.Website.Astro("Website", {
175 sessionKVBindingName: false,
176 });
177 ```
178
179 ## Route caching
180
181 Astro's route cache runs on Workers Cache. Set the cache provider to
182 `cacheCloudflare()` and give each route a rule in `routeRules`:
183
184 ```typescript
185 // astro.config.ts
186 import { defineConfig } from "astro/config";
187 import { cacheCloudflare } from "@alchemy.run/frontend-frameworks/astro/cache";
188
189 export default defineConfig({
190 cache: { provider: cacheCloudflare() },
191 routeRules: {
192 "/insights": { maxAge: 600, swr: 86400 },
193 },
194 });
195 ```
196
197 Alchemy sees the provider and turns on Workers Cache for the Worker.
198 The edge then serves `/insights` for 10 minutes without running the
199 Worker. A route with no rule is never cached.
200
201 Import `cacheCloudflare` from `@alchemy.run/frontend-frameworks`, not
202 `@astrojs/cloudflare/cache`. The upstream package needs Wrangler.
203
204 Set a rule from a page with `Astro.cache.set()`:
205
206 ```astro
207 ---
208 // src/pages/blog/[slug].astro
209 Astro.cache.set({ maxAge: 300, tags: ["blog"] });
210 ---
211 ```
212
213 Each response is tagged with its path. Purge a path or a tag with
214 `Astro.cache.invalidate()`:
215
216 ```typescript
217 // src/pages/api/publish.ts
218 import type { APIRoute } from "astro";
219
220 export const POST: APIRoute = async ({ cache }) => {
221 await cache.invalidate({ tags: ["blog"] });
222 return new Response("purged");
223 };
224 ```
225
226 ## Fully static sites
227
228 Set `output: "static"` in `astro.config.*` and every page is
229 prerendered at build time. The deploy is assets-only: no server
230 bundle is uploaded, and Cloudflare's asset layer answers every
231 request.
232
233 ```typescript
234 // astro.config.ts
235 import { defineConfig } from "astro/config";
236
237 export default defineConfig({ output: "static" });
238 ```
239
240 Serve the built `404.html` for unmatched routes:
241
242 ```typescript
243 export const Website = Cloudflare.Website.Astro("Website", {
244 assets: { notFoundHandling: "404-page" },
245 });
246 ```
247
248 No Worker code runs at request time, so a static site gets no
249 session namespace.
250
251 ## Astro configuration
252
253 Your `astro.config.*` is the primary place to configure Astro —
254 integrations, Vite plugins, and every other option (serializable or
255 not) work as usual:
256
257 ```typescript
258 // astro.config.ts
259 import { defineConfig } from "astro/config";
260 import react from "@astrojs/react";
261 import tailwindcss from "@tailwindcss/vite";
262
263 export default defineConfig({
264 site: "https://blog.example.com",
265 integrations: [react()],
266 vite: {
267 plugins: [tailwindcss()],
268 },
269 });
270 ```
271
272 A config file can't consume Alchemy `Output`s or vary by stage. For
273 those values the `astro` prop is a deploy-time override bag — a
274 serializable subset (`site`, `base`, `output`, `srcDir`, `publicDir`,
275 `outDir`, `trailingSlash`) merged *over* the config file, so a value
276 set here wins:
277
278 ```typescript
279 // alchemy.run.ts
280 import { Stack } from "alchemy/Stack";
281
282 export const Website = Cloudflare.Website.Astro(
283 "Website",
284 Stack.useSync(({ stage }) => ({
285 astro: {
286 site:
287 stage === "prod"
288 ? "https://blog.example.com"
289 : `https://${stage}.example.com`,
290 },
291 })),
292 );
293 ```
294
295 Use `config` to load an alternate config file (relative to
296 `rootDir`) instead of astro's own `astro.config.*` discovery:
297
298 ```typescript
299 export const Website = Cloudflare.Website.Astro("Website", {
300 config: "astro.deploy.config.ts",
301 });
302 ```
303
304 Alchemy injects its wrangler-free Cloudflare adapter. Declaring an
305 `adapter` in `astro.config.*` fails the build with an error that
306 tells you to remove it.
307
308 `output` comes from the `astro` prop, then the config file, then
309 defaults to `"server"`. Astro's own default is `"static"`, which
310 would prerender every page at build time, where the Worker's
311 bindings don't exist.
312
313 ## Prerendering runtime
314
315 Prerendered pages render in workerd at build time, the same runtime
316 as the deployed Worker. Pages that need Node APIs while prerendering
317 can use Astro's Node prerenderer instead:
318
319 ```typescript
320 export const Website = Cloudflare.Website.Astro("Website", {
321 prerenderEnvironment: "node",
322 });
323 ```