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