0

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.

1 Answer 1

2

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;
                });
            });
        });
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.