Categories
JavaScript Answers

How to add user authentication for Node.js?

Spread the love

Sometimes, we want to add user authentication for Node.js.

In this article, we’ll look at how to add user authentication for Node.js.

How to add user authentication for Node.js?

To add user authentication for Node.js, we can use Passport.

For instance, we write

passport.use(new LocalStrategy(
  (username, password, done) => {
    User.findOne({
      username,
      password
    }, (err, user) => {
      done(err, user);
    });
  }
));

app.post('/login',
  passport.authenticate('local', {
    failureRedirect: '/login'
  }),
  (req, res) => {
    res.redirect('/');
  });

to add Passport to the Express app we have.

We call passport.use with a LocalStrategy instance to let us authenticate users by looking them up from our own MongoDB database.

We use User.findOne to find the user.

Then we add the /login route that uses the middleware returned by passport.authenticate for authentication before we redirect to /.

Conclusion

To add user authentication for Node.js, we can use Passport.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *