@astrojs/cloudflare 7.7.1 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,420 +2,37 @@
2
2
 
3
3
  An SSR adapter for use with Cloudflare Pages Functions targets. Write your code in Astro/Javascript and deploy to Cloudflare Pages.
4
4
 
5
- ## Install
5
+ ## Documentation
6
6
 
7
- Add the Cloudflare adapter to enable SSR in your Astro project with the following `astro add` command. This will install the adapter and make the appropriate changes to your `astro.config.mjs` file in one step.
7
+ Read the [`@astrojs/cloudflare` docs][docs]
8
8
 
9
- ```sh
10
- # Using NPM
11
- npx astro add cloudflare
12
- # Using Yarn
13
- yarn astro add cloudflare
14
- # Using PNPM
15
- pnpm astro add cloudflare
16
- ```
9
+ ## Support
17
10
 
18
- If you prefer to install the adapter manually instead, complete the following two steps:
11
+ - Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more!
19
12
 
20
- 1. Add the Cloudflare adapter to your project's dependencies using your preferred package manager. If you’re using npm or aren’t sure, run this in the terminal:
13
+ - Check our [Astro Integration Documentation][astro-integration] for more on integrations.
21
14
 
22
- ```bash
23
- npm install @astrojs/cloudflare
24
- ```
15
+ - Submit bug reports and feature requests as [GitHub issues][issues].
25
16
 
26
- 2. Add the following to your `astro.config.mjs` file:
27
-
28
- ```diff lang="js"
29
- // astro.config.mjs
30
- import { defineConfig } from 'astro/config';
31
- + import cloudflare from '@astrojs/cloudflare';
32
-
33
- export default defineConfig({
34
- + output: 'server',
35
- + adapter: cloudflare(),
36
- });
37
- ```
38
-
39
- ## Options
40
-
41
- ### `mode`
42
-
43
- `mode: "advanced" | "directory"`
44
-
45
- default `"advanced"`
46
-
47
- This configuration option defines how your Astro project is deployed to Cloudflare Pages.
48
-
49
- - `advanced` mode picks up the `_worker.js` file in the `dist` folder
50
- - `directory` mode picks up the files in the `functions` folder, by default only one `[[path]].js` file is generated
51
-
52
- Switching to directory mode allows you to add additional files manually such as [Cloudflare Pages Plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/), [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/) or custom functions using [Cloudflare Pages Functions Routing](https://developers.cloudflare.com/pages/platform/functions/routing/).
53
-
54
- ```js
55
- // astro.config.mjs
56
- export default defineConfig({
57
- adapter: cloudflare({ mode: 'directory' }),
58
- });
59
- ```
60
-
61
- To compile a separate bundle for each page, set the `functionPerRoute` option in your Cloudflare adapter config. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing files with identical names in the `functions` folder, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages.
62
-
63
- ```diff lang="js"
64
- // astro.config.mjs
65
- import {defineConfig} from "astro/config";
66
- import cloudflare from '@astrojs/cloudflare';
67
-
68
- export default defineConfig({
69
- adapter: cloudflare({
70
- mode: 'directory',
71
- + functionPerRoute: true
72
- })
73
- })
74
- ```
75
-
76
- This adapter doesn't support the [`edgeMiddleware`](https://docs.astro.build/en/reference/adapter-reference/#edgemiddleware) option.
77
-
78
- ### `routes.strategy`
79
-
80
- `routes.strategy: "auto" | "include" | "exclude"`
81
-
82
- default `"auto"`
83
-
84
- Determines how `routes.json` will be generated if no [custom `_routes.json`](#custom-_routesjson) is provided.
85
-
86
- There are three options available:
87
-
88
- - **`"auto"` (default):** Will automatically select the strategy that generates the fewest entries. This should almost always be sufficient, so choose this option unless you have a specific reason not to.
89
-
90
- - **`include`:** Pages and endpoints that are not pre-rendered are listed as `include` entries, telling Cloudflare to invoke these routes as functions. `exclude` entries are only used to resolve conflicts. Usually the best strategy when your website has mostly static pages and only a few dynamic pages or endpoints.
91
-
92
- Example: For `src/pages/index.astro` (static), `src/pages/company.astro` (static), `src/pages/users/faq.astro` (static) and `/src/pages/users/[id].astro` (SSR) this will produce the following `_routes.json`:
93
-
94
- ```json
95
- {
96
- "version": 1,
97
- "include": [
98
- "/_image", // Astro's image endpoint
99
- "/users/*" // Dynamic route
100
- ],
101
- "exclude": [
102
- // Static routes that needs to be exempted from the dynamic wildcard route above
103
- "/users/faq/",
104
- "/users/faq/index.html"
105
- ]
106
- }
107
- ```
108
-
109
- - **`exclude`:** Pre-rendered pages are listed as `exclude` entries (telling Cloudflare to handle these routes as static assets). Usually the best strategy when your website has mostly dynamic pages or endpoints and only a few static pages.
110
-
111
- Example: For the same pages as in the previous example this will produce the following `_routes.json`:
112
-
113
- ```json
114
- {
115
- "version": 1,
116
- "include": [
117
- "/*" // Handle everything as function except the routes below
118
- ],
119
- "exclude": [
120
- // All static assets
121
- "/",
122
- "/company/",
123
- "/index.html",
124
- "/users/faq/",
125
- "/favicon.png",
126
- "/company/index.html",
127
- "/users/faq/index.html"
128
- ]
129
- }
130
- ```
131
-
132
- ### `routes.include`
133
-
134
- `routes.include: string[]`
135
-
136
- default `[]`
137
-
138
- If you want to use the automatic `_routes.json` generation, but want to include additional routes (e.g. when having custom functions in the `functions` folder), you can use the `routes.include` option to add additional routes to the `include` array.
139
-
140
- ### `routes.exclude`
141
-
142
- `routes.exclude: string[]`
143
-
144
- default `[]`
145
-
146
- If you want to use the automatic `_routes.json` generation, but want to exclude additional routes, you can use the `routes.exclude` option to add additional routes to the `exclude` array.
147
-
148
- The following example automatically generates `_routes.json` while including and excluding additional routes. Note that that is only necessary if you have custom functions in the `functions` folder that are not handled by Astro.
149
-
150
- ```diff lang="js"
151
- // astro.config.mjs
152
- export default defineConfig({
153
- adapter: cloudflare({
154
- mode: 'directory',
155
- + routes: {
156
- + strategy: 'include',
157
- + include: ['/users/*'], // handled by custom function: functions/users/[id].js
158
- + exclude: ['/users/faq'], // handled by static page: pages/users/faq.astro
159
- + },
160
- }),
161
- });
162
- ```
163
-
164
- ### `imageService`
165
-
166
- `imageService: "passthrough" | "cloudflare"`
167
-
168
- Determines which image service is used by the adapter. The adapter will default to `passthrough` mode when an incompatible image service is configured. Otherwise, it will use the globally configured image service:
169
-
170
- - **`cloudflare`:** Uses the [Cloudflare Image Resizing](https://developers.cloudflare.com/images/image-resizing/) service.
171
- - **`passthrough`:** Uses the existing [`noop`](https://docs.astro.build/en/guides/images/#configure-no-op-passthrough-service) service.
172
-
173
- ### `wasmModuleImports`
174
-
175
- `wasmModuleImports: boolean`
176
-
177
- default: `false`
178
-
179
- Whether or not to import `.wasm` files [directly as ES modules](https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration) using the `.wasm?module` import syntax.
180
-
181
- Add `wasmModuleImports: true` to `astro.config.mjs` to enable this functionality in both the Cloudflare build and the Astro dev server. Read more about [using Wasm modules](#use-wasm-modules).
182
-
183
- ```diff lang="js"
184
- // astro.config.mjs
185
- import {defineConfig} from "astro/config";
186
- import cloudflare from '@astrojs/cloudflare';
187
-
188
- export default defineConfig({
189
- adapter: cloudflare({
190
- + wasmModuleImports: true
191
- }),
192
- output: 'server'
193
- })
194
- ```
195
-
196
- ### `runtime`
197
-
198
- `runtime: { mode: "off" | "local", persistTo: string }`
199
-
200
- default `{ mode: 'off', persistTo: '' }`
201
-
202
- Determines whether and how the Cloudflare Runtime is added to `astro dev`.
203
-
204
- The Cloudflare Runtime includes [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Read more about [accessing the Cloudflare Runtime](#cloudflare-runtime).
205
-
206
- The `mode` property defines how the runtime is added to `astro dev`:
207
-
208
- - `local`: uses bindings mocking and locally static placeholders
209
- - `off`: no access to the Cloudflare runtime using `astro dev`. You can alternatively use [Preview with Wrangler](#preview-with-wrangler)
210
-
211
- The `persistTo` property defines where the local runtime is persisted to when using `mode: local`. This value is a directory relative to your `astro dev` execution path.
212
-
213
- The default value is set to `.wrangler/state/v3` to match the default path Wrangler uses. This means both tools are able to access and use the local state.
214
-
215
- Whichever directory is set in `persistTo`, `.wrangler` or your custom value, must be added to `.gitignore`.
216
-
217
- ```diff lang="js"
218
- // astro.config.mjs
219
- import { defineConfig } from 'astro/config';
220
- import cloudflare from '@astrojs/cloudflare';
221
-
222
- export default defineConfig({
223
- output: 'server',
224
- adapter: cloudflare({
225
- + runtime: { mode: 'local' },
226
- }),
227
- });
228
- ```
229
-
230
- ## Cloudflare runtime
231
-
232
- Gives you access to [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings).
233
-
234
- Currently supported bindings:
235
-
236
- - [Cloudflare D1](https://developers.cloudflare.com/d1/)
237
- - [Cloudflare R2](https://developers.cloudflare.com/r2/)
238
- - [Cloudflare Workers KV](https://developers.cloudflare.com/kv/)
239
- - [Cloudflare Durable Objects](https://developers.cloudflare.com/durable-objects/)
240
-
241
- You can access the runtime from Astro components through `Astro.locals` inside any `.astro` file.
242
-
243
- ```astro
244
- ---
245
- // src/pages/index.astro
246
- const runtime = Astro.locals.runtime;
247
- ---
248
-
249
- <pre>{JSON.stringify(runtime.env)}</pre>
250
- ```
251
-
252
- You can access the runtime from API endpoints through `context.locals`:
253
-
254
- ```js
255
- // src/pages/api/someFile.js
256
- export function GET(context) {
257
- const runtime = context.locals.runtime;
258
-
259
- return new Response('Some body');
260
- }
261
- ```
262
-
263
- ### Typing
264
-
265
- If you have configured `mode: advanced`, you can type the `runtime` object using `AdvancedRuntime`:
266
-
267
- ```ts
268
- // src/env.d.ts
269
- /// <reference types="astro/client" />
270
-
271
- type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
272
- type ENV = {
273
- SERVER_URL: string;
274
- KV_BINDING: KVNamespace;
275
- };
276
-
277
- type Runtime = import('@astrojs/cloudflare').AdvancedRuntime<ENV>;
278
-
279
- declare namespace App {
280
- interface Locals extends Runtime {
281
- user: {
282
- name: string;
283
- surname: string;
284
- };
285
- }
286
- }
287
- ```
288
-
289
- If you have configured `mode: directory`, you can type the `runtime` object using `DirectoryRuntime`:
290
-
291
- ```ts
292
- // src/env.d.ts
293
- /// <reference types="astro/client" />
294
-
295
- type KVNamespace = import('@cloudflare/workers-types/experimental').KVNamespace;
296
- type ENV = {
297
- SERVER_URL: string;
298
- KV_BINDING: KVNamespace;
299
- };
300
-
301
- type Runtime = import('@astrojs/cloudflare').DirectoryRuntime<ENV>;
302
-
303
- declare namespace App {
304
- interface Locals extends Runtime {
305
- user: {
306
- name: string;
307
- surname: string;
308
- };
309
- }
310
- }
311
- ```
312
-
313
- ## Platform
314
-
315
- ### Headers
316
-
317
- You can attach [custom headers](https://developers.cloudflare.com/pages/platform/headers/) to your responses by adding a `_headers` file in your Astro project's `public/` folder. This file will be copied to your build output directory.
318
-
319
- ### Redirects
320
-
321
- You can declare [custom redirects](https://developers.cloudflare.com/pages/platform/redirects/) using Cloudflare Pages. This allows you to redirect requests to a different URL. You can add a `_redirects` file in your Astro project's `public/` folder. This file will be copied to your build output directory.
322
-
323
- ### Routes
324
-
325
- You can define which routes are invoking functions and which are static assets, using [Cloudflare routing](https://developers.cloudflare.com/pages/platform/functions/routing/#functions-invocation-routes) via a `_routes.json` file. This file is automatically generated by Astro.
326
-
327
- #### Custom `_routes.json`
328
-
329
- By default, `@astrojs/cloudflare` will generate a `_routes.json` file with `include` and `exclude` rules based on your applications's dynamic and static routes.
330
- This will enable Cloudflare to serve files and process static redirects without a function invocation. Creating a custom `_routes.json` will override this automatic optimization. See [Cloudflare's documentation on creating a custom `routes.json`](https://developers.cloudflare.com/pages/platform/functions/routing/#create-a-_routesjson-file) for more details.
331
-
332
- ## Use Wasm modules
333
-
334
- The following is an example of importing a Wasm module that then responds to requests by adding the request's number parameters together.
335
-
336
- ```js
337
- // pages/add/[a]/[b].js
338
- import mod from '../util/add.wasm?module';
339
-
340
- // instantiate ahead of time to share module
341
- const addModule: any = new WebAssembly.Instance(mod);
342
-
343
- export async function GET(context) {
344
- const a = Number.parseInt(context.params.a);
345
- const b = Number.parseInt(context.params.b);
346
- return new Response(`${addModule.exports.add(a, b)}`);
347
- }
348
- ```
349
-
350
- While this example is trivial, Wasm can be used to accelerate computationally intensive operations which do not involve significant I/O such as embedding an image processing library.
351
-
352
- ## Node.js compatibility
353
-
354
- Astro's Cloudflare adapter allows you to use any Node.js runtime API supported by Cloudflare:
355
-
356
- - assert
357
- - AsyncLocalStorage
358
- - Buffer
359
- - Crypto
360
- - Diagnostics Channel
361
- - EventEmitter
362
- - path
363
- - process
364
- - Streams
365
- - StringDecoder
366
- - util
367
-
368
- To use these APIs, your page or endpoint must be server-side rendered (not pre-rendered) and must use the the `import {} from 'node:*'` import syntax.
369
-
370
- ```js
371
- // pages/api/endpoint.js
372
- export const prerender = false;
373
- import { Buffer } from 'node:buffer';
374
- ```
375
-
376
- Additionally, you'll need to enable the Compatibility Flag in Cloudflare. The configuration for this flag may vary based on where you deploy your Astro site. For detailed guidance, please refer to the [Cloudflare documentation on enabling Node.js compatibility](https://developers.cloudflare.com/workers/runtime-apis/nodejs).
377
-
378
- ## Cloudflare module support
379
-
380
- All Cloudflare namespaced packages (e.g. `cloudflare:sockets`) are allowlisted for use. Note that the package `cloudflare:sockets` does not work locally without using Wrangler dev mode.
381
-
382
- ## Preview with Wrangler
383
-
384
- To use [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) to run your application locally, update the preview script:
385
-
386
- ```json
387
- //package.json
388
- "preview": "wrangler pages dev ./dist"
389
- ```
390
-
391
- [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) gives you access to [Cloudflare bindings](https://developers.cloudflare.com/pages/platform/functions/bindings), [environment variables](https://developers.cloudflare.com/pages/platform/functions/bindings/#environment-variables), and the [cf object](https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties). Getting hot reloading or the astro dev server to work with Wrangler might require custom setup. See [community examples](https://github.com/withastro/roadmap/discussions/590).
392
-
393
- ### Meaningful error messages
394
-
395
- Currently, errors during running your application in Wrangler are not very useful, due to the minification of your code. For better debugging, you can add `vite.build.minify = false` setting to your `astro.config.mjs`.
396
-
397
- ```diff lang="js"
398
- // astro.config.mjs
399
- export default defineConfig({
400
- adapter: cloudflare(),
401
- output: 'server',
402
-
403
- + vite: {
404
- + build: {
405
- + minify: false,
406
- + },
407
- + },
408
- });
409
- ```
17
+ ## Contributing
410
18
 
411
- ## Troubleshooting
19
+ This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started:
412
20
 
413
- For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
21
+ - [Contributor Manual][contributing]
22
+ - [Code of Conduct][coc]
23
+ - [Community Guide][community]
414
24
 
415
- You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
25
+ ## License
416
26
 
417
- ## Contributing
27
+ MIT
418
28
 
419
- This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
29
+ Copyright (c) 2023–present [Astro][astro]
420
30
 
31
+ [astro]: https://astro.build/
32
+ [docs]: https://docs.astro.build/en/guides/integrations-guide/cloudflare/
33
+ [contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md
34
+ [coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md
35
+ [community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md
36
+ [discord]: https://astro.build/chat/
37
+ [issues]: https://github.com/withastro/adapter/issues
421
38
  [astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
@@ -14,7 +14,7 @@ export function createExports(manifest) {
14
14
  if (manifest.assets.has(pathname)) {
15
15
  return env.ASSETS.fetch(request);
16
16
  }
17
- let routeData = app.match(request);
17
+ const routeData = app.match(request);
18
18
  Reflect.set(request, Symbol.for('astro.clientAddress'), request.headers.get('cf-connecting-ip'));
19
19
  const locals = {
20
20
  runtime: {
@@ -26,7 +26,7 @@ export function createExports(manifest) {
26
26
  caches: caches,
27
27
  },
28
28
  };
29
- let response = await app.render(request, routeData, locals);
29
+ const response = await app.render(request, routeData, locals);
30
30
  if (app.setCookieHeaders) {
31
31
  for (const setCookieHeader of app.setCookieHeaders(response)) {
32
32
  response.headers.append('Set-Cookie', setCookieHeader);
@@ -16,7 +16,7 @@ export function createExports(manifest) {
16
16
  if (manifest.assets.has(pathname)) {
17
17
  return env.ASSETS.fetch(request);
18
18
  }
19
- let routeData = app.match(request);
19
+ const routeData = app.match(request);
20
20
  Reflect.set(request, Symbol.for('astro.clientAddress'), request.headers.get('cf-connecting-ip'));
21
21
  const locals = {
22
22
  runtime: {
@@ -28,7 +28,7 @@ export function createExports(manifest) {
28
28
  caches: caches,
29
29
  },
30
30
  };
31
- let response = await app.render(request, routeData, locals);
31
+ const response = await app.render(request, routeData, locals);
32
32
  if (app.setCookieHeaders) {
33
33
  for (const setCookieHeader of app.setCookieHeaders(response)) {
34
34
  response.headers.append('Set-Cookie', setCookieHeader);
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { AstroIntegration } from 'astro';
2
+ import type { RUNTIME } from './utils/local-runtime.js';
2
3
  export type { AdvancedRuntime } from './entrypoints/server.advanced.js';
3
4
  export type { DirectoryRuntime } from './entrypoints/server.directory.js';
4
- type Options = {
5
+ export type Options = {
5
6
  mode?: 'directory' | 'advanced';
6
7
  functionPerRoute?: boolean;
7
8
  imageService?: 'passthrough' | 'cloudflare';
@@ -19,18 +20,34 @@ type Options = {
19
20
  exclude?: string[];
20
21
  };
21
22
  /**
22
- * Going forward only the object API should be used. The modes work as known before:
23
- * 'off': current behaviour (wrangler is needed)
24
- * 'local': use a static req.cf object, and env vars defined in wrangler.toml & .dev.vars (astro dev is enough)
25
- * 'remote': use a dynamic real-live req.cf object, and env vars defined in wrangler.toml & .dev.vars (astro dev is enough)
23
+ * { mode: 'off' }: current behaviour (wrangler is needed)
24
+ * { mode: 'local', ... }: adds cf request object, locals bindings, env vars/secrets which are defined by the user to `astro.dev` with `Astro.locals.runtime` / `context.locals.runtime`
26
25
  */
27
- runtime?: 'off' | 'local' | 'remote' | {
26
+ runtime?: {
28
27
  mode: 'off';
29
28
  } | {
30
- mode: 'remote';
29
+ mode: Extract<RUNTIME, {
30
+ type: 'pages';
31
+ }>['mode'];
32
+ type: Extract<RUNTIME, {
33
+ type: 'pages';
34
+ }>['type'];
35
+ persistTo?: Extract<RUNTIME, {
36
+ type: 'pages';
37
+ }>['persistTo'];
38
+ bindings?: Extract<RUNTIME, {
39
+ type: 'pages';
40
+ }>['bindings'];
31
41
  } | {
32
- mode: 'local';
33
- persistTo?: string;
42
+ mode: Extract<RUNTIME, {
43
+ type: 'workers';
44
+ }>['mode'];
45
+ type: Extract<RUNTIME, {
46
+ type: 'workers';
47
+ }>['type'];
48
+ persistTo?: Extract<RUNTIME, {
49
+ type: 'workers';
50
+ }>['persistTo'];
34
51
  };
35
52
  wasmModuleImports?: boolean;
36
53
  };