Categories
JavaScript Answers

How to implement login auth in Node.js?

Spread the love

To implement login auth in Node.js, we add a middleware to check for authentication and a login and logout route.

For instance, we write

const checkAuth = (req, res, next) => {
  if (!req.session.userId) {
    res.send("You are not authorized to view this page");
  } else {
    next();
  }
};

app.get("/my_secret_page", checkAuth, (req, res) => {
  res.send("You are logged in");
});

app.post("/login", (req, res) => {
  const post = req.body;
  if (post.user === "john" && post.password === "johnspassword") {
    //...
    req.session.userId = userId;
    res.redirect("/my_secret_page");
  } else {
    res.send("Bad user/pass");
  }
});

app.get("/logout", (req, res) => {
  delete req.session.userId;
  res.redirect("/login");
});

to define the checkAuth middleware function to check for the userId property in the session.

If it’s set, then the user is logged in and we call next.

Otherwise, we call res.send to return an error response.

Then we add the /my_secret_page route with app.get.

We call checkAuth before calling the route handler to check for authentication before sending the response.

Next we add the /login route that checks for the user and password from the req.body request body.

If they match, then we set req.session.userId since the user is authenticated.

And we call redirect to the /my_secret_page route.

Otherwise, we send an error response.

Finally, we add a /logout route that deletes the userId from req.session and redirect to /login

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 *