Search code examples
javabrowserbrowser-cachecache-control

response header to cache the response?


In my web app some pages, I have two scenarios for browser cache

Scenario 1 :- I want to server from browser cache if not modified at server side. For example :-

  1. User issues the request for all employees
  2. Response returns 10 employees
  3. User issues the request for all employees again
  4. Expectation is this time it should be served from browser cache
  5. User creates one more employee
  6. User issues the request for all employees again
  7. Expectation is this time it should be served latest from server instead of browser cache

I am planning to use below header

response.setHeader("Cache-Control", "no-cache"); 

As

no-cache is not instructing the browser or proxies about whether or not to cache the content. It just tells the browser and proxies to validate the cache content with the server before using it

Scenario 2 :- But for some sensitive pages i don't want to cache at all, i am planning it to use below header

response.setHeader("Cache-Control",  "no-store"); 

But some articles safe to use below header to make it work for all browsers. So i am going to use below

response.setHeader("Cache-Control", "no-cache, no-store"); 

Is my proposed implementation correct ?


Solution

  • For Scenario #1 you indeed need to set Cache-Control to no-cache (or set a max-age for even a better scalability but in this case you won't have necessary the latest value) but you also need to use the HTTP header ETag in order to allow the browser to check if the data content has changed such that the browser will be able to know if the cache entry can be reused or not.

    For Scenario #2 you need to set Cache-Control to no-store to prevent the browser to cache the data as it is the standard way but indeed no-cache, no-store will help to work on old browsers if you need to support them too.