Expressjs Middleware

Middleware is a function that runs between receiving a request and sending the response, its flow is as follow.

Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware in the stack.

Basic middleware

const express = require("express");

const app = express();

function myMiddleware(req, res, next) {
console.log("Middleware executed");
next();
}

app.use(myMiddleware);

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

app.listen(3000);

When you visit http://localhost:3000/
It will print “Middleware executed” in the CLI tool. While at the browser side it will show “Hello Expressjs”.

Middleware will not always call next, because it can also send response as can be seen in the following example.

function checkAge(req, res, next) {
    const age = 15;

    if (age < 18) {
        return res.status(403).send("Access denied");
    }

    next();
}

age < 18

Send response

STOP