'req.flash() not working after req.session.destroy()
Based on a condition, I need to destroy user's current session, and redirect him to a login page with a message. I use flash
to have a show-once-only message. Everywhere, this works fine on my app except here, because here I use req.flash
after req.session.destroy()
.
How can I achieve this? I have tried placing req.flash()
before req.session.destroy()
but that does not work, I think because req.session.destroy()
clears the session where we just stored the flash message. Thanks.
if( req.session.adminUser.blocked ){
req.logout();
req.session.destroy(()=>{
req.flash("flashMessage", "You are blocked, Please contact admin");
req.session.save(function(){
res.redirect("/admin-panel/login");
return false;
});//session.save()
});
}
With this code, I get this error - Error: req.flash() requires sessions
. If I move the flash statement before the session.destroy
statement, then I do not get any error, but the message is not shown.
Solution 1:[1]
req.flash()
depends on a valid session, so if you destroy that session, the flash messages are destroyed as well.
It seems to me that it might actually be better to create a separate "blocked" page, and render that, instead of redirecting the blocked used back to the login page (where they can't log in anyway):
req.session.save(function(){
res.render("/admin-panel/blocked");
});
As a (less-pretty) alternative, you can pass a query string to the login page indicating that the user was blocked:
res.redirect("/admin-panel/login?blocked=true");
And use a check in the login-template to see if it should show a "you are blocked" message.
Solution 2:[2]
If you look at flash source you can see that this middleware REQUIRE session to work
Solution 3:[3]
I realize this is an old post by now, but in case it helps someone.
It looks like using req.logout();
does the trick, this allows req.flash();
to be called afterwards effectively.
"Node version": "14.16.1"
"express": "4.17.2"
"express-session": "1.17.2"
"passport": "0.5.2"
"connect-flash": "0.1.1"
"cookie-parser": "1.4.6"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | robertklep |
Solution 2 | ponury-kostek |
Solution 3 | Henry Ecker |