Rails 7.2 allow_browser version guard feature

Updated: 

Rails 7.2 introduced the allow_browser version guard feature, that allows you to specify the minimum browser versions your application supports.

This lesson is from Full Stack Rails Mastery.

If you're using Rails 7.2 or above, you might have run into an error like this when using a slightly older browser:

Your browser is not supported. Please upgrade your browser to continue.

In your Rails server logs, you will see:
Rendering public/406-unsupported-browser.html
Completed 406 Not Acceptable

The Rails server is returning a 406 Not Acceptable HTTP code response due to a new feature that allows you to specify which browsers can access your site.

The allowed versions are specified in ApplicationController with the allow_browser method. 
class ApplicationController < ActionController::Base
  # Only allow modern browsers supporting webp images, web push, 
  # badges, import maps, CSS nesting, and CSS :has.

  allow_browser versions: :modern
end

The default value is set to :modern which refers to the following versions:
{ modern: 
  {
    safari: 17.2,
    chrome: 120,
    firefox: 121,
    opera: 106,
    ie: false
  }
}

These versions are from December 2023. At the time of writing this article (Aug 2024), this seems a bit too restrictive.

You can specify minimum versions for any browser and also whether they apply to all actions or some, using only and except. You can specify versions in ApplicationController and also in individual controllers for finer control.

For example, to allow all versions of Chrome and Opera, no versions of "internet explorer" (ie), Safari versions 16.4+ and Firefox 121+:
allow_browser versions: { safari: 16.4, firefox: 121, ie: false }

To block specific versions for specific controller actions, in addition to those specified in ApplicationController:
class ProductsController < ApplicationController
  allow_browser versions: { opera: 105, chrome: 119 }, only: :show
end

You can allow all versions by deleting or commenting out the allow_browser line.