Skip to content

Redirect to new registration (sign up) path if unauthenticated

Kyle Fox edited this page Aug 12, 2018 · 3 revisions

By default, Devise's authenticate_user! filter will redirect unauthenticated users to the login page, i.e. new_user_session_url.

It's possible to redirect these users to another page, for example the new registration (sign up) page, i.e. new_user_registration_url.

To do this, define a custom failure app with a route method that returns a symbol representing the named route to redirect to:

# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
  def route(scope)
    :new_user_registration_url
  end
end

Then inside the Devise initializer, specify your failure app:

# config/initializers/devise.rb
config.warden do |manager|
  manager.failure_app = MyFailureApp
end

Working with multiple Devise resources

Say your app has both Admin and User Devise resources. In that case, you don't want to redirect to a new_admin_registration_url — in fact, you probably shouldn't have such a route in your app to begin with 😬

To handle this, just check which kind of Devise scope is being processed, and conditionally return a URL based on that:

# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
  def route(scope)
    scope.to_sym == :user ? :new_user_registration_url : super
  end
end

Notes:

  • This approach is preferable to overriding authenticate_user! in your controller because it won't clobber a lot of "behind the scenes" stuff Devise does (such as storing the attempted URL so the user can be redirected after successful sign in).
  • Ensure app/lib folder is autoloaded inside config/application.rb, ex: config.autoload_paths << Rails.root.join('lib').
  • You need to restart your Rails server after making changes to my_failure_app.rb.
Clone this wiki locally