@astrojs/cloudflare 7.7.0 → 8.0.0

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
@@ -195,24 +195,46 @@ export default defineConfig({
195
195
 
196
196
  ### `runtime`
197
197
 
198
- `runtime: { mode: "off" | "local", persistTo: string }`
198
+ See Cloudflare's repository for more type information about [CF_BINDING](https://github.com/cloudflare/workers-sdk/blob/eaa16db25103d26ef31499634a31b86caccdf7aa/packages/wrangler/src/api/startDevWorker/types.ts#L190-L219)
199
+
200
+ `runtime: { mode: 'off' } | { mode: 'local'; type: 'pages'; persistTo?: string; bindings?: Record<string, CF_BINDING> } | { mode: 'local'; type: 'workers'; persistTo?: string; };`
199
201
 
200
202
  default `{ mode: 'off', persistTo: '' }`
201
203
 
202
204
  Determines whether and how the Cloudflare Runtime is added to `astro dev`.
205
+ Read more about [the Cloudflare Runtime](#cloudflare-runtime).
206
+
207
+ The `type` property defines where your Astro project is deployed to:
208
+
209
+ - `pages`: Deployed to [Cloudflare Pages](https://pages.cloudflare.com/)
210
+ - `workers`: Deployed to [Cloudflare Workers](https://workers.cloudflare.com/)
211
+
212
+ The `mode` property defines what you want the runtime to support in `astro dev`:
213
+
214
+ - `off`: no access to the runtime using `astro dev`. You can choose [Preview with Wrangler](#preview-with-wrangler) when you need access to the runtime, to simulate the production environment locally.
215
+ - `local`: uses a local runtime powered by miniflare and workerd, which supports Cloudflare's Bindings. Only if you want to use unsupported features, such as `eval`, bindings with no local support choose [Preview with Wrangler](#preview-with-wrangler)
203
216
 
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).
217
+ In `mode: local`, you have access to the `persistTo` property which defines where the local bindings state is saved. This avoids fresh bindings on every restart of the dev server. This value is a directory relative to your `astro dev` execution path. By default it is set to `.wrangler/state/v3` to allow usage of `wrangler` cli commands (e.g. for migrations). Add this path to your `.gitignore`.
218
+
219
+ ## Cloudflare runtime
220
+
221
+ The Cloudflare runtime gives you access to environment variables and Cloudflare bindings. You can find more information in Cloudflare's [Workers](https://developers.cloudflare.com/workers/configuration/bindings/) and [Pages](https://developers.cloudflare.com/pages/platform/functions/bindings/) docs. Depending on your deployment type (`pages` or `workers`), you need to configure the bindings differently.
222
+
223
+ Currently supported bindings:
205
224
 
206
- The `mode` property defines how the runtime is added to `astro dev`:
225
+ - Environment Variables
226
+ - [Cloudflare Workers KV](https://developers.cloudflare.com/kv/)
227
+ - [Cloudflare D1](https://developers.cloudflare.com/d1/)
228
+ - [Cloudflare R2](https://developers.cloudflare.com/r2/)
229
+ - [Cloudflare Durable Objects](https://developers.cloudflare.com/durable-objects/)
207
230
 
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)
231
+ ### Config
210
232
 
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.
233
+ #### Cloudflare Pages
212
234
 
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.
235
+ Cloudflare Pages does not support a configuration file.
214
236
 
215
- Whichever directory is set in `persistTo`, `.wrangler` or your custom value, must be added to `.gitignore`.
237
+ To deploy your pages project to production, you need to configure the bindings using Cloudflare's Dashboard. To be able to access bindings locally, you need to configure them using the adpater's `runtime` option.
216
238
 
217
239
  ```diff lang="js"
218
240
  // astro.config.mjs
@@ -222,21 +244,103 @@ import cloudflare from '@astrojs/cloudflare';
222
244
  export default defineConfig({
223
245
  output: 'server',
224
246
  adapter: cloudflare({
225
- + runtime: { mode: 'local' },
247
+ + runtime: {
248
+ + mode: 'local',
249
+ + type: 'pages',
250
+ + bindings: {
251
+ // example of a var binding (environment variable)
252
+ + "URL": {
253
+ + type: "var",
254
+ + value: "https://example.com",
255
+ + },
256
+ // example of a KV binding
257
+ + "KV": {
258
+ + type: "kv",
259
+ + },
260
+ // example of a D1 binding
261
+ + "D1": {
262
+ + type: "d1",
263
+ + },
264
+ // example of a R2 binding
265
+ + "R2": {
266
+ + type: "r2",
267
+ + },
268
+ // example of a Durable Object binding
269
+ + "DO": {
270
+ + type: "durable-object",
271
+ + className: "DO",
272
+ + },
273
+ + },
274
+ + },
226
275
  }),
227
276
  });
228
277
  ```
229
278
 
230
- ## Cloudflare runtime
279
+ If you also need to define `secrets` in addition to enviroment variables, you need to add a `.dev.vars` file to the root of the Astro project:
231
280
 
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).
281
+ ```
282
+ # .dev.vars
283
+ DB_PASSWORD=myPassword
284
+ ```
233
285
 
234
- Currently supported bindings:
286
+ If you want to use `wrangler` for cli commands, e.g. D1 migrations, you also need to add a `wrangler.toml` to the root of the Astro project with the correct content. Consult [Cloudflare's documentation](https://developers.cloudflare.com/) for further details.
235
287
 
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/)
288
+ ```toml
289
+ # wrangler.toml
290
+ name = "example"
291
+ compatibility_date = "2023-06-14"
292
+
293
+ # example for D1 Binding
294
+ [[d1_databases]]
295
+ binding = "D1"
296
+ database_name = "D1"
297
+ database_id = "D1"
298
+ preview_database_id = "D1"
299
+ ```
300
+
301
+ #### Cloudflare Workers
302
+
303
+ To deploy your workers project to production, you need to configure the bindings using a `wrangler.toml` config file in the root directory of your Astro project. To be able to access bindings locally, the `@astrojs/cloudflare` adapter will also read the `wrangler.toml` file.
304
+
305
+ ```toml
306
+ # wrangler.toml
307
+ name = "example"
308
+
309
+ # example of a KV Binding
310
+ kv_namespaces = [
311
+ { binding = "KV", id = "KV", preview_id = "KV" },
312
+ ]
313
+
314
+ # example of a var binding (environment variables)
315
+ [vars]
316
+ URL = "example.com"
317
+
318
+ # example of a D1 Binding
319
+ [[d1_databases]]
320
+ binding = "D1"
321
+ database_name = "D1"
322
+ database_id = "D1"
323
+ preview_database_id = "D1"
324
+
325
+ # example of a R2 Binding
326
+ [[r2_buckets]]
327
+ binding = 'R2'
328
+ bucket_name = 'R2'
329
+
330
+ # example of a Durable Object Binding
331
+ [[durable_objects.bindings]]
332
+ name = "DO"
333
+ class_name = "DO"
334
+ ```
335
+
336
+ If you also need to define `secrets` in addition to enviroment variables, you need to add a `.dev.vars` file to the root of the Astro project:
337
+
338
+ ```
339
+ # .dev.vars
340
+ DB_PASSWORD=myPassword
341
+ ```
342
+
343
+ ### Usage
240
344
 
241
345
  You can access the runtime from Astro components through `Astro.locals` inside any `.astro` file.
242
346
 
@@ -14,31 +14,25 @@ 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, { matchNotFound: true });
18
- if (routeData) {
19
- Reflect.set(request, Symbol.for('astro.clientAddress'), request.headers.get('cf-connecting-ip'));
20
- const locals = {
21
- runtime: {
22
- waitUntil: (promise) => {
23
- context.waitUntil(promise);
24
- },
25
- env: env,
26
- cf: request.cf,
27
- caches: caches,
17
+ let routeData = app.match(request);
18
+ Reflect.set(request, Symbol.for('astro.clientAddress'), request.headers.get('cf-connecting-ip'));
19
+ const locals = {
20
+ runtime: {
21
+ waitUntil: (promise) => {
22
+ context.waitUntil(promise);
28
23
  },
29
- };
30
- let response = await app.render(request, routeData, locals);
31
- if (app.setCookieHeaders) {
32
- for (const setCookieHeader of app.setCookieHeaders(response)) {
33
- response.headers.append('Set-Cookie', setCookieHeader);
34
- }
24
+ env: env,
25
+ cf: request.cf,
26
+ caches: caches,
27
+ },
28
+ };
29
+ let response = await app.render(request, routeData, locals);
30
+ if (app.setCookieHeaders) {
31
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
32
+ response.headers.append('Set-Cookie', setCookieHeader);
35
33
  }
36
- return response;
37
34
  }
38
- return new Response(null, {
39
- status: 404,
40
- statusText: 'Not found',
41
- });
35
+ return response;
42
36
  };
43
37
  return { default: { fetch } };
44
38
  }
@@ -16,31 +16,25 @@ 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, { matchNotFound: true });
20
- if (routeData) {
21
- Reflect.set(request, Symbol.for('astro.clientAddress'), request.headers.get('cf-connecting-ip'));
22
- const locals = {
23
- runtime: {
24
- waitUntil: (promise) => {
25
- context.waitUntil(promise);
26
- },
27
- env: context.env,
28
- cf: request.cf,
29
- caches: caches,
19
+ let routeData = app.match(request);
20
+ Reflect.set(request, Symbol.for('astro.clientAddress'), request.headers.get('cf-connecting-ip'));
21
+ const locals = {
22
+ runtime: {
23
+ waitUntil: (promise) => {
24
+ context.waitUntil(promise);
30
25
  },
31
- };
32
- let response = await app.render(request, routeData, locals);
33
- if (app.setCookieHeaders) {
34
- for (const setCookieHeader of app.setCookieHeaders(response)) {
35
- response.headers.append('Set-Cookie', setCookieHeader);
36
- }
26
+ env: context.env,
27
+ cf: request.cf,
28
+ caches: caches,
29
+ },
30
+ };
31
+ let response = await app.render(request, routeData, locals);
32
+ if (app.setCookieHeaders) {
33
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
34
+ response.headers.append('Set-Cookie', setCookieHeader);
37
35
  }
38
- return response;
39
36
  }
40
- return new Response(null, {
41
- status: 404,
42
- statusText: 'Not found',
43
- });
37
+ return response;
44
38
  };
45
39
  return { onRequest, manifest };
46
40
  }
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
  };
package/dist/index.js CHANGED
@@ -1,50 +1,27 @@
1
- import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
2
- import { AstroError } from 'astro/errors';
3
- import esbuild from 'esbuild';
4
- import { Miniflare } from 'miniflare';
5
1
  import * as fs from 'node:fs';
6
2
  import * as os from 'node:os';
7
3
  import { dirname, relative, sep } from 'node:path';
8
4
  import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
6
+ import { AstroError } from 'astro/errors';
7
+ import esbuild from 'esbuild';
9
8
  import glob from 'tiny-glob';
10
9
  import { getAdapter } from './getAdapter.js';
11
10
  import { deduplicatePatterns } from './utils/deduplicatePatterns.js';
12
- import { getCFObject } from './utils/getCFObject.js';
13
11
  import { prepareImageConfig } from './utils/image-config.js';
14
- import { getD1Bindings, getDOBindings, getEnvVars, getKVBindings, getR2Bindings, } from './utils/parser.js';
12
+ import { getLocalRuntime, getRuntimeConfig } from './utils/local-runtime.js';
15
13
  import { prependForwardSlash } from './utils/prependForwardSlash.js';
16
14
  import { rewriteWasmImportPath } from './utils/rewriteWasmImportPath.js';
17
15
  import { wasmModuleLoader } from './utils/wasm-module-loader.js';
18
- const RUNTIME_WARNING = `You are using a deprecated string format for the \`runtime\` API. Please update to the current format for better support.
19
-
20
- Example:
21
- Old Format: 'local'
22
- Current Format: { mode: 'local', persistTo: '.wrangler/state/v3' }
23
-
24
- Please refer to our runtime documentation for more details on the format. https://docs.astro.build/en/guides/integrations-guide/cloudflare/#runtime`;
25
16
  export default function createIntegration(args) {
26
17
  let _config;
27
18
  let _buildConfig;
28
- let _mf;
19
+ let _localRuntime;
29
20
  let _entryPoints = new Map();
30
21
  const SERVER_BUILD_FOLDER = '/$server_build/';
31
22
  const isModeDirectory = args?.mode === 'directory';
32
23
  const functionPerRoute = args?.functionPerRoute ?? false;
33
- let runtimeMode = { mode: 'off' };
34
- if (args?.runtime === 'remote') {
35
- runtimeMode = { mode: 'remote' };
36
- }
37
- else if (args?.runtime === 'local') {
38
- runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
39
- }
40
- else if (typeof args?.runtime === 'object' &&
41
- args?.runtime.mode === 'local' &&
42
- args.runtime.persistTo === undefined) {
43
- runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
44
- }
45
- else if (args?.runtime) {
46
- runtimeMode = args?.runtime;
47
- }
24
+ const runtimeMode = getRuntimeConfig(args?.runtime);
48
25
  return {
49
26
  name: '@astrojs/cloudflare',
50
27
  hooks: {
@@ -68,7 +45,7 @@ export default function createIntegration(args) {
68
45
  image: prepareImageConfig(args?.imageService ?? 'DEFAULT', config.image, command, logger),
69
46
  });
70
47
  },
71
- 'astro:config:done': ({ setAdapter, config, logger }) => {
48
+ 'astro:config:done': ({ setAdapter, config }) => {
72
49
  setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
73
50
  _config = config;
74
51
  _buildConfig = config.build;
@@ -78,97 +55,38 @@ export default function createIntegration(args) {
78
55
  if (_config.base === SERVER_BUILD_FOLDER) {
79
56
  throw new AstroError('[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.');
80
57
  }
81
- if (typeof args?.runtime === 'string') {
82
- logger.warn(RUNTIME_WARNING);
83
- }
84
58
  },
85
- 'astro:server:setup': ({ server }) => {
59
+ 'astro:server:setup': ({ server, logger }) => {
86
60
  if (runtimeMode.mode === 'local') {
87
- const typedRuntimeMode = runtimeMode;
88
61
  server.middlewares.use(async function middleware(req, res, next) {
89
- try {
90
- const cf = await getCFObject(typedRuntimeMode.mode);
91
- const vars = await getEnvVars();
92
- const D1Bindings = await getD1Bindings();
93
- const R2Bindings = await getR2Bindings();
94
- const KVBindings = await getKVBindings();
95
- const DOBindings = await getDOBindings();
96
- let bindingsEnv = new Object({});
97
- // fix for the error "kj/filesystem-disk-unix.c++:1709: warning: PWD environment variable doesn't match current directory."
98
- // note: This mismatch might be primarily due to the test runner.
99
- const originalPWD = process.env.PWD;
100
- process.env.PWD = process.cwd();
101
- _mf = new Miniflare({
102
- modules: true,
103
- script: '',
104
- cache: true,
105
- cachePersist: `${typedRuntimeMode.persistTo}/cache`,
106
- cacheWarnUsage: true,
107
- d1Databases: D1Bindings,
108
- d1Persist: `${typedRuntimeMode.persistTo}/d1`,
109
- r2Buckets: R2Bindings,
110
- r2Persist: `${typedRuntimeMode.persistTo}/r2`,
111
- kvNamespaces: KVBindings,
112
- kvPersist: `${typedRuntimeMode.persistTo}/kv`,
113
- durableObjects: DOBindings,
114
- durableObjectsPersist: `${typedRuntimeMode.persistTo}/do`,
115
- });
116
- await _mf.ready;
117
- for (const D1Binding of D1Bindings) {
118
- const db = await _mf.getD1Database(D1Binding);
119
- Reflect.set(bindingsEnv, D1Binding, db);
120
- }
121
- for (const R2Binding of R2Bindings) {
122
- const bucket = await _mf.getR2Bucket(R2Binding);
123
- Reflect.set(bindingsEnv, R2Binding, bucket);
124
- }
125
- for (const KVBinding of KVBindings) {
126
- const namespace = await _mf.getKVNamespace(KVBinding);
127
- Reflect.set(bindingsEnv, KVBinding, namespace);
128
- }
129
- for (const key in DOBindings) {
130
- if (Object.prototype.hasOwnProperty.call(DOBindings, key)) {
131
- const DO = await _mf.getDurableObjectNamespace(key);
132
- Reflect.set(bindingsEnv, key, DO);
133
- }
134
- }
135
- const mfCache = await _mf.getCaches();
136
- process.env.PWD = originalPWD;
137
- const clientLocalsSymbol = Symbol.for('astro.locals');
138
- Reflect.set(req, clientLocalsSymbol, {
139
- runtime: {
140
- env: {
141
- // default binding for static assets will be dynamic once we support mocking of bindings
142
- ASSETS: {},
143
- // this is just a VAR for CF to change build behavior, on dev it should be 0
144
- CF_PAGES: '0',
145
- // will be fetched from git dynamically once we support mocking of bindings
146
- CF_PAGES_BRANCH: 'TBA',
147
- // will be fetched from git dynamically once we support mocking of bindings
148
- CF_PAGES_COMMIT_SHA: 'TBA',
149
- CF_PAGES_URL: `http://${req.headers.host}`,
150
- ...bindingsEnv,
151
- ...vars,
152
- },
153
- cf: cf,
154
- waitUntil: (_promise) => {
155
- return;
156
- },
157
- caches: mfCache,
62
+ _localRuntime = getLocalRuntime(_config, runtimeMode, logger);
63
+ const bindings = await _localRuntime.getBindings();
64
+ const secrets = await _localRuntime.getSecrets();
65
+ const caches = await _localRuntime.getCaches();
66
+ const cf = await _localRuntime.getCF();
67
+ const clientLocalsSymbol = Symbol.for('astro.locals');
68
+ Reflect.set(req, clientLocalsSymbol, {
69
+ runtime: {
70
+ env: {
71
+ CF_PAGES_URL: `http://${req.headers.host}`,
72
+ ...bindings,
73
+ ...secrets,
158
74
  },
159
- });
160
- next();
161
- }
162
- catch {
163
- next();
164
- }
75
+ cf: cf,
76
+ caches: caches,
77
+ waitUntil: (_promise) => {
78
+ return;
79
+ },
80
+ },
81
+ });
82
+ next();
165
83
  });
166
84
  }
167
85
  },
168
86
  'astro:server:done': async ({ logger }) => {
169
- if (_mf) {
170
- logger.info('Cleaning up the Miniflare instance, and shutting down the workerd server.');
171
- await _mf.dispose();
87
+ if (_localRuntime) {
88
+ logger.info('Cleaning up the local Cloudflare runtime.');
89
+ await _localRuntime.dispose();
172
90
  }
173
91
  },
174
92
  'astro:build:setup': ({ vite, target }) => {
@@ -209,8 +127,7 @@ export default function createIntegration(args) {
209
127
  if (isModeDirectory) {
210
128
  await fs.promises.mkdir(functionsUrl, { recursive: true });
211
129
  }
212
- // TODO: remove _buildConfig.split in Astro 4.0
213
- if (isModeDirectory && (_buildConfig.split || functionPerRoute)) {
130
+ if (isModeDirectory && functionPerRoute) {
214
131
  const entryPointsURL = [..._entryPoints.values()];
215
132
  const entryPaths = entryPointsURL.map((entry) => fileURLToPath(entry));
216
133
  const outputUrl = new URL('$astro', _buildConfig.server);
@@ -390,11 +307,14 @@ export default function createIntegration(args) {
390
307
  /**
391
308
  * These route types are candiates for being part of the `_routes.json` `include` array.
392
309
  */
310
+ let notFoundIsSSR = false;
393
311
  const potentialFunctionRouteTypes = ['endpoint', 'page'];
394
312
  const functionEndpoints = routes
395
313
  // Certain route types, when their prerender option is set to false, run on the server as function invocations
396
314
  .filter((route) => potentialFunctionRouteTypes.includes(route.type) && !route.prerender)
397
315
  .map((route) => {
316
+ if (route.component === 'src/pages/404.astro' && route.prerender === false)
317
+ notFoundIsSSR = true;
398
318
  const includePattern = '/' +
399
319
  route.segments
400
320
  .flat()
@@ -499,7 +419,11 @@ export default function createIntegration(args) {
499
419
  const excludeStrategyLength = excludeStrategy
500
420
  ? excludeStrategy.include.length + excludeStrategy.exclude.length
501
421
  : Infinity;
502
- const winningStrategy = includeStrategyLength <= excludeStrategyLength ? includeStrategy : excludeStrategy;
422
+ const winningStrategy = notFoundIsSSR
423
+ ? excludeStrategy
424
+ : includeStrategyLength <= excludeStrategyLength
425
+ ? includeStrategy
426
+ : excludeStrategy;
503
427
  await fs.promises.writeFile(new URL('./_routes.json', _config.outDir), JSON.stringify({
504
428
  version: 1,
505
429
  ...winningStrategy,