Rails 7 raise ActionController::Redirecting::UnsafeRedirectError for unsafe redirects


Rails has powerful and configurable redirection assets. It just gets better with every release!

Rails 5 was known for introducing redirect_back which allowed for an easy way to take the user back to where he came from. However, in certain scenarios, he/she would be taken back to an external page. Let’s take an example where a user navigates to our web app from a Google search. Now, if there is logic in the code that redirects the user “back”, the user would be kicked off our web app.

To mitigate this, Rails then introduced allow_other_host which gives the developer a little more control over redirection.

Before

However, one issue with allow_other_host is that in case a user is redirected to an external website when the option is turned off, an ArgumentError is raised.

if allow_other_host || _url_host_allowed?(location)
  location
else
  raise ArgumentError, "Unsafe redirect to #{location.truncate(100).inspect}, pass allow_other_host: true to redirect anyway."
end

While this is okay when developing an app, it provides very little flexibility when things go live.

After

Fortunately, Rails is one step ahead of us. Rails 7 will now raise UnsafeRedirectError instead of ArgumentError.

Practically one can use this to rescue all possible ActionController::Redirecting::UnsafeRedirectError errors and redirect the user to a safe location. This can be added directly to the ApplicationController.

class ApplicationController < ActionController::Base
  rescue_from ActionController::Redirecting::UnsafeRedirectError do
    redirect_to root_url
  end
end

Join Our Newsletter