javascriptoptimizationasp.net-core-webapicookie-authenticationcacheapi

Browser Cache API is not working for cookie authenticated services


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!
                    })
                });
            }

Solution

  • 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!
                    })
                });
            }