Patrick Miah
Patrick Miah

Reputation: 51

Clearing back/forward cache only after logout

After a user has logged in or out, and the browser back button is used, the page is restored from the bfcache,
The page is restored even when a logged out user isn't supposed to access this page.


I know it's possible to clear the cache, by using the following code.

res.header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.header("Pragma: no-cache"); // HTTP 1.0.
res.header("Expires: 0"); // Proxies.

I just want the cache to be removed after a user has logged in or out, but the above script only works for that single page it runs for.
If I run it on every page, I'm removing the cashing capabilities from the server entirely, which is not what I want.


I've also came accross history.deleteAll(), which I thought would solve my issue.
When I run 'deleteAll' in history in Brave, Chrome, Edge, Firefox or Opera, I do get back false, and I'm not sure why.

This function should work in Chrome, Edge, Firefox, Opera according to the browser compatibility table on this page:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/deleteAll


I also came across this page:
https://web.dev/articles/bfcache

This page explains how to observe when a page has been restored from bfcache.
There's even a section called 'Update stale or sensitive data after bfcache restore' on this page.

window.addEventListener('pageshow', (event) => {
  if (event.persisted && !document.cookie.match(/my-cookie)) {
    // Force a reload if the user has logged out.
    location.reload();
  }
});

The problem with utilizing this is that when I reload or show or hide elements on the page in the event handler, it's always after the fact that the page has already restored itself, thus it will still display sensitive information, albeit in a flash of a second, which I'm still not okay with.


Also, immediately prompting the user to close the page after a logout is a fallback option I'd rather not utilize.
Using window.close() after a logout is also not possible, because according to the browser console Scripts may close only the windows that were opened by them..


How could I clear the bfcache after a user has logged in/out, and still make use of it in all other cases?

Upvotes: 1

Views: 287

Answers (0)

Related Questions