DEV Community

Hrishi Mittal
Hrishi Mittal

Posted on • Originally published at learnetto.com

Rails 7.2 allow_browser version guard feature

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:

406 Not Acceptable. Your browser is not supported. Please upgrade your browser to continue.
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



Enter fullscreen mode Exit fullscreen mode


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
  }
}


Enter fullscreen mode Exit fullscreen mode


These versions are from December 2023.

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 }


Enter fullscreen mode Exit fullscreen mode


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


Enter fullscreen mode Exit fullscreen mode


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

Learn to build production apps with Ruby on Rails.

Top comments (0)