Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly prevent caching of 302 redirect location?

I've encountered next problem with Post/Redirect/Get pattern. When performing GET after redirect Chrome takes the page from cache. So user sees stale data.

302 chrome from cache

I've tried following to force/support revalidation

if (request.checkNotModified(sinceLastTweet)) return null;
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Last-Modified", String.valueOf(sinceLastTweet));

But only no-store causes a server request.

Why Chrome takes the page from cache when performing redirect?


enter image description here

@RequestMapping(method = GET)
public String home(ModelMap model, @PathVariable String username, HttpServletResponse response, WebRequest request) {
    // response.setHeader("Cache-Control", "no-store");

    List<Tweet> tweets = tweetRepository.findAll();
    // long sinceLastTweet = tweets.get(0).getTimestamp().toEpochMilli();
    // if (request.checkNotModified(sinceLastTweet)) return null;
    // response.setHeader("Cache-Control", "no-cache");
    // response.setHeader("Last-Modified", String.valueOf(sinceLastTweet));

    model.addAttribute("tweets", tweets);
    model.addAttribute("tweet", new Tweet());
    model.addAttribute("username", username);

    return "home";
}
like image 826
user2418306 Avatar asked Sep 08 '25 14:09

user2418306


1 Answers

1) You have to try to force Chrome to not use the cache,

How to control web page caching, across all browsers?

Like the answer of that question suggest you have to put this header in the http response:

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

2) You can make a little trick

You can program to respond any request with the follow format with the same controller:

http://localhost:8080/spitter/username-{timestamp}

Then you change your links in your page to have the last timestamp before send the request.

In this case, event if chrome caches the page it doesn't matter.

Instead of timestamp you can use any other methodology, like "autoincrement" or "uuid".

like image 51
Troncador Avatar answered Sep 10 '25 04:09

Troncador