[Fixed]-Cache website to browser when navigating back

1đź‘Ť

whenever a user navigates away from that page, and then presses the BACK button of the browser, I don’t want that request to go to django at all, but serve the cached version of the page that is in the browser

For some browsers, this is the default behavior – if you have set no caching directives on the server, then it will keep not only a copy of the response but the entire rendered page in memory so than when you click the back button, it can be shown instantly.

But if you want to explicitly instruct the browser to cache the response you can use a max-age directive on the Cache-Control header. Set

Cache-Control: max-age=3600

This is a more modern and reliable way than using an “Expires” header, especially for small durations. If the user’s browser has the incorrect time or time zone set “Expires” might not work at all, but “max-age” still should.

If you are serving each person a different version of the page you can add the “private” too to prevent caching by proxies (as in your example):

Cache-Control: private; max-age=3600

Note: you can’t force a browser to always use the cache. If you are noticing that sometimes it doesn’t use the cache, it could be:

  • The item in the cache has expired. You were giving it only 5 minutes, so 5 minutes after the request that went into the cache, if you request it again it will send through the request to the remote server – even if there have been requests in the time between.

  • The browser cache became full and some items were purged.

  • For some reason the browser believed or was configured to believe that the response should not be cached regardless of cache directives.

  • The user pressed reload.

  • A proxy between client and server stripped the Cache-Control or other headers.

👤thomasrutter

Leave a comment