Search code examples
node.jsexpresspassport.jspassport-local

Passport.authenticate() Error handling inside a route?


If I want to handle errors from "incorrect" logins on this route how to collect (err) and where?

// POST LOGIN
usersRouter
    .route('/login')
    .post(passport.authenticate('local'), (req, res, next) => {

        // for example, to declare an if here to catch err and call next with err...

        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json({ success: true, status: 'You are successfully logged in!' });
    });

Solution

  • You can use like this

    usersRouter.post('/login', function(req, res, next) {
      passport.authenticate('local', function(err, user, info) {
        if (err) { return next(err); }
        if (!user) { 
            return res.send(401,{ success : false, message : 'authentication failed' });
        }
            return res.send({ success : true, message : 'authentication succeeded' }); 
      })(req, res, next);
    });