nuxt-skew-protection 1.5.2 → 1.5.3

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
@@ -4,32 +4,32 @@
4
4
  [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
5
  [![Nuxt][nuxt-src]][nuxt-href]
6
6
 
7
- > Solve Nuxt version skew with persistent assets and instant updates.
7
+ > Keep old build assets available and notify users when their app needs an update.
8
8
 
9
9
  ## Why Nuxt Skew Protection?
10
10
 
11
- **Version skew** is a mismatch between your deployed build and the chunks running in user browsers and crawler sessions. It can lead to several issues:
11
+ **Version skew** happens when a browser or crawler still uses chunks from an older deployment. You may see:
12
12
 
13
- - 🕷️ **Crawlers 404 on stale chunks** - Googlebot requests `_nuxt/builds/abc123.js` which no longer exists post-deploy, logging 500s and potentially impacting indexing
14
- - 💥 **ChunkLoadError in production** - Users mid-session get `Failed to fetch dynamically imported module` when navigating to routes with invalidated chunks
15
- - 🔄 **Delayed rollout** - Your latest release sits unloaded until users hard refresh, sometimes hours or days later
13
+ - 🕷️ **Crawlers 404 on stale chunks**: Googlebot requests a chunk that no longer exists after deployment.
14
+ - 💥 **ChunkLoadError in production**: Users see `Failed to fetch dynamically imported module` when a route needs a deleted chunk.
15
+ - 🔄 **Delayed rollout**: Users keep running an old version until they refresh.
16
16
 
17
- Nuxt's built-in behavior (hard-reload when it detects a new deployment) helps, but in many cases it's [not enough](https://github.com/nuxt/nuxt/issues/29624).
17
+ Nuxt can reload the page after detecting a new deployment. It still has [limits](https://github.com/nuxt/nuxt/issues/29624).
18
18
 
19
- Nuxt Skew Protection solves this with proactive update prompts and persistent build assets across deploys.
19
+ Nuxt Skew Protection keeps previous build assets available across deployments and provides update notification logic.
20
20
 
21
21
  ## Features
22
22
 
23
- - 🕷️ **Persistent Build Assets** - Previous build artifacts remain accessible, so crawlers and stale sessions never hit dead ends.
24
- - ⚡ **Instant Update Prompts** - Zero-config real-time notifications on deploy. Users adopt your latest build immediately.
25
- - 🎯 **Chunk-Aware Targeting** - Notifications fire only when the user's loaded chunks are invalidated. No noise for unrelated updates.
26
- - 🎨 **Headless UI** - Drop-in notification component with first-class Nuxt UI support.
27
- - 📊 **Live Connection Monitoring** - Track active users and version distribution in real-time for admin dashboards and rollout progress.
28
- - 🔌 **Third-Party Adapters** - Real-time updates on any platform (including static sites) via [Pusher](https://pusher.com) or [Ably](https://ably.com).
23
+ - 🕷️ **Persistent Build Assets**: Keep previous build assets available for crawlers and users on old versions.
24
+ - ⚡ **Instant Update Prompts**: Detect deployments through polling, SSE, WebSockets, or an external provider.
25
+ - 🎯 **Chunk-Aware Targeting**: Prompt users when a deployment invalidates their loaded chunks.
26
+ - 🎨 **Headless UI**: Use the headless notification component with your own template or a Nuxt UI example.
27
+ - 📊 **Live Connection Monitoring**: Track active users and version distribution in real-time for admin dashboards and rollout progress.
28
+ - 🔌 **Third-Party Adapters**: Real-time updates on any platform (including static sites) via [Pusher](https://pusher.com) or [Ably](https://ably.com).
29
29
 
30
30
  ## Installation
31
31
 
32
- Install `nuxt-skew-protection` dependency to your project:
32
+ Add `nuxt-skew-protection` to your project:
33
33
 
34
34
  ```bash
35
35
  npx nuxi@latest module add nuxt-skew-protection
@@ -43,7 +43,7 @@ npx nuxi@latest module add nuxt-skew-protection
43
43
 
44
44
  ## Documentation
45
45
 
46
- [📖 Read the full documentation](https://nuxtseo.com/skew-protection) for more information.
46
+ [📖 Read the documentation](https://nuxtseo.com/skew-protection).
47
47
 
48
48
  ## Sponsors
49
49
 
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "nuxt": ">=4.0.0"
5
5
  },
6
6
  "configKey": "skewProtection",
7
- "version": "1.5.2",
7
+ "version": "1.5.3",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -464,11 +464,7 @@ async function getVersionManifest(storage) {
464
464
  return manifest;
465
465
  return emptyManifest;
466
466
  }).catch((e) => {
467
- const message = e instanceof Error ? e.message : String(e);
468
- const cause = e instanceof Error ? e.cause?.message || "" : "";
469
- if (cause.includes("ENOTFOUND") || cause.includes("ECONNREFUSED") || message.includes("401") || message === "fetch failed")
470
- throw formatStorageError(e, "read");
471
- return emptyManifest;
467
+ throw formatStorageError(e, "read");
472
468
  });
473
469
  }
474
470
  async function setVersionManifest(manifest, storage) {
@@ -643,10 +639,7 @@ function createAssetManager(options) {
643
639
  return;
644
640
  }
645
641
  const assetPath = join$1(publicDir, asset);
646
- const assetData = await promises.readFile(assetPath).catch((error) => {
647
- logger.debug(`Failed to read ${assetPath}: ${error}`);
648
- return null;
649
- });
642
+ const assetData = await promises.readFile(assetPath);
650
643
  if (assetData) {
651
644
  totalBytes += assetData.byteLength;
652
645
  const storageKey = `${buildId}/${asset}`;
@@ -690,7 +683,7 @@ function createAssetManager(options) {
690
683
  createdAt: new Date(data.timestamp).getTime()
691
684
  }));
692
685
  }
693
- async function restoreOldAssetsToPublic(currentBuildId, publicDir, currentAssets = [], isExistingVersion = false) {
686
+ async function restoreOldAssetsToPublic(currentBuildId, publicDir, currentAssets = []) {
694
687
  const startTime = Date.now();
695
688
  logger.debug(`restoreOldAssetsToPublic: starting for ${currentBuildId}`);
696
689
  const manifestStart = Date.now();
@@ -700,10 +693,6 @@ function createAssetManager(options) {
700
693
  logger.debug(`restoreOldAssetsToPublic: no manifest or versions, skipping`);
701
694
  return;
702
695
  }
703
- if (isExistingVersion) {
704
- logger.debug(`restoreOldAssetsToPublic: build ${currentBuildId} already exists, skipping restore`);
705
- return;
706
- }
707
696
  const versionCount = Object.keys(manifest.versions).length - 1;
708
697
  logger.debug(`restoreOldAssetsToPublic: checking ${versionCount} previous versions`);
709
698
  const restoredAssets = [];
@@ -975,7 +964,7 @@ const module$1 = defineNuxtModule({
975
964
  addTypeTemplate({
976
965
  filename: "types/nuxt-skew-protection.d.ts",
977
966
  getContents: () => `// Generated by nuxt-skew-protection
978
- import type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEConfig, SkewWebSocketConfig } from '#skew-protection/app/types'
967
+ import type { ChunksOutdatedPayload, SkewAdapterConfig, SkewConnection, SkewSSEConfig, SkewVersionDetection, SkewWebSocketConfig } from '#skew-protection/app/types'
979
968
 
980
969
  declare module '#app' {
981
970
  interface RuntimeNuxtHooks {
@@ -988,6 +977,7 @@ declare module '#app' {
988
977
  interface NuxtApp {
989
978
  $skewConnection?: SkewConnection
990
979
  _skewStatsSubscribed?: boolean
980
+ _skewVersionDetection?: SkewVersionDetection
991
981
  }
992
982
  interface NuxtAppManifestMeta {
993
983
  skewProtection?: {
@@ -1012,6 +1002,7 @@ declare module 'nuxt/app' {
1012
1002
  interface NuxtApp {
1013
1003
  $skewConnection?: SkewConnection
1014
1004
  _skewStatsSubscribed?: boolean
1005
+ _skewVersionDetection?: SkewVersionDetection
1015
1006
  }
1016
1007
  interface NuxtAppManifestMeta {
1017
1008
  skewProtection?: {
@@ -1269,7 +1260,7 @@ export {}
1269
1260
  driver: await resolveBuildTimeDriver(options.storage)
1270
1261
  });
1271
1262
  const assets = await assetManager.getAssetsFromBuild(publicDir);
1272
- const { isExistingVersion } = await assetManager.updateVersionsManifest(buildId, assets);
1263
+ await assetManager.updateVersionsManifest(buildId, assets);
1273
1264
  if (options.bundleAssets) {
1274
1265
  const manifest = await assetManager.getManifest();
1275
1266
  const totalReleases = Object.keys(manifest.versions).length;
@@ -1302,7 +1293,7 @@ export {}
1302
1293
  }
1303
1294
  logger.log(`Restoring build files from ${versionCount} release${versionCount > 1 ? "s" : ""} (${totalAssets} assets) [${versionSizes.join(", ")}]...`);
1304
1295
  }
1305
- await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets, isExistingVersion);
1296
+ await assetManager.restoreOldAssetsToPublic(buildId, publicDir, assets);
1306
1297
  }
1307
1298
  await assetManager.augmentBuildMetadata(buildId, publicDir);
1308
1299
  });
@@ -1,6 +1,6 @@
1
1
  <script setup>
2
2
  import { useTimeAgo } from "@vueuse/core";
3
- import { reloadNuxtApp, useNuxtApp } from "nuxt/app";
3
+ import { reloadNuxtApp, useNuxtApp, useState } from "nuxt/app";
4
4
  import { computed, ref } from "vue";
5
5
  import { useSkewProtection } from "../composables/useSkewProtection";
6
6
  defineOptions({
@@ -17,7 +17,12 @@ const isOnline = skewProtection.isOnline;
17
17
  const chunksOutdated = ref(false);
18
18
  const appOutdated = ref(false);
19
19
  const outdatedPayload = ref(null);
20
- const dismissed = ref(false);
20
+ const dismissedUpdate = useState("skew-dismissed-update", () => void 0);
21
+ const updateKey = computed(() => JSON.stringify([
22
+ skewProtection.manifest.value?.id ?? version,
23
+ outdatedPayload.value?.passedReleases.at(-1)
24
+ ]));
25
+ const dismissed = computed(() => dismissedUpdate.value === updateKey.value);
21
26
  skewProtection.onCurrentChunksOutdated((payload) => {
22
27
  chunksOutdated.value = true;
23
28
  outdatedPayload.value = payload;
@@ -56,8 +61,7 @@ const timeAgo = useTimeAgo(releaseTimestamp, {
56
61
  showSecond: true
57
62
  });
58
63
  function handleDismiss() {
59
- dismissed.value = true;
60
- chunksOutdated.value = false;
64
+ dismissedUpdate.value = updateKey.value;
61
65
  emit("dismiss");
62
66
  }
63
67
  async function handleReload() {
@@ -12,58 +12,78 @@ export function useSkewProtection(options = {}) {
12
12
  const isConnected = useState("skew-connected", () => false);
13
13
  const serverVersion = useState("skew-server-version", () => void 0);
14
14
  const manifest = useState("skew-manifest", () => void 0);
15
- let lastDetectedServerVersion;
16
- let lastProcessedManifestId;
15
+ const chunks = useState("skew-outdated-chunks", () => void 0);
16
+ const firstConsumer = !nuxtApp._skewVersionDetection;
17
+ const detection = nuxtApp._skewVersionDetection ??= {
18
+ lastDetectedServerVersion: void 0,
19
+ inFlight: void 0,
20
+ queue: createBackoffQueue({
21
+ delays: [0, 5e3, 3e4, 3e5],
22
+ onTick: () => nuxtApp.runWithContext(checkForUpdates)
23
+ })
24
+ };
17
25
  async function checkForUpdates() {
18
26
  if (import.meta.client && !useOnline().value)
19
27
  return;
20
- const meta = await $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
28
+ detection.inFlight ??= $fetch(`${buildAssetsURL("builds/latest.json")}?${Date.now()}`).catch(() => {
21
29
  return null;
30
+ }).finally(() => {
31
+ detection.inFlight = void 0;
22
32
  });
23
- if (meta && meta.id !== clientVersion && meta.id !== lastProcessedManifestId) {
24
- lastProcessedManifestId = meta.id;
25
- queue.clear();
26
- await nuxtApp.hooks.callHook("app:manifest:update", meta);
33
+ const meta = await detection.inFlight;
34
+ if (meta && meta.id !== clientVersion) {
35
+ detection.queue.clear();
36
+ if (meta.id !== manifest.value?.id) {
37
+ manifest.value = meta;
38
+ await nuxtApp.hooks.callHook("app:manifest:update", meta);
39
+ } else if (!manifest.value.skewProtection && meta.skewProtection) {
40
+ manifest.value = meta;
41
+ await nuxtApp.hooks.callHook("app:manifest:update", meta);
42
+ }
27
43
  }
28
44
  }
29
- const queue = createBackoffQueue({
30
- delays: [0, 5e3, 3e4, 3e5],
31
- onTick: () => nuxtApp.runWithContext(checkForUpdates)
32
- });
33
45
  if (!lazy) {
34
- onMounted(() => {
35
- nuxtApp.$skewConnection?.connect();
46
+ onMounted(connect);
47
+ }
48
+ if (firstConsumer) {
49
+ nuxtApp.hooks.hook("app:manifest:update", (meta) => {
50
+ if (!meta || meta.id === manifest.value?.id)
51
+ return;
52
+ manifest.value = meta;
53
+ });
54
+ nuxtApp.hooks.hook("skew:chunks-outdated", (payload) => {
55
+ chunks.value = payload;
56
+ });
57
+ nuxtApp.hooks.hook("skew:message", (msg) => {
58
+ if (msg.type !== SKEW_MESSAGE_TYPE.VERSION && msg.type !== SKEW_MESSAGE_TYPE.CONNECTED)
59
+ return;
60
+ if (msg.version)
61
+ serverVersion.value = msg.version;
62
+ if (!msg.version || msg.version === clientVersion)
63
+ return;
64
+ if (msg.version === detection.lastDetectedServerVersion && (detection.queue.isRunning() || msg.version === manifest.value?.id))
65
+ return;
66
+ detection.lastDetectedServerVersion = msg.version;
67
+ logger.debug(`[SkewProtection] Version mismatch (${msg.version} !== ${clientVersion}), starting backoff checks`);
68
+ detection.queue.start();
36
69
  });
37
70
  }
38
- nuxtApp.hooks.hook("skew:message", (msg) => {
39
- if (msg.type !== SKEW_MESSAGE_TYPE.VERSION && msg.type !== SKEW_MESSAGE_TYPE.CONNECTED)
40
- return;
41
- if (msg.version) {
42
- serverVersion.value = msg.version;
43
- }
44
- if (!msg.version || msg.version === clientVersion)
45
- return;
46
- if (msg.version === lastDetectedServerVersion)
47
- return;
48
- lastDetectedServerVersion = msg.version;
49
- logger.debug(`[SkewProtection] Version mismatch (${msg.version} !== ${clientVersion}), starting backoff checks`);
50
- queue.start();
51
- });
52
71
  function connect() {
53
- if (!import.meta.client || isConnected.value)
72
+ if (!import.meta.client || isConnected.value || !nuxtApp.$skewConnection)
54
73
  return;
55
- isConnected.value = true;
56
- nuxtApp.$skewConnection?.connect();
74
+ nuxtApp.$skewConnection.connect();
57
75
  }
58
76
  function disconnect() {
59
77
  if (!import.meta.client || !isConnected.value)
60
78
  return;
61
- isConnected.value = false;
62
- queue.clear();
79
+ detection.queue.clear();
63
80
  nuxtApp.$skewConnection?.disconnect();
64
81
  }
65
82
  function onCurrentChunksOutdated(callback) {
66
83
  const hook = nuxtApp.hooks.hook("skew:chunks-outdated", callback);
84
+ if (chunks.value) {
85
+ Promise.resolve(callback(chunks.value)).catch((error) => logger.error("Chunk update callback failed", error));
86
+ }
67
87
  onUnmounted(() => {
68
88
  if (typeof hook === "function") {
69
89
  hook();
@@ -72,10 +92,10 @@ export function useSkewProtection(options = {}) {
72
92
  return hook;
73
93
  }
74
94
  function onAppOutdated(callback) {
75
- const hook = nuxtApp.hooks.hook("app:manifest:update", (_manifest) => {
76
- manifest.value = _manifest;
77
- callback(_manifest);
78
- });
95
+ const hook = nuxtApp.hooks.hook("app:manifest:update", callback);
96
+ if (manifest.value && manifest.value.id !== clientVersion) {
97
+ Promise.resolve(callback(manifest.value)).catch((error) => logger.error("App update callback failed", error));
98
+ }
79
99
  onUnmounted(() => {
80
100
  if (typeof hook === "function") {
81
101
  hook();
@@ -39,20 +39,18 @@ export default defineNuxtPlugin({
39
39
  }
40
40
  if (config.multiTab === false || typeof BroadcastChannel === "undefined")
41
41
  return;
42
- const channel = new BroadcastChannel(CHANNEL_NAME);
43
- let receivedFromChannel = false;
42
+ const channel = new BroadcastChannel(`${CHANNEL_NAME}:${config.basePath || "/__skew"}`);
43
+ const receivedFromChannel = /* @__PURE__ */ new WeakSet();
44
44
  const stopBroadcasting = nuxtApp.hooks.hook("app:manifest:update", (manifest) => {
45
- if (receivedFromChannel) {
46
- receivedFromChannel = false;
45
+ if (!manifest || receivedFromChannel.has(manifest))
47
46
  return;
48
- }
49
47
  logger.debug("[MultiTab] Broadcasting version update to other tabs");
50
- channel.postMessage({ type: "version-update", id: manifest?.id, timestamp: manifest?.timestamp });
48
+ channel.postMessage({ ...manifest, type: "version-update" });
51
49
  });
52
50
  channel.onmessage = (event) => {
53
51
  if (event.data?.type === "version-update" && event.data.id) {
54
52
  logger.debug("[MultiTab] Received version update from another tab");
55
- receivedFromChannel = true;
53
+ receivedFromChannel.add(event.data);
56
54
  nuxtApp.hooks.callHook("app:manifest:update", event.data);
57
55
  }
58
56
  };
@@ -156,8 +156,6 @@ export default defineNuxtPlugin({
156
156
  await new Promise((resolve) => setTimeout(resolve, 100));
157
157
  await checkDeletedChunks(allDeletedChunks, passedReleases);
158
158
  }
159
- logger.debug("[SW] Resetting modules in service worker");
160
- swRegistration.then((reg) => reg.active?.postMessage({ type: "RESET_MODULES" }));
161
159
  });
162
160
  }
163
161
  });
@@ -1,5 +1,7 @@
1
1
  import type { UseEventSourceOptions, UseWebSocketOptions } from '@vueuse/core';
2
+ import type { NuxtAppManifestMeta } from 'nuxt/app';
2
3
  import type { Ref } from 'vue';
4
+ import type { BackoffQueue } from './utils/backoff-queue.js';
3
5
  export interface SkewWebSocketConfig {
4
6
  url: string;
5
7
  options: UseWebSocketOptions;
@@ -26,3 +28,9 @@ export interface SkewConnection {
26
28
  buildId: string;
27
29
  cookie?: Ref<string | null | undefined>;
28
30
  }
31
+ /** Detection work belongs to the app, independently of mounted consumers. */
32
+ export interface SkewVersionDetection {
33
+ queue: BackoffQueue;
34
+ lastDetectedServerVersion: string | undefined;
35
+ inFlight: Promise<NuxtAppManifestMeta | null> | undefined;
36
+ }
@@ -8,7 +8,11 @@ export function createBackoffQueue(options) {
8
8
  const start = () => {
9
9
  clear();
10
10
  delays.forEach((delay, i) => {
11
- timers.push(setTimeout(onTick, delay, i));
11
+ const timer = setTimeout(() => {
12
+ timers = timers.filter((pending) => pending !== timer);
13
+ onTick(i);
14
+ }, delay);
15
+ timers.push(timer);
12
16
  });
13
17
  };
14
18
  const isRunning = () => timers.length > 0;
@@ -1,4 +1,4 @@
1
- import { useCookie, useNuxtApp, useRuntimeConfig } from "nuxt/app";
1
+ import { useCookie, useNuxtApp, useRuntimeConfig, useState } from "nuxt/app";
2
2
  import { useBotDetection } from "#imports";
3
3
  import { SKEW_MESSAGE_TYPE } from "../../const.js";
4
4
  import { init, logger } from "../../shared/logger.js";
@@ -9,6 +9,8 @@ export function createSkewConnection(config) {
9
9
  const buildId = runtimeConfig.app.buildId;
10
10
  init();
11
11
  const { isBot } = useBotDetection();
12
+ const isConnected = useState("skew-connected", () => false);
13
+ isConnected.value = false;
12
14
  const basePath = runtimeConfig.public.skewProtection.basePath || "/__skew";
13
15
  const cookieConfig = runtimeConfig.public.skewProtection.cookie;
14
16
  const cookie = cookieConfig === false ? void 0 : (() => {
@@ -29,7 +31,6 @@ export function createSkewConnection(config) {
29
31
  }
30
32
  let cleanup;
31
33
  let sendFn;
32
- let isConnected = false;
33
34
  let connectionId;
34
35
  const handleMessage = (msg) => {
35
36
  logger.debug(`[${name}] Received message:`, msg.type);
@@ -39,11 +40,11 @@ export function createSkewConnection(config) {
39
40
  nuxtApp.hooks.callHook("skew:message", msg);
40
41
  };
41
42
  const connect = () => {
42
- if (isConnected)
43
+ if (isConnected.value)
43
44
  return;
44
- isConnected = true;
45
45
  logger.debug(`[${name}] Connecting`);
46
46
  const result = setup(handleMessage);
47
+ isConnected.value = true;
47
48
  if (result && typeof result === "object") {
48
49
  cleanup = result.cleanup;
49
50
  sendFn = result.send;
@@ -52,19 +53,23 @@ export function createSkewConnection(config) {
52
53
  }
53
54
  };
54
55
  const disconnect = () => {
55
- if (!isConnected)
56
+ if (!isConnected.value)
56
57
  return;
57
- isConnected = false;
58
+ isConnected.value = false;
58
59
  logger.debug(`[${name}] Disconnecting`);
59
- cleanup?.();
60
+ const close = cleanup;
61
+ cleanup = void 0;
62
+ sendFn = void 0;
63
+ connectionId = void 0;
64
+ close?.();
60
65
  };
61
66
  const send = (data) => {
62
- if (!isConnected || !sendFn)
67
+ if (!isConnected.value || !sendFn)
63
68
  return;
64
69
  sendFn(data);
65
70
  };
66
71
  const sendRoute = (route) => {
67
- if (!isConnected)
72
+ if (!isConnected.value)
68
73
  return;
69
74
  if (sendFn) {
70
75
  sendFn({ type: "route-update", route });
@@ -79,7 +84,7 @@ export function createSkewConnection(config) {
79
84
  }
80
85
  };
81
86
  const subscribeStats = () => {
82
- if (!isConnected || !connectionId)
87
+ if (!isConnected.value || !connectionId)
83
88
  return;
84
89
  if (sendFn) {
85
90
  sendFn({ type: SKEW_MESSAGE_TYPE.SUBSCRIBE_STATS });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-skew-protection",
3
3
  "type": "module",
4
- "version": "1.5.2",
4
+ "version": "1.5.3",
5
5
  "description": "Solve Nuxt version skews with persistent assets and instant updates.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",