Creating Login Functionality with Express.js

overview

In Express.js, the login functionality is implemented within a middleware function. A request object and a response object are passed as arguments to the middleware function. These objects are used for login processing, response generation, and so on.

Here, I will explain how to implement the login function in Express.js using the following versions.

Express.js v4.17.1
nodejs v19.7.0
express-session v1.17.2

In addition, all the code created this time is posted on GitHub.

How to create backend for login functionality

To implement the login process we will use the express-session middleware and the request object. express-session parses session information included in requests from clients. After a successful login, store the session in the request object’s session property.

The sample code below is an example to understand the login function in Express.js. Receives a POST request, processes the user’s login, and returns a response containing the result.

login.js

const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();

app. use(
  session({
    secret: "your secret",
    save: false,
    saveUninitialized: true,
    cookies: {
      secure: process.env.NODE_ENV === "production" ? true : false,
      sameSite: "Strict",
    },
  })
);
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: false }));
app.set("view engine", "ejs"); // added

// Middleware to check login status
function checkAuthenticated(req, res, next) {
  if (req.session.loggedin) {
    next();
  } else {
    res.redirect("/");
  }
}
app. get("/", (req, res) => {
  res.render("index"); // fix
});
// dashboard route handler
app.get("/dashboard", checkAuthenticated, (req, res) => {
  res.render("dashboard", { username: req.session.username });
});

app.post("/login", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  req.session.loggedin = true;
  req.session.username = username;

  res.redirect("/dashboard"); // Redirect to dashboard
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Commentary

Below is a detailed explanation of the code.

  • Load the required modules.
const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const path = require("path");

These modules provide the basic functionality required for web application development on express.

  • Create an application instance for express.
const app = express();

This creates a web server that accepts HTTP requests and returns responses.

  • Configure session middleware.
app. use(
session({
    secret: "your secret",
    save: false,
    saveUninitialized: true,
    cookies: {
    secure: process.env.NODE_ENV === "production" ? true : false,
    sameSite: "Strict",
    },
})
);

This middleware manages session data for client requests.

  • Set up a directory for hosting static files.
app.use(express.static(path.join(__dirname, "public")));

Files in the “public” directory will be directly accessible from the browser.

  • Configure request body parsing.
app.use(bodyParser.urlencoded({ extended: false }));

This allows parsing URL-encoded request bodies.

  • Configure the view engine.
app.set("view engine", "ejs");

Set EJS as the view engine. This allows EJS templates to be rendered.

  • Define middleware to check login status.
function checkAuthenticated(req, res, next) {
  if (req.session.loggedin) {
    next();
  } else {
    res.redirect("/");
  }
}

This function checks that the request is from a logged in user and redirects to the login page if not.

  • Handle GET requests to the root path ("/").
app. get("/", (req, res) => {
  res.render("index"); // fix
});

This will render the “index.ejs” template when a user visits the root of your website.

  • Handle GET requests to the dashboard.
app.get("/dashboard", checkAuthenticated, (req, res) => {
  res.render("dashboard", { username: req.session.username });
});

This route is only accessible to logged in users. The checkAuthenticated middleware ensures this.

  • Handle POST requests to login.
app.post("/login", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  req.session.loggedin = true;
  req.session.username = username;

  res.redirect("/dashboard"); // Redirect to dashboard
});

This will process the data submitted from the login form and create a login session.

  • Start your application on port 3000.
app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.

How to create a frontend for the login functionality

Add the following code to “views/index.ejs” to create the login form.

views/index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>Login Page</title>
  </head>
  <body>
    <h1>Login</h1>
    <form action="/login" method="POST">
      <label for="username">Username:</label><br />
      <input type="text" id="username" name="username" /><br />
      <label for="password">Password:</label><br />
      <input type="password" id="password" name="password" /><br />
      <input type="submit" value="Login" />
    </form>
  </body>
</html>

Add the following code to “views/dashboard.ejs” to create a dashboard after login. views/dashboard.ejs

<!-- views/dashboard.ejs -->
<!DOCTYPE html>
<html>
  <head>
    <title>Dashboard</title>
  </head>
  <body>
    <h1>Welcome, <%= username %>!</h1>
    <p>This is your dashboard.</p>
  </body>
</html>

After creating all the files, the directory structure will be as follows.

certification
|- views
| |- dashboard.ejs
| |- index.ejs
|- app.js
|-package.json
|-package-lock.json

After creating all the files, run the following command to start the server.

node app.js

summary

This article showed how to implement login functionality using Express.js. Specifically, it showed how to use the express-session middleware and the body-parser module to handle user login and return the result as a response. Login functionality plays a very important role in web applications, so it’s important to understand how to implement it. I hope this article helps you understand it.