Another try to fix service worker bypassing cache
All checks were successful
Build Docker image / build (push) Successful in 1m28s
Build Docker image / deploy (push) Successful in 4s
Build Docker image / verify (push) Successful in 56s

This commit is contained in:
Roman Krček
2025-09-03 10:52:48 +02:00
parent c881d660e2
commit 28fc22fcd8

View File

@@ -16,7 +16,7 @@ self.addEventListener('install', (event: ExtendableEvent) => {
await cache.addAll(ASSETS); await cache.addAll(ASSETS);
}; };
console.log("[SW] Installing new service worker"); console.log(`[SW] Installing new service worker, cache name: ${CACHE}`);
event.waitUntil(addFilesToCache()); event.waitUntil(addFilesToCache());
self.skipWaiting(); self.skipWaiting();
@@ -37,34 +37,29 @@ self.addEventListener('activate', (event: ExtendableEvent) => {
self.addEventListener('fetch', (event: FetchEvent) => { self.addEventListener('fetch', (event: FetchEvent) => {
if (event.request.method !== 'GET') return; if (event.request.method !== 'GET') return;
const url = new URL(event.request.url); // For navigation requests, always fetch from the network to ensure
// server-side authentication checks are performed.
// Never cache private routes if (event.request.mode === 'navigate') {
if (url.pathname.startsWith('/private')) {
event.respondWith(fetch(event.request)); event.respondWith(fetch(event.request));
return; return;
} }
// For other requests (e.g., static assets), use a cache-first strategy.
const respond = async () => { const respond = async () => {
const cache = await caches.open(CACHE); const cache = await caches.open(CACHE);
if (ASSETS.includes(url.pathname)) { const cachedResponse = await cache.match(event.request);
const cached = await cache.match(url.pathname); if (cachedResponse) {
if (cached) return cached; return cachedResponse;
} }
try { try {
const response = await fetch(event.request); return await fetch(event.request);
if (response.status === 200 && build.length > 0 && url.pathname.startsWith(`/${build[0]}/`)) {
cache.put(event.request, response.clone());
}
return response;
} catch { } catch {
const cached = await cache.match(event.request); // If the network fails, and it's not in the cache, it will fail,
if (cached) return cached; // which is the expected behavior for non-navigation requests.
return new Response('Not found', { status: 404 });
} }
return new Response('Not found', { status: 404 });
}; };
event.respondWith(respond()); event.respondWith(respond());