0

I am trying browser Cache API mechanism, but the api which is going to be cached is using cookie authentication. And am receiving 'unauthorized-401' error message. I am suspecting the http cookie supposed to send for all the api request is not sending when i am calling from cache.add(apiurl)

         if ('caches' in window) {
                caches.open('cachename').then(cache => {
                    cache.add(apiUrl).then(() => {
                        //done!
                    })
                });
            }
Sudheer Muhammed
  • 813
  • 8
  • 10

2 Answers2

0

I found a way to handle this. Instead of adding URL in add() method, create a Request object with "credentials: include " or "credentials: same-orgin" depends on your CORS settings.

 if ('caches' in window) {
            caches.open('cachename').then(cache => {
                cache.add(new Request('apiurl', {credentials: 'include'}).then(() => {
                    //done!
                })
            });
        }

//Or

if ('caches' in window) {
            caches.open('cachename').then(cache => {
                cache.add(new Request('apiurl', {credentials: 'same-origin'}).then(() => {
                    //done!
                })
            });
        }
Sudheer Muhammed
  • 813
  • 8
  • 10
0

It is not recommended to use cache.add with new Request. At least it is new request to server, and can cache irrelevant data. Instead I recommend use cache.put + res.clone()

if ('caches' in window) {
  if (navigator.onLine) {
    return fetch(request)
        .then(res => {
            const resClone = res.clone();
            caches.open(KEY).then((cache) => cache.put(request, resClone));

            return res;
        })
        .catch(err => console.error(err));
  }

  // some other logic
}

enter image description here

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#recovering_failed_requests

Jahongir
  • 141
  • 2
  • 7