Reputation: 10055
I have setup a basic service worker installation on an application that I am developing.
This service worker is causing a lot of issues when users sign out and sign in with another username. Or even some times it blocks signin.
I basically know what is happening I just can't figure out how to fix it.
So, my application is strictly for logged in users, so an unauthorized user can only view the signin page.
My first issue is that when a user signs in, the Dashboard page is cached and if they sign out and sign in as another use, the dashboard of the first user is shown. (It shows the wrong username on the top of the page)
Second issue is that sometimes the signin page is cached in a way that it constantly redirects users back to the signin page even when they have signed in successfully.
All of these issues are completely fixed once the user does ctrl + f5
since that doesn't use the cache and get all the content straight from the network.
Here is my sw.js
file:
importScripts( '/cache-polyfill.js' );
var CACHE_NAME = 'XYZ-cache-v0.4.16';
var assetsToCache = [
// A list of CSS, JS, Images and font files
];
self.addEventListener( 'install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(assetsToCache))
);
});
self.addEventListener('activate', async (e) => {
e.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if(CACHE_NAME.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request).then((r) => {
return r || fetch(e.request).then((response) => {
return caches.open(CACHE_NAME).then((cache) => {
cache.put(e.request, response.clone());
return response;
});
});
})
);
});
Upvotes: 2
Views: 1752
Reputation: 1
I had the same issue with my app. Removing my main page from cached files list in sw.js and clearing cache in the browser helped in my case.
Upvotes: 0
Reputation: 5253
Well, you should consider whether it is wise to cache PII (https://en.wikipedia.org/wiki/Personal_data) in the first place. If that is what you really need, then you should implement a mechanism that empties the caches when the first user's session expires.
You may use the postMessage API
(https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) to send a msg to the Service Worker when the logout is happening. Then, inside your Service Worker, have some functionality that empties the caches.
This alone - emptying caches when user specifically clicks "log out" - most likely isn't enough. The login sessions are usually limited to some time frame so you would need to have logic that detects when the session is ended and then clears the caches even if the user did NOT click on log out.
Maybe login page should not be cached at all - it cannot work when there's no connection, right?
Upvotes: 1