Protecting Routes with Middleware

Introduction

In this lesson, we will learn how to protect parts of our To-Do List application using middleware in Express.js. Middleware acts as checkpoints that control access to different routes. By the end of this lesson, you'll understand how to use middleware to enhance the security of your application, much like an office building's security system determines who can access different floors.

What You'll Learn

In this lesson, you'll learn:

  • What middleware is and why it's important.
  • How to set up middleware in Express.js.
  • How to use middleware to protect routes.
  • How to manage sessions for user authentication.

What Is Middleware?

Middleware in Express.js is a series of small programs that handle requests and responses. Imagine middleware as security checkpoints in a building; each checkpoint ensures only authorized individuals can proceed to certain areas.

Middleware can:

  • Execute any code.
  • Modify request and response objects.
  • End the request-response cycle.
  • Move to the next middleware function.

Middleware ensures your application is secure and functions properly by controlling the flow of requests and responses.

Step 1: Setting Up Express.js and MongoDB

Let's set up our Express.js application and connect to MongoDB. This is essential for a running server and a database to store user information.

const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');

const app = express();
const PORT = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/todo-app', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

Here, we import the necessary libraries, initialize an Express.js application, and connect to a MongoDB database named todo-app. Connecting to MongoDB is crucial for storing user data and managing user authentication.

Step 2: Setting Up Session Middleware

Sessions help track user information as they navigate through the app, similar to how an office maintains visitor logs.

// Middleware for sessions
app.use(session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: true
}));

In this step, we use the express-session middleware to manage sessions. We configure the session with a secret key to sign the session ID cookie, which helps prevent tampering. The resave option, set to false, ensures the session is not saved back to the session store unless it has been modified. The saveUninitialized option, set to true, saves new but unmodified sessions to the store. This setup allows the application to maintain state across multiple requests, essential for tracking logged-in users.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal