How to make browser skip cache if cookie exists

Viewed 200
  1. User visits subdomain1.mydomain.com, which sends back cache-control (public, max-age=86400) instructions in its response, which means the CDN and browser cache it. These instructions are only sent for logged-out visitors.
  2. User visits subdomain2.mydomain.com, and logs in. The login cookie is an http-only mydomain.com cookie, valid for both subdomains.
  3. User navigates back to subdomain1.mydomain.com to visit the previously visited page, and unfortunately gets the logged-out version of the page since it is browser-cached.

What's the cleanest way to have #3 skip the browser cache? This is also an issue when someone clicks the back button (from subdomain2 to subdomain1). The cookie is http-only so we can't have client-side javascript check for the presence of the cookie.

We also need that cache-control instruction (or something like it) for the CDN (Akamai). We could possibly then have Akamai send altered cache-control instructions to the browser, maybe no-cache?

I've also heard about Vary: cookie but I mostly see warnings not to use it.

It's as if I want the browser to serve from browser cache unless a certain cookie exists.

2 Answers

You may add vary: cookie as response header but this header should be added on the CDN. If you add it on your Origin, it may prevent CDN from caching your pages. You would also have to by-pass cache on CDN when cookie is in a request.

Vary header is not a really efficient way to deal with that situation. Few alternatives: leverage XHR if cookie is not available from JS, use different URLs, set TTL to 0s for the browser for systematic revalidation (keep it high on CDN) or add an extra cookie readable from JS with a boolean indicating whether user is logged.

i recommend you localstorage instead of cookie as it is more powerful then cookie so if you use localstorage then you will achive this one otherwise no you can achive your goal like this

if(localstorage.getItem("item-name")==null){
    // code to handle
}
Related