@harlan-zw/nuxt-cloudflare 0.0.4 → 0.0.5

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
@@ -12,7 +12,8 @@ The module extracts production patterns already proven in Nuxt SEO and gscdump.
12
12
  - Preview URLs disabled unless explicitly enabled
13
13
  - `workers_dev` disabled when a route proves the Worker remains reachable; workers without routes must choose explicitly
14
14
  - Version metadata binding at `CF_VERSION_METADATA`
15
- - Workers Caching explicitly disabled by default; opt-in requires a version-sharing decision
15
+ - Workers Caching enabled by default with per-version isolation
16
+ - Dynamic responses default to `private, no-store`; rendered HTML is forcibly private and conflicting page route rules fail the build
16
17
  - Smart Placement enabled by default; explicit region, host, or hostname placement is preserved
17
18
  - Source-map upload when the Nitro build emits maps; explicit `false` is preserved
18
19
  - Module-wide `secrets.required` names copied to each environment; source root secrets remain scoped to the root
@@ -31,7 +32,6 @@ export default defineNuxtConfig({
31
32
 
32
33
  nuxtCloudflare: {
33
34
  requiredSecrets: ['NUXT_SESSION_PASSWORD'],
34
- workersCache: { _tag: 'enabled', crossVersion: false },
35
35
  },
36
36
 
37
37
  nitro: {
@@ -58,7 +58,17 @@ export default defineNuxtConfig({
58
58
 
59
59
  Cloudflare KV requires TTLs of at least 60 seconds.
60
60
 
61
- Workers Caching is separate from Nitro's KV-backed cache. Enabling it lets Cloudflare serve responses without invoking the Worker. Keep `crossVersion: false` for deploy isolation; choose `true` only when stale responses across deployments are acceptable and a purge path exists. An authored `nitro.cloudflare.wrangler.cache` block is preserved unless `nuxtCloudflare.workersCache` is set; omitted `cross_version_cache` is normalized to `false`.
61
+ Workers Caching is separate from Nitro's KV-backed cache. It is enabled by default with `cross_version_cache: false`, so each deployment starts with an isolated cache. Dynamic Nitro responses default to `Cache-Control: private, no-store` and `Cloudflare-CDN-Cache-Control: no-store` unless they declare an explicit cache policy. Rendered HTML always receives those private directives; this is required because Cloudflare otherwise heuristically caches a `200` response with no cache header for two hours.
62
+
63
+ HTML-capable route rules fail the build when they use `cache`, `isr`, `swr`, or publicly cacheable `Cache-Control`, `CDN-Cache-Control`, and `Cloudflare-CDN-Cache-Control` headers. Explicit `private` and `no-store` policies are safe. API and static asset routes remain available for explicit caching. Disable Workers Caching only for a gateway that must execute on every request:
64
+
65
+ ```ts
66
+ export default defineNuxtConfig({
67
+ nuxtCloudflare: {
68
+ workersCache: { _tag: 'disabled' },
69
+ },
70
+ })
71
+ ```
62
72
 
63
73
  Smart Placement moves fetch handlers only when Cloudflare measures a faster location near upstream services. Assets-first delivery remains close to the user. Queue handlers, RPC methods, and named entrypoints are unaffected. An authored region, host, or hostname placement overrides the smart default.
64
74
 
@@ -187,7 +187,7 @@ const doctor = defineCommand({
187
187
  const main = defineCommand({
188
188
  meta: {
189
189
  name: "nuxt-cloudflare",
190
- version: "0.0.4",
190
+ version: "0.0.5",
191
191
  description: "Cloudflare deployment defaults and diagnostics for Nuxt"
192
192
  },
193
193
  subCommands: { doctor }
package/dist/module.d.mts CHANGED
@@ -35,6 +35,7 @@ interface NitroCloudflareShape {
35
35
  wrangler?: WranglerConfigInput;
36
36
  };
37
37
  preset?: string;
38
+ plugins?: string[];
38
39
  sourceMap?: boolean;
39
40
  storage?: Record<string, NitroStorageMount>;
40
41
  }
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.5.0"
6
6
  },
7
- "version": "0.0.4",
7
+ "version": "0.0.5",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -5,8 +5,76 @@ import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics
5
5
  import 'node:fs';
6
6
  import 'node:fs/promises';
7
7
 
8
+ const NON_HTML_ROUTE_PREFIXES = [
9
+ "/api",
10
+ "/_ipx",
11
+ "/_nuxt",
12
+ "/assets",
13
+ "/fonts",
14
+ "/images"
15
+ ];
16
+ const NON_HTML_EXTENSION_RE = /\.(?:avif|css|csv|gif|ico|jpe?g|js|json|map|md|mjs|pdf|png|svg|txt|webmanifest|webp|woff2?|xml)(?:$|[?*])/i;
17
+ const CACHE_HEADER_NAMES = /* @__PURE__ */ new Set([
18
+ "cache-control",
19
+ "cdn-cache-control",
20
+ "cloudflare-cdn-cache-control"
21
+ ]);
22
+ const CACHE_ROUTE_RULE_NAMES = ["cache", "isr", "swr"];
23
+ const PRIVATE_CACHE_DIRECTIVE_RE = /(?:^|,)\s*(?:no-store|private)\s*(?:,|$)/i;
24
+ function isRecord(value) {
25
+ return value !== null && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+ function isHtmlCapableRoute(route) {
28
+ if (NON_HTML_EXTENSION_RE.test(route))
29
+ return false;
30
+ return !NON_HTML_ROUTE_PREFIXES.some((prefix) => route === prefix || route.startsWith(`${prefix}/`));
31
+ }
32
+ function isPrivateCachePolicy(value) {
33
+ return typeof value === "string" && PRIVATE_CACHE_DIRECTIVE_RE.test(value);
34
+ }
35
+ function findHtmlCacheRouteRuleViolations(routeRules) {
36
+ if (!routeRules)
37
+ return [];
38
+ return Object.entries(routeRules).flatMap(([route, value]) => {
39
+ if (!isHtmlCapableRoute(route) || !isRecord(value))
40
+ return [];
41
+ const violations = [];
42
+ for (const name of CACHE_ROUTE_RULE_NAMES) {
43
+ if (value[name] !== void 0 && value[name] !== false) {
44
+ violations.push({
45
+ _tag: "html-cache-route-rule",
46
+ route,
47
+ configPath: `routeRules.${route}.${name}`
48
+ });
49
+ }
50
+ }
51
+ if (!isRecord(value.headers))
52
+ return violations;
53
+ for (const name of Object.keys(value.headers)) {
54
+ if (CACHE_HEADER_NAMES.has(name.toLowerCase()) && !isPrivateCachePolicy(value.headers[name])) {
55
+ violations.push({
56
+ _tag: "html-cache-header",
57
+ route,
58
+ configPath: `routeRules.${route}.headers.${name}`
59
+ });
60
+ }
61
+ }
62
+ return violations;
63
+ });
64
+ }
65
+ function formatHtmlCacheRouteRuleViolations(violations) {
66
+ return violations.map((violation) => `${violation.configPath}: Workers Caching requires HTML responses to remain private and no-store.`).join("\n");
67
+ }
68
+
8
69
  const logger = useLogger("nuxt-cloudflare");
9
70
  const cacheDriverPath = resolve(import.meta.dirname, import.meta.url.endsWith(".ts") ? "storage.ts" : "storage.mjs");
71
+ const workersCachePluginPath = resolve(
72
+ import.meta.dirname,
73
+ import.meta.url.endsWith(".ts") ? "runtime/server/plugins/workers-cache.ts" : "runtime/server/plugins/workers-cache.js"
74
+ );
75
+ function resolveModuleWorkersCachePolicy(options) {
76
+ return options.workersCache ?? { _tag: "enabled", crossVersion: false };
77
+ }
10
78
  function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
11
79
  nitro.preset ??= "cloudflare-module";
12
80
  nitro.cloudflare ??= {};
@@ -19,8 +87,13 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
19
87
  tracesSampleRate: options.tracesSampleRate,
20
88
  uploadSourceMaps: options.sourceMaps ?? nitro.sourceMap ?? nuxtServerSourceMaps ?? false,
21
89
  versionMetadataBinding: options.versionMetadataBinding,
22
- workersCache: options.workersCache
90
+ workersCache: resolveModuleWorkersCachePolicy(options)
23
91
  });
92
+ if (nitro.cloudflare.wrangler.cache?.enabled) {
93
+ nitro.plugins ??= [];
94
+ if (!nitro.plugins.includes(workersCachePluginPath))
95
+ nitro.plugins.push(workersCachePluginPath);
96
+ }
24
97
  if (options.kvCache === false)
25
98
  return;
26
99
  const cache = nitro.storage?.cache;
@@ -75,6 +148,17 @@ function setupCloudflareModule(options, nuxt) {
75
148
  nuxt.hook("modules:done", () => {
76
149
  configure();
77
150
  });
151
+ nuxt.hook("nitro:config", (nitroConfig) => {
152
+ if (resolveModuleWorkersCachePolicy(options)._tag === "disabled")
153
+ return;
154
+ const violations = findHtmlCacheRouteRuleViolations(nitroConfig.routeRules);
155
+ if (violations.length > 0) {
156
+ throw new Error(
157
+ `[nuxt-cloudflare] HTML route rules conflict with Workers Caching:
158
+ ${formatHtmlCacheRouteRuleViolations(violations)}`
159
+ );
160
+ }
161
+ });
78
162
  if (!nuxt.options.dev) {
79
163
  nuxt.hook("nitro:init", (nitro) => {
80
164
  nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(nitro, options, nuxt.options.rootDir));
@@ -93,7 +177,8 @@ const module$1 = defineNuxtModule({
93
177
  doctor: { _tag: "advisory" },
94
178
  logsSampleRate: 0.1,
95
179
  tracesSampleRate: 0.01,
96
- versionMetadataBinding: "CF_VERSION_METADATA"
180
+ versionMetadataBinding: "CF_VERSION_METADATA",
181
+ workersCache: { _tag: "enabled", crossVersion: false }
97
182
  },
98
183
  setup: setupCloudflareModule
99
184
  });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack").NitroAppPlugin;
2
+ export default _default;
@@ -0,0 +1,14 @@
1
+ import { getResponseHeader, setResponseHeader } from "h3";
2
+ import { defineNitroPlugin } from "nitropack/runtime";
3
+ import { hasExplicitCachePolicy, withHtmlNoStoreHeaders } from "../utils/workers-cache.js";
4
+ export default defineNitroPlugin((nitroApp) => {
5
+ nitroApp.hooks.hook("render:response", (response) => {
6
+ response.headers = withHtmlNoStoreHeaders(response.headers);
7
+ });
8
+ nitroApp.hooks.hook("beforeResponse", (event) => {
9
+ if (hasExplicitCachePolicy((name) => getResponseHeader(event, name)))
10
+ return;
11
+ setResponseHeader(event, "cache-control", "private, no-store");
12
+ setResponseHeader(event, "cloudflare-cdn-cache-control", "no-store");
13
+ });
14
+ });
@@ -0,0 +1,2 @@
1
+ export declare function hasExplicitCachePolicy(getHeader: (name: string) => unknown): boolean;
2
+ export declare function withHtmlNoStoreHeaders(headers?: Record<string, string>): Record<string, string>;
@@ -0,0 +1,20 @@
1
+ const CACHE_POLICY_HEADER_NAMES = [
2
+ "cache-control",
3
+ "cdn-cache-control",
4
+ "cloudflare-cdn-cache-control",
5
+ "expires"
6
+ ];
7
+ const HTML_CACHE_HEADER_NAMES = new Set(CACHE_POLICY_HEADER_NAMES.slice(0, 3));
8
+ export function hasExplicitCachePolicy(getHeader) {
9
+ return CACHE_POLICY_HEADER_NAMES.some((name) => Boolean(getHeader(name)));
10
+ }
11
+ export function withHtmlNoStoreHeaders(headers = {}) {
12
+ const preserved = Object.fromEntries(
13
+ Object.entries(headers).filter(([name]) => !HTML_CACHE_HEADER_NAMES.has(name.toLowerCase()))
14
+ );
15
+ return {
16
+ ...preserved,
17
+ "cache-control": "private, no-store",
18
+ "cloudflare-cdn-cache-control": "no-store"
19
+ };
20
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.0.4",
4
+ "version": "0.0.5",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -87,6 +87,8 @@
87
87
  "@nuxt/kit": "^4.5.2",
88
88
  "citty": "^0.2.2",
89
89
  "consola": "^3.4.2",
90
+ "h3": "2.0.1-rc.25",
91
+ "nitropack": "^2.13.4",
90
92
  "pathe": "^2.0.3",
91
93
  "unstorage": "^1.17.5"
92
94
  },