From 8daac4cdd1ba35ae5a4cb4eb9ed0cc214f0182ab Mon Sep 17 00:00:00 2001 From: Pranav Date: Sat, 10 Jan 2026 20:13:39 -0800 Subject: [PATCH] fix: Construct CDN asset URLs correctly with protocol and path - Add https:// protocol to ASSET_CDN_HOST if missing - Include asset path (/vite/) when constructing CDN URLs - Fix URL: https://cdn.example.com/vite/assets/file.css Co-Authored-By: Claude Opus 4.5 --- app/javascript/service-worker/build.js | 6 +++++- app/javascript/service-worker/sw-runtime.js | 10 ++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/app/javascript/service-worker/build.js b/app/javascript/service-worker/build.js index e4e087572..3eae2a591 100644 --- a/app/javascript/service-worker/build.js +++ b/app/javascript/service-worker/build.js @@ -56,7 +56,11 @@ function generateAssetManifest() { async function buildServiceWorker() { console.log('🔨 Building service worker...'); - const assetOrigin = process.env.ASSET_CDN_HOST || ''; + // Ensure CDN host has protocol prefix for absolute URLs + let assetOrigin = process.env.ASSET_CDN_HOST || ''; + if (assetOrigin && !assetOrigin.startsWith('http')) { + assetOrigin = `https://${assetOrigin}`; + } const isProduction = process.env.NODE_ENV === 'production'; // vite-plugin-ruby serves from /vite/ in production, /vite-dev/ in development const assetPath = isProduction ? '/vite/' : '/vite-dev/'; diff --git a/app/javascript/service-worker/sw-runtime.js b/app/javascript/service-worker/sw-runtime.js index 695bbde55..9fa7a9c2c 100644 --- a/app/javascript/service-worker/sw-runtime.js +++ b/app/javascript/service-worker/sw-runtime.js @@ -123,7 +123,10 @@ async function prefetchAssets() { if (!ASSET_MANIFEST?.length) return; const cache = await caches.open(CACHE_NAME); - const baseUrl = ASSET_ORIGIN || `${self.location.origin}${ASSET_PATH}`; + // Build base URL: CDN origin + asset path, or local origin + asset path + const baseUrl = ASSET_ORIGIN + ? `${ASSET_ORIGIN}${ASSET_PATH}` + : `${self.location.origin}${ASSET_PATH}`; // Prefetch in batches of 5 (await in loop is intentional for throttling) for (let i = 0; i < ASSET_MANIFEST.length; i += 5) { @@ -171,7 +174,10 @@ async function cleanupStaleAssets() { const cache = await caches.open(CACHE_NAME); const cachedRequests = await cache.keys(); - const baseUrl = ASSET_ORIGIN || `${self.location.origin}${ASSET_PATH}`; + // Build base URL: CDN origin + asset path, or local origin + asset path + const baseUrl = ASSET_ORIGIN + ? `${ASSET_ORIGIN}${ASSET_PATH}` + : `${self.location.origin}${ASSET_PATH}`; // Build set of valid asset URLs from current manifest const validUrls = new Set(