AbstractBrain Answers About us →

How to prevent the browser back / forward cache in Rails

Question

When a user clicks the browser back button, or the back button on mobile, they see stale information.

For example, if a user adds some items to a page, then clicks the back button several times, they may see an older version of the page without those items and this can be confusing.

Is there any way to prevent the page from being cached in the browser back / forward cache?

Answer

You can prevent the page from being cached using this HTTP header:

Cache-Control: no-store

In Rails you can add it using the no_store method in a controller action. For example:

def show
  @items = @category.items
  no_store
end