How to use the Browser Guard in Rails

August 12, 2024

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teachers

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

Collin Jilbert

Ruby on Rails Developer | Lover of Music | Skateboarder | Proud Papa | Co-editor @therubyradar | Launched @fleur_de_ruby

About This Episode

The new browser guard in Rails 7.2 allows you to gate access to your application if a user is not using a modern browser.

Notes

There are lots of nice features that modern browsers support like webp images, Web Push, Badges, Importmaps, and CSS Nesting + :has.

Not all browsers are up-to-date so your users might have broken functionality if they're using an older browser version.

Rails 7.2 introduces allow_browser versions: :modern method in your controllers to recommend users upgrade their browser before they can access your application. This is great for no build applications that take advantage of these new browser features.

You can also customize this to specific versions of each browser to perfectly tailor the browser guard for the specific features your application needs.

class ApplicationController < ActionController::Base
  # Allow only browsers natively supporting webp images, web push, badges, import maps, CSS nesting + :has
  allow_browser versions: :modern
end

class ApplicationController < ActionController::Base
  # All versions of Chrome and Opera will be allowed, but no versions of "internet explorer" (ie). Safari needs to be 16.4+ and Firefox 121+.
  allow_browser versions: { safari: 16.4, firefox: 121, ie: false }
end

class MessagesController < ApplicationController
  # In addition to the browsers blocked by ApplicationController, also block Opera below 104 and Chrome below 119 for the show action.
  allow_browser versions: { opera: 104, chrome: 119 }, only: :show
end

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.