Noampz
Noampz

Reputation: 1205

workbox 3 - ignore URL params on run-time caching

I want to cache assets from a secure CDN that uses policy token as URL params. for example: www.cdn.com/image.png?Policy=AAAAA&Key-Pair-Id=BBBBB and if I re-visit the site, I want to get the asset from the cache even if I have a different policy token and Key-Pair-Id. for example: www.cdn.com/image.png?Policy=CCCCC&Key-Pair-Id=DDDDD

If I use this code in the service worker:

workbox.routing.registerRoute(
    /^(http(s)?:)?\/\/www\.cdn\.com.*/,
    workbox.strategies.staleWhileRevalidate()
);

It doesn't find the response in the cache and goes to the network. I want it to match by the URL without the URL params (even if Policy=CCCCC&Key-Pair-Id=DDDDD is not actually a valid policy). just look if www.cdn.com/image.png exists and retrieve it.

Upvotes: 0

Views: 1211

Answers (1)

Noampz
Noampz

Reputation: 1205

I found a solution for this by using a custom handler:

workbox.routing.registerRoute(
    /^(http(s)?:)?\/\/www\.cdn\.com.*/,
    ({url, event}) => {
        return caches.open(`${prefix}-${runtime}-${suffix}`).then((cache) => {
            const customRequest = `${url.origin}${url.pathname}`;
            return cache.match(customRequest).then((cacheRes) => {
                if (cacheRes) {
                    return cacheRes;
                }
                return fetch(event.request).then((fetchRes) => {
                    cache.put(customRequest, fetchRes.clone());
                    return fetchRes;
                });
            });
        });
    }
);

Upvotes: 2

Related Questions