Friday 17 August 2018

Passing messages between redirects in Express.js

Hi. I have a route in my Express.js web server that resets a user's password. If successful, I want to redirect the user to the sign-in route and set a message that informs the user that the password reset was successful. To do this, I use the express-session module in the password reset route to create a session with a signinMessage property, and then I redirect the user to the sign-in route. In the sign-in route, I check if the message exists, and if it does then I extract it from the session, and then I set the session message property to undefined to clear it. See code below:router.post('/auth/reset-password/step-2', (req, res) => { req.session.signinMessage = 'You successfully reset your password.'; req.session.save((err) => { res.redirect('/auth/sign-in'); }); }); router.get('/auth/sign-in', (req, res) => { const message = req.session.signinMessage; if (message) { req.session.signinMessage = undefined; } res.render('auth/signin', { message }); }); What I'm wondering is; is this the best the best way to do this, and also, is setting the signinMessage property to undefined enough or should I also destroy the session somehow?Any advice or constructive criticism on my code is appreciated.

Submitted August 17, 2018 at 09:06AM by dr_goodweather

No comments:

Post a Comment