Clarify service worker cross-origin guard

This commit is contained in:
Scott Idem
2026-05-13 15:13:27 -04:00
parent 82430649db
commit 978a9a6960

View File

@@ -31,21 +31,26 @@ self.addEventListener('activate', (event) => {
}); });
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {
// ignore POST requests etc // Only handle same-origin GET requests for the app shell and static assets.
// Chromium can surface private-network/CORS failures on cross-origin API calls,
// so we intentionally leave those requests to the browser untouched here.
if (event.request.method !== 'GET') return; if (event.request.method !== 'GET') return;
if (!event.request.url.startsWith('http')) return; if (!event.request.url.startsWith('http')) return;
// Skip CDN/API/extension requests. This worker should only cache the app origin.
const request_url = new URL(event.request.url);
if (request_url.origin !== self.location.origin) return;
async function respond() { async function respond() {
const url = new URL(event.request.url);
const cache = await caches.open(CACHE); const cache = await caches.open(CACHE);
// `build`/`files` can always be served from the cache // App build assets and static files are safe to serve directly from cache.
if (ASSETS.includes(url.pathname)) { if (ASSETS.includes(request_url.pathname)) {
const cachedResponse = await cache.match(url.pathname); const cachedResponse = await cache.match(request_url.pathname);
if (cachedResponse) return cachedResponse; if (cachedResponse) return cachedResponse;
} }
// for everything else, try the network first, but fall back to the cache if we're offline // For same-origin runtime requests, prefer the network and fall back to cache if offline.
try { try {
const response = await fetch(event.request); const response = await fetch(event.request);