How to check if user is logged in with Passport.js?

Sometimes, we want to check if user is logged in with Passport.js.

In this article, we’ll look at how to check if user is logged in with Passport.js.

How to check if user is logged in with Passport.js?

To check if user is logged in with Passport.js, we can check is req.user is defined.

For instance, we write

if (req.user) {
  // logged in
} else {
  // not logged in
}

to do the check in a middleware function.

We write

const loggedIn = (req, res, next) => {
  if (req.user) {
    next();
  } else {
    res.redirect('/login');
  }
}

app.get('/me', loggedIn, (req, res, next) => {
  //...
});

to define the loggedIn middleware function with the if statement.

We call next to run the next middleware function if req.user is set and call res.redirect to redirect to the /login route otherwise.

And then we can use loggedIn in a route by passing it in as an argument.

Conclusion

To check if user is logged in with Passport.js, we can check is req.user is defined.