How to get a flash message to show with passport-local logout method?

122 views Asked by At

I am unable to show a flash message of 'You have successfully logged out' when trying to use the req.logout() method using passport-local.

Here is what I currently have, which will redirect to the login page but not display the message.

logout: (req, res, next) => {
      req.logout((err) => {
         if (err) {
            return next(err)
         }
      })
      req.flash('success_msg', 'You have successfully logged out')
      res.redirect('/login')
   }

If I comment out the req.logout code, the flash message will show up as well as redirect to the login page.

logout: (req, res, next) => {
      // req.logout((err) => {
      //    if (err) {
      //       return next(err)
      //    }
      // })
      req.flash('success_msg', 'You have successfully logged out')
      res.redirect('/login')
   }

I am wondering how to use req.logout() and also get the flash message to show to the user.

1

There are 1 answers

0
Hannah On

The issue is that the req.flash() and res.redirect() needed to be inside of the req.logout() callback and in my code above it was outside of it.

logout: (req, res, next) => {
  req.logout((err) => {
    if (err) {
      return next(err)
    }
    req.flash('success_msg', 'You have successfully logged out')
    res.redirect('/login')
  })
}