JSON response after passport js authentication

Apr 5, 2022

JSON after passport auth

To send a JSON response with passport-local, the failWithError option is useful.

Example:

app.post('/login',
  passport.authenticate('local', { failWithError: true }),
  function(req, res, next) {
    // Handle success
    return res.send({ success: true, message: 'Logged in' })
  },
  function(err, req, res, next) {
    // Handle error
    return res.status(401).send({ success: false, message: err })
  }
)

The failWithError option was added in 2014 (see issue #126) but wasn't documented.

This is important for folks who want custom error messages without needing to implement a custom callback

Share on Twitter

Give this page a share if you found it useful 🙏

A handsome man.

I'm Wes. I live in Boston and work on Wonderment.