Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rails 7 devise flash messages not being shown #5446

Closed
steveroot opened this issue Dec 30, 2021 · 33 comments · Fixed by #5548
Closed

Rails 7 devise flash messages not being shown #5446

steveroot opened this issue Dec 30, 2021 · 33 comments · Fixed by #5548

Comments

@steveroot
Copy link

Environment

  • Ruby 3.0.2p107
  • Rails 7.0.0
  • Devise 4.8.1

Current behavior

A new rails 7 app with devise.
Flash messages from Devise are not shown but Flash messages generated from another controller are shown.
The Devise flash messages appear to be being generated in the console rendering messages when a new user is registered with a password that is too short


Started POST "/users" for ::1 at 2021-12-24 08:02:10 +0000
Processing by Devise::RegistrationsController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"asdf@asdf.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
  TRANSACTION (0.1ms)  begin transaction
  User Exists? (2.7ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ?  [["email", "asdf@asdf.com"], ["LIMIT", 1]]
  TRANSACTION (0.2ms)  rollback transaction
  Rendering layout layouts/application.html.erb
  Rendering /home/sroot/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/devise-4.8.1/app/views/devise/registrations/new.html.erb within layouts/application
  Rendered /home/sroot/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/devise-4.8.1/app/views/devise/shared/_error_messages.html.erb (Duration: 0.7ms | Allocations: 582)
  Rendered /home/sroot/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/devise-4.8.1/app/views/devise/shared/_links.html.erb (Duration: 0.2ms | Allocations: 92)
  Rendered /home/sroot/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/devise-4.8.1/app/views/devise/registrations/new.html.erb within layouts/application (Duration: 3.9ms | Allocations: 2199)
  Rendered layout layouts/application.html.erb (Duration: 77.5ms | Allocations: 4429)
Completed 200 OK in 473ms (Views: 78.7ms | ActiveRecord: 3.1ms | Allocations: 15288)

Example minimal app:
https://github.com/steveroot/rails7deviseflash
(Add a 'new club' to see working flash message, Register a new user with a short password to not see flash message yet see render message in console)

Expected behavior

Flash messages shown on screen when generated

@steveroot
Copy link
Author

Update, I found an error reported in the browser console, i don't know if this is useful

turbo.es2017-esm.js:2115 Error: Form responses must redirect to another location

A failure in the clubs controller generates a flash error message and a different message in the console turbo.es2017-esm.js:430 POST http://localhost:3000/clubs 422 (Unprocessable Entity)

image

The devise part generates the 'must redirect' message in the console like this screenshot

image

@AlanDonohoe
Copy link

I am also having this issue.

I thought that this might fix it but it doesn't...

ref: #5439
Ran into this at the same time as you 😆

Quick fix, tl;dr

Add :turbo_stream as a navigational format. This line goes in config/initializers/devise.rb. I haven't tested this extensively, but I think it should be fine.

config.navigational_formats = ['*/*', :html, :turbo_stream]

There's also this open PR that may be of use: #5440

@steveroot
Copy link
Author

I am also having this issue.

I thought that this might fix it but it doesn't...

ref: #5439 Ran into this at the same time as you 😆

Quick fix, tl;dr

Add :turbo_stream as a navigational format. This line goes in config/initializers/devise.rb. I haven't tested this extensively, but I think it should be fine.

config.navigational_formats = ['*/*', :html, :turbo_stream]

There's also this open PR that may be of use: #5440

Thanks, it's nice to know it's not just me having trouble :-)
I just tried it too and you're right that didn't work either, same error messages in the browser console too. Worth a try though, thanks again

@bouaik
Copy link

bouaik commented Jan 1, 2022

I am also having this issue.
I thought that this might fix it but it doesn't...
ref: #5439 Ran into this at the same time as you laughing

Quick fix, tl;dr

Add :turbo_stream as a navigational format. This line goes in config/initializers/devise.rb. I haven't tested this extensively, but I think it should be fine.

config.navigational_formats = ['*/*', :html, :turbo_stream]

There's also this open PR that may be of use: #5440

Thanks, it's nice to know it's not just me having trouble :-) I just tried it too and you're right that didn't work either, same error messages in the browser console too. Worth a try though, thanks again

Did it work for you, I just tried it, it's not working for me.

Note: after 2 hours i found this episode of gorails, it's solved
https://www.youtube.com/watch?v=yZDTBItc3ZM&t=316s&ab_channel=GoRails

@AlanDonohoe
Copy link

@bouaik Nice one! Thank you for sharing that.

Bit of a fiddly one, but it's mostly working for me. Other than a failed log in attempt (logs below) - this just returns to the log in page without any error message.

Have you got this working too?

logs:

Started POST "/users/sign_in" for ::1 at 2022-01-02 11:57:55 +0000
Processing by Devise::SessionsController#create as TURBO_STREAM
...
Completed 401 Unauthorized in 7ms (ActiveRecord: 0.3ms | Allocations: 2129)

Started GET "/users/sign_in.turbo_stream" for ::1 at 2022-01-02 11:57:55 +0000
Processing by Devise::SessionsController#new as TURBO_STREAM

No flash message being set...

@bouaik
Copy link

bouaik commented Jan 2, 2022

@AlanDonohoe , yes it's working for me, setting :turbo_stream as a navigational format solves the 401, but not the flash messages, you have to add the same code as in the video to make it all working.

@AlanDonohoe
Copy link

And full code here hotwired/turbo#45 from the very clever @excid3 - thank you so much! 👏

@jaindivij21
Copy link

jaindivij21 commented Jan 4, 2022

I am an absolute beginner, so pardon me for any mistake. But I have been facing a similar issue to this, where I cannot sign up a user. The sqlite3 database remains empty even after pressing sign up.

The browser console shows the following error:
Error: Form responses must redirect to another location.

While terminal serves me a rollback transaction:

Started POST "/users" for ::1 at 2022-01-04 16:41:34 +0530
Processing by Devise::RegistrationsController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"jaindivijwork@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
  TRANSACTION (0.1ms)  begin transaction
  User Exists? (0.2ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ?  [["email", "jaindivijwork@gmail.com"], ["LIMIT", 1]]    
  TRANSACTION (0.1ms)  rollback transaction

I tried pasting the following in config/initializers/devise.rb but have had no success. Kindly help me implement user authentication.
config.navigational_formats = ['*/*', :html, :turbo_stream]

Demo Github Repo : https://github.com/jaindivij21/friends-list

@nejdetkadir
Copy link

maybe it can help you.

@john-999
Copy link

A temporary solution/hack would be to set: data: { turbo: false }, as in:

<%= form_with url: some_path, data: { turbo: false } do |f| %>
   ...
<% end %>

@DaniG2k
Copy link

DaniG2k commented May 7, 2022

+1

Surprised Rails 7 isn't working out of the box with Devise yet 🤔

@caiohenrique12
Copy link

caiohenrique12 commented Jun 3, 2022

A temporary solution/hack would be to set: data: { turbo: false }, as in:

<%= form_with url: some_path, data: { turbo: false } do |f| %>
   ...
<% end %>

Hi guys, that's works for me!

@awais-amjed
Copy link

awais-amjed commented Jun 13, 2022

Turns out the issue is javascript_importmap_tags in application.html.erb

image

Remove it and Devise will start showing flash messages.
I am not sure why this happens, but it happens. If someone can understand the reason, do explain it. Thanks

@bushmusi
Copy link

bushmusi commented Jul 4, 2022

@awais-amjed You are right. I don't know why it works after I removed it. Thanks a lot

@ohashioji
Copy link

@awais-amjed Thanks, that worked for me as well

@amo13
Copy link

amo13 commented Jul 19, 2022

Can you actually comment that out without breaking all of the hotwire stuff like turbo and stimulus?

@awais-amjed
Copy link

awais-amjed commented Jul 19, 2022

@amo13 No, actually that's not a good way to do this. We should use above solutions data: { turbo: false }
I figured out later when I needed to use hotwire that removing this line breaks all that stuff.

SO GUYS DON'T REMOVE THAT LINE IF YOU NEED HOTWIRE.

@lperry65
Copy link

Is this fixed now, I don't really want to be putting in hacks to get things working ?

@wandji20
Copy link

wandji20 commented Aug 4, 2022

I think the issue is about setting the right response status when devise renders new.html.erb after login failure.
After adding turbo_stream to devise navigational_formats, sign_in request with turbo_stream format returns an :ok status. However, flash messages will not be shown for login failures unless we explicitly set a failure status (eg :unprocessable_entity)
Will show flash message

def create
user = User.find_by_email(sessions_params[:email])
if user&.authenticate(sessions_params[:password])
# do some stuffs
flash[:notice] = 'Welcome'
redirect_to redirect_location
else
flash.now[:alert] = 'Invalid Email/Password'
render :new, status: :unprocessable_entity
end
end

Will not show message

def create
user = User.find_by_email(sessions_params[:email])
if user&.authenticate(sessions_params[:password])
# do some stuffs
flash[:notice] = 'Welcome'
redirect_to redirect_location
else
flash.now[:alert] = 'Invalid Email/Password'
render :new
end
end

Any suggestions on how we can achieve a similar result with devise?

@d33pjs
Copy link

d33pjs commented Aug 8, 2022

maybe it can help you.

That also worked for me. And like @DaniG2k I'm also wondering why this is not working out of the box.

@bellatrix988
Copy link

I tried both approaches and they worked just fine. Finally decided to override form_for method with these data: { turbo: false } options.

📎 I created a gist with all the information may come in handy for this issue.

@marcel-strzalka
Copy link

Is this issue still relevant? What is the current status of this problem?

@john-999
Copy link

john-999 commented Oct 4, 2022

This issue is still unresolved. Use this working hack for now:

A temporary solution/hack would be to set: data: { turbo: false }, as in:

<%= form_with url: some_path, data: { turbo: false } do |f| %>
   ...
<% end %>

This simply disables Turbo for this form submission (but not anywhere else).

YoussefHenna added a commit to modulehandbook/modulehandbook that referenced this issue Oct 27, 2022
Devise had issues with Turbo and did'nt work out of the box:
heartcombo/devise#5446

Workaround/solution as
shown here:
https://betterprogramming.pub/devise-auth-setup-in-rails-7-44240aaed4be
lotteunckell pushed a commit to modulehandbook/modulehandbook that referenced this issue Nov 4, 2022
* refactor: Migrated to importmap instead of webpacker

Importmap (https://github.com/rails/importmap-rails) instead of the
retired webpacker

* Added bootstrap in proper importmap manner

* refactor: Removed webpacker gem

Removal of gem introduced a couple a breaking issues that were
also
addressed in this commit:
- Turbolinks needed to replaced by
turbo
- Route to delete needed to follow a new format

* fix: Fixed devise config to work with Turbo

Devise had issues with Turbo and did'nt work out of the box:
heartcombo/devise#5446

Workaround/solution as
shown here:
https://betterprogramming.pub/devise-auth-setup-in-rails-7-44240aaed4be

* fix: Fixed delete format for Program

* Undid changes required for windows local running

* Removed yarn and webpacker steps from Github tests

* Removed webpacker + yarn steps in makefile

* Removed yarn and package.json from Dockerfile

* fix: Fix to destroy tests failing

The addition of the 'Turbo' library changed the way delete alert was shown. For some reason, test was too fast and click action does not work. Adding a 1 second delay before click fixed the test.
@dan
Copy link

dan commented Nov 23, 2022

A temporary solution/hack would be to set: data: { turbo: false }, as in:

<%= form_with url: some_path, data: { turbo: false } do |f| %>
   ...
<% end %>

This is the correct answer.

@rex-9
Copy link

rex-9 commented Dec 5, 2022

data: { turbo: false }

Thank you so much! This saved me.

@KapilDevPal
Copy link

<%= bootstrap_form_with model: @Company, data: { turbo: false } do |form| %>
it worked

carlosantoniodasilva added a commit that referenced this issue Jan 31, 2023
Treat `:turbo_stream` request format as a navigational format, much like
HTML, so Devise/responders can work properly.

Allow configuring the `error_status` and `redirect_status` using the
latest responders features, via a new custom Devise responder, so we can
customize the both responses to match Hotwire/Turbo behavior, for
example with `422 Unprocessable Entity` and `303 See Other`,
respectively. The defaults aren't changing in Devise itself (yet), so it
still responds on errors cases with `200 OK`, and redirects on non-GET
requests with `302 Found`, but new apps are generated with the new
statuses and existing apps can opt-in. Please note that these defaults
might change in a future release of Devise.

PRs/Issues references:

#5545
#5529
#5516
#5499
#5487
#5467
#5440
#5410
#5340

#5542
#5530
#5519
#5513
#5478
#5468
#5463
#5458
#5448
#5446
#5439
carlosantoniodasilva added a commit that referenced this issue Jan 31, 2023
Treat `:turbo_stream` request format as a navigational format, much like
HTML, so Devise/responders can work properly.

Allow configuring the `error_status` and `redirect_status` using the
latest responders features, via a new custom Devise responder, so we can
customize the both responses to match Hotwire/Turbo behavior, for
example with `422 Unprocessable Entity` and `303 See Other`,
respectively. The defaults aren't changing in Devise itself (yet), so it
still responds on errors cases with `200 OK`, and redirects on non-GET
requests with `302 Found`, but new apps are generated with the new
statuses and existing apps can opt-in. Please note that these defaults
might change in a future release of Devise.

PRs/Issues references:

#5545
#5529
#5516
#5499
#5487
#5467
#5440
#5410
#5340

#5542
#5530
#5519
#5513
#5478
#5468
#5463
#5458
#5448
#5446
#5439
carlosantoniodasilva added a commit that referenced this issue Jan 31, 2023
Treat `:turbo_stream` request format as a navigational format, much like
HTML, so Devise/responders can work properly.

Allow configuring the `error_status` and `redirect_status` using the
latest responders features, via a new custom Devise responder, so we can
customize the both responses to match Hotwire/Turbo behavior, for
example with `422 Unprocessable Entity` and `303 See Other`,
respectively. The defaults aren't changing in Devise itself (yet), so it
still responds on errors cases with `200 OK`, and redirects on non-GET
requests with `302 Found`, but new apps are generated with the new
statuses and existing apps can opt-in. Please note that these defaults
might change in a future release of Devise.

PRs/Issues references:

#5545
#5529
#5516
#5499
#5487
#5467
#5440
#5410
#5340

#5542
#5530
#5519
#5513
#5478
#5468
#5463
#5458
#5448
#5446
#5439
carlosantoniodasilva added a commit that referenced this issue Jan 31, 2023
Treat `:turbo_stream` request format as a navigational format, much like
HTML, so Devise/responders can work properly.

Allow configuring the `error_status` and `redirect_status` using the
latest responders features, via a new custom Devise responder, so we can
customize the both responses to match Hotwire/Turbo behavior, for
example with `422 Unprocessable Entity` and `303 See Other`,
respectively. The defaults aren't changing in Devise itself (yet), so it
still responds on errors cases with `200 OK`, and redirects on non-GET
requests with `302 Found`, but new apps are generated with the new
statuses and existing apps can opt-in. Please note that these defaults
might change in a future release of Devise.

PRs/Issues references:

#5545
#5529
#5516
#5499
#5487
#5467
#5440
#5410
#5340

#5542
#5530
#5519
#5513
#5478
#5468
#5463
#5458
#5448
#5446
#5439
@Gubio
Copy link

Gubio commented Jan 31, 2023

@carlosantoniodasilva 🚀

JesusGautamah added a commit to JesusGautamah/outerspace-blockchain that referenced this issue Feb 1, 2023
…adern.auth do' to verify password and call sign_method, redirectin to root path with notice in the correct local of front end to correct the issue heartcombo/devise#5446 in this project
@carlosantoniodasilva
Copy link
Member

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.

@steveroot
Copy link
Author

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.

Thank you for fixing and sharing, and my apologies to all here that since I discovered this and created the issue a year ago I've had zero time to code and respond (I code for fun alone and this year was too busy for me, that time will come again and I appreciate all of your help).

@yayahc
Copy link

yayahc commented Apr 9, 2023

@awais-amjed thank, I remove <%= javascript_importmap_tags %> and it work for me.

@tamersalama
Copy link

Just as @carlosantoniodasilva mentioned - this is now included in the latest. I used the following gems (although I don't think I needed to)

gem 'devise', github: 'heartcombo/devise', branch: 'main'
gem 'responders', '~> 3.1.0'

Make sure there's a flash message included in your template (application.erb or devise.erb) to display the error messages

        - flash.each do |name, msg|
          .message[class=flash_class(name.to_sym)]
            = content_tag :div, msg, id: "flash_#{name}"

@carlosantoniodasilva
Copy link
Member

The latest stable version v4.9.2 should have all you need to, in case you don't want to bundle from main directly.

@hamen
Copy link

hamen commented Nov 21, 2023

I ended up here from https://www.youtube.com/watch?v=m3uhldUGVes&t
I'm happy this is fixed now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.