Skip to content

Commit ff130e3

Browse files
committed
fix(service-worker): handle vercel images
1 parent 5aa09f9 commit ff130e3

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

src/app/src/service-worker.ts

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,26 @@ const IMAGE_EXTENSIONS = [
1919
'gif',
2020
]
2121
22+
function extractImagePath(pathname) {
23+
if (pathname.startsWith('/_ipx/_/')) {
24+
return pathname.replace('/_ipx/_', '')
25+
}
26+
27+
if (pathname.startsWith('/_vercel/image')) {
28+
try {
29+
return new URL(pathname, 'http://localhost').searchParams.get('url') || null
30+
} catch (error) {
31+
return null
32+
}
33+
}
34+
35+
if (IMAGE_EXTENSIONS.includes(pathname.split('.').pop())) {
36+
return pathname
37+
}
38+
39+
return null
40+
}
41+
2242
self.addEventListener('fetch', event => {
2343
const url = new URL(event.request.url);
2444
const isSameDomain = url.origin === self.location.origin;
@@ -27,19 +47,18 @@ self.addEventListener('fetch', event => {
2747
return event.respondWith(fetch(event.request));
2848
}
2949
30-
if (url.pathname.startsWith('/_ipx/_/') || IMAGE_EXTENSIONS.includes(url.pathname.split('.').pop())) {
31-
return event.respondWith(fetchFromIndexedDB(event, url));
50+
const imageUrl = extractImagePath(url.pathname);
51+
if (imageUrl) {
52+
return event.respondWith(fetchFromIndexedDB(event, imageUrl));
3253
}
3354
3455
event.respondWith(fetch(event.request))
3556
})
3657
3758
function fetchFromIndexedDB(event, url) {
38-
console.log('Fetching from IndexedDB:', url.pathname);
39-
const dbKey = ['public-assets:', url.pathname.replace(/^\\/+(_ipx\\/_\\/)?/, '').replace('/', ':')].join('')
59+
const dbKey = ['public-assets:', url.replace(/^\\//g, ':')].join('')
4060
return getData(dbKey).then(data => {
4161
if (!data) {
42-
console.log('No data found in IndexedDB:', url.pathname, dbKey);
4362
return fetch(event.request);
4463
}
4564

0 commit comments

Comments
 (0)