...

/

Introduction to Middleware

Introduction to Middleware

Understand and harness the power of middleware in Express.js to create flexible and modular applications.

Middleware functions execute at different stages of the request-response cycle, allowing us to intercept requests, modify data, enforce rules, and pass execution along a defined sequence. They are fundamental to Express applications, acting as the glue that connects different parts of our app.

In this lesson, we will focus on understanding what middleware is, how it executes, and how it fits into Express’s architecture.

What is middleware?

Middleware is a function that typically runs before the final request handler, but it can also execute after one—for example, during error handling or response modification. It allows us to process incoming requests, modify responses, and control execution flow.

Every middleware function receives three parameters:

  • req: This is the request object.

  • res: This is the response object.

  • next: This function passes control to the next middleware or route handler.

How middleware executes in Express.js

Middleware functions execute in the order they are registered using app.use(). When a request is made, Express processes middleware from top to bottom, invoking each middleware function sequentially.

const express = require("express");
const app = express();

const firstMiddleware = (req, res, next) => {
  console.log("First middleware executed");
  next(); // Pass control to the next middleware
};

const secondMiddleware = (req, res, next) => {
  console.log("Second middleware executed");
  next(); // Pass control to the route handler
};

app.use(firstMiddleware);
app.use(secondMiddleware);

app.get("/", (req, res) => {
  res.send("Hello, World!");
});

app.listen(3000, () => console.log("Server running on port 3000"));
Understanding middleware execution

Explanation:

  • Lines 1–2: Import the Express module and create an instance of an Express ...

Access this course and 1400+ top-rated courses and projects.