Rails 6. A page with outdated data is shown after the browser opening

Viewed 319

There is a Rails web-application. Each time I open a browser with kinda the 'restore previous session on startup' option (Chrome, Firefox, Edge) I can see the page with outdated data (old numbers, text, and so on). I have to refresh the page to see the actual data.

Is there any way to get refreshed pages on browser opening? Maybe there is a Rails setting... or there is a way to do something using JS.

So, the basic scenario is looking like this:

  • open a page with some data
  • close the browser (do not close the tab with our page)
  • change the data for this page (e.g. in DB)
  • open the browser and look at the state of our page

Expected result: the page contains relevant ('fresh') data. Actual result: the page contains outdated data.

Can anyone help me with that?

3 Answers

I've found an answer here.

class ApplicationController < ActionController::Base

  before_action :set_cache_headers

  private

  def set_cache_headers
    response.headers["Cache-Control"] = "no-cache, no-store"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Mon, 01 Jan 1990 00:00:00 GMT"
  end
end

The solution is 12 years old but it's still workable.

In config/initializers/default_headers.rb (or similar), put the following:

Rails.application.config.action_dispatch.default_headers['Cache-Control'] = 'no-cache, no-store'

Haven't came across this issue, but I would probably use some JS to handle it in some way or another.

This could be as simple as storing the page_generated_at time (as unix timestamp probably to avoid need for datetime format handling) somewhere on the page (when the page is rendered from the server), and then adding JS to reload the page if the page_generated_at time is more than X seconds older than the current time, which would be a few lines of JS.

Related