Chrome back button in express caching issue solved

express Feb 13, 2017

While working in a React/express universal app, I created an express route that serves both JSON and HTML sort of like how Rails has a respond_to block. That way if I just add .json on to the end of some of my requests it will give me the JSON used to render that page.

This caused an interesting issue in production. Occasionally when I was surfing, I would click on a link, and go forward in our universal app. Then, when I hit the back button, rather than seeing HTML I saw the JSON for the page?

Welp, turns out, Chrome doesn't take the headers into account for caching unless you tell it to. It usually only will use the URL and the request method (get, put, etc). In order for Chrome to cache differently based on the content/type, you have to add a header...

app.use((req, res, next) => {
  res.header("Vary", "X-Requested-With");
  next();
});

This will allow chrome to cache both the HTML and the JSON pages separately and prevent the issue from happening.

Tags