Express-session and the redirect() function

Posted on: 2017-06-25

If you are using express-session in your express app, you might have wanted to use the res.redirect() function, and you may have faced an unexpected behaviour : changes on session data are not always saved when the client receives the redirect response from the server and makes a new request to the server.

Here is a solution to always save the session before sending a redirect response : create a middleware that overide the redirect function.

app.use((req, res, next) => { const oldRedirect = res.redirect; res.redirect = function (...args) { if (req.session) { // redirecting after saving... req.session.save(() => Reflect.apply(oldRedirect, this, args)) } else { Reflect.apply(oldRedirect, this, args); } } })

As you can see ES6 make it simpler ! 😗