devise: Rails 7: logout redirect not working

Set this in application_controller.rb:

  def after_sign_out_path_for scope
    root_path
  end

You expect the logout to redirect the user to root.

However Devise returns a redirect with status 302, which does not work with Turbo.

All redirects must return 303 (i.e. status: :see_other) in order to work with Turbo.

This should be fixed in Devise in order to work with Rails 7.

Related: https://github.com/rails/rails/issues/44170

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 12
  • Comments: 31 (3 by maintainers)

Commits related to this issue

Most upvoted comments

You have to change from:

<%= link_to “Sign out”, destroy_user_session_path, method: delete %>

to

<%= link_to “Sign out”, destroy_user_session_path, data: { turbo_method: :delete" } %>

I fixed this as follows:

<%= link_to("Log out", destroy_user_session_path, method: :delete, data: { turbo_method: :delete }) %>
module Users
  class SessionsController < Devise::SessionsController
    def destroy
      super do
        # Turbo requires redirects be :see_other (303); so override Devise default (302)
        return redirect_to after_sign_out_path_for(resource_name), status: :see_other
      end
    end
  end
end

This worked for me initially:

<%= link_to "Logout", destroy_user_session_path, data: { turbo_method: :delete } %>

But after making these turbo changes (to fix an unrelated issue of some bootstrap javascripts not working) from:

// app/javascript/application.js
import "@hotwired/turbo-rails"

to this

// app/javascript/application.js
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false

then logout broke.

However, this worked:

<%= button_to "Log out", destroy_user_session_path, method: :delete, data: { turbo: false } %>

Hope it’s useful.

@designium Yes, sure, I already use the correct code for Turbo… However there is the bug described in the original post.

I ended up with this which makes a mini form:

<%= button_to "Logout", destroy_user_session_path, method: :delete, form: {  data: { turbo: :false } } %>

This issue is not specific to Turbo, it’s how the Fetch API behaves: when the HTTP status is 302, the browser will send another request to the redirect URL using the same HTTP method as the initial request. Turbo wraps the Fetch API, but I ran into the same issue in our app which doesn’t use Turbo.

In our case we solved this by changing the HTTP method for the sign out route from DELETE to GET.

In config/initializers/devise.rb:

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :get

Then you can use a regular link in your view, no Turbo/JS needed at all:

<%= link_to "Sign Out", destroy_user_session_path %>

Alternatively, you can keep using a DELETE route (preferable, since GET routes with side-effects are kind of icky) and use a form rather than a link:

<%= button_to "Sign Out", destroy_user_session_path, method: :delete %>

This also requires no Turbo/JS, though you’ll probably want to sprinkle some CSS to make the button look like a regular link.

@collimarco I have found simple hotfix

# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
  def respond_to_on_destroy
    respond_to do |format|
      format.all { head :no_content }
      format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name), status: :see_other}
    end
  end
end
# config/routes.rb
Rails.application.routes.draw do
  # ...
  devise_for :users, controllers: { sessions: 'sessions' }
  # ...
end

You just need add status: :see_other (303) to redirect_to method arguments to make it works correctly

I just notice that when you are using a button to log out: <%= button_to "Log Out", destroy_user_session_path, method: :delete %> the the redirect works as expected and the user is taken to the root_path. However as soon as you are using a link things are not working (mostly due to the status issue mentioned above).

@Havoc85

You need to generate or create an inherited Devise controller for sessions first. You can do that by running the following command (assuming that “user” is your Devise model):

rails generate devise:controllers users -c=sessions

Uncomment the destroy method in the new file that gets created and place the above code inside the method.

Don’t forget to update your Devise routes for the changes to take effect.

Disabling Turbo is the wrong answer here. This issue is specific to an incorrect redirect being returned by Devise::SessionController.

My Selenium tests fail like this:

2) Authentication as a User allows a user to Log In and Out
     Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
     
     ActionController::RoutingError:
       No route matches [DELETE] "/"

The Rails log will follow a pattern similar to this:

Started DELETE "/users/sign_out" for 127.0.0.1 at 2022-09-02 17:00:43 -0600
Processing by Devise::SessionsController#destroy as TURBO_STREAM
  User Load (1.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
Redirected to http://127.0.0.1:57460/
Completed 302 Found in 10ms (ActiveRecord: 1.6ms | Allocations: 1787)
Started DELETE "/" for 127.0.0.1 at 2022-09-02 17:00:43 -0600

The issue is that Turbo is attempting to render after_sign_out_path with the incorrect HTTP Verb (DELETE, in this case). You want your Devise controller to respond with HTTP 303 See Other. Solutions that override Devise’s default behavior, such as @mattbrictson’s, should be used.

I fixed this as follows:

<%= link_to("Log out", destroy_user_session_path, method: :delete, data: { turbo_method: :delete }) %>
module Users
  class SessionsController < Devise::SessionsController
    def destroy
      super do
        # Turbo requires redirects be :see_other (303); so override Devise default (302)
        return redirect_to after_sign_out_path_for(resource_name), status: :see_other
      end
    end
  end
end

Don’t forget to update your routes, too:

  devise_for :users, controllers: {
    sessions: 'users/sessions'
  }

None of the other replies actually fix the OP’s original issue.

The main branch should contain all that’s necessary for fully working with Turbo now, which should fix this. A new version will be released soon, but feel free to test it out from the main branch in the meantime, and report back on any issues. Thanks.

This worked for me initially:

<%= link_to "Logout", destroy_user_session_path, data: { turbo_method: :delete } %>

But after making these turbo changes (to fix an unrelated issue of some bootstrap javascripts not working) from:

// app/javascript/application.js
import "@hotwired/turbo-rails"

to this

// app/javascript/application.js
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false

then logout broke.

However, this worked:

<%= button_to "Log out", destroy_user_session_path, method: :delete, data: { turbo: false } %>

Hope it’s useful.

👍 Thanks

@Havoc85

You need to generate or create an inherited Devise controller for sessions first. You can do that by running the following command (assuming that “user” is your Devise model):

rails generate devise:controllers users -c=sessions

Uncomment the destroy method in the new file that gets created and place the above code inside the method.

Don’t forget to update your Devise routes for the changes to take effect.

Thank you for that description! That helps a lot.