Express Middleware

Understand how middleware works and learn app.use, built-in middleware, custom middleware, and route-specific middleware.

🎯 Introduction

Middleware is central to Express. Almost everything—JSON parsing, static file serving, logging, and authentication—builds on it. By the end of this article, you will understand what middleware is and its execution order, and be able to use built-in middleware and write your own.


🧱 What Is Middleware?

Middleware is a function that processes a request before (or after) it reaches a route handler.

Imagine the airport process: check-in → security → gate → boarding. Passengers (requests) pass through a series of checkpoints (middleware). Each checkpoint checks and clears them (calls next()) before they move on. If a checkpoint finds a problem, such as a missing ID, the passenger is stopped and does not proceed to the remaining checkpoints.

A middleware function receives three arguments:

const middleware = (req, res, next) => {
    // req: the request object, which you can read and modify
    // res: the response object; you can send a response here
    // next: call this function to continue to the next middleware
};

🛠 Application-wide Middleware with app.use

Middleware registered with app.use() without a path applies to all requests. Here is logging middleware that prints each request method and URL:

app.js
import express from 'express';

const app = express();

// Logging middleware: each incoming request passes through here first
app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

app.get('/', (req, res) => {
    res.send('Home page');
});

app.listen(3000);

Refresh the browser a few times, and the terminal prints GET /. Make sure to call next() here; otherwise, the request stops in this middleware and the browser keeps waiting.

Middleware has two ways to proceed: call next() to pass control onward, or send a response directly with a method such as res.send(). Every request must take one of these paths. Doing neither leaves the request hanging.

🪤 Execution Order: Top to Bottom

Express executes matching middleware and routes strictly in the order they are registered:

app.js
app.use((req, res, next) => {
    console.log('Middleware 1');
    next();
});

app.use((req, res, next) => {
    console.log('Middleware 2');
    next();
});

app.get('/', (req, res) => {
    console.log('Route handler');
    res.send('Home page');
});

Visiting / prints Middleware 1, Middleware 2, and Route handler, in that order. Like stages on an assembly line, changing the order can change the result. For example, placing JSON parsing middleware after a route means the handler cannot read the parsed request body.


🛠 Built-in Middleware: express.json

With the native http module, handling JSON submitted in a POST request requires listening to the data stream, combining chunks, and parsing them yourself. The built-in express.json() middleware does this for you and puts the result in req.body:

app.js
const app = express();

// Parse JSON request bodies so req.body is available afterward
app.use(express.json());

app.post('/users', (req, res) => {
    console.log(req.body); // { name: 'Ming', age: 18 }
    res.send('Created successfully');
});

Test it with curl in your terminal:

curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d "{\"name\":\"Ming\",\"age\":18}"
Without app.use(express.json()), req.body is undefined. This is a common beginner mistake: if an endpoint cannot read the submitted data, first check that this middleware is registered before the route.

🛠 Built-in Middleware: express.static

For static files such as images, CSS, and frontend build output, use express.static to serve an entire directory instead of writing a route for each file:

app.js
app.use(express.static('public'));

Create a public directory in your project and put logo.png in it. You can then access it at http://localhost:3000/logo.png. You can serve the dist directory generated by npm run build in a Vue project in the same way.


🛠 Route-specific Middleware

An unscoped app.use applies to all requests, but some checks belong to specific routes—for example, requiring login before viewing a profile. Place the middleware between the route path and its handler:

app.js
// Authentication middleware: check for a token header
const checkAuth = (req, res, next) => {
    if (!req.headers.token) {
        return res.status(401).send('Please log in first');
    }

    next();
};

// Only this route requires the authentication check
app.get('/profile', checkAuth, (req, res) => {
    res.send('Profile');
});

Requests to /profile pass through checkAuth first. Without a token, it returns 401 without reaching the handler. With a token, the request continues. Other routes are unaffected.


❓ Questions and Answers

Q1: What happens if I forget to call next()?

If no response is sent, the request stops in the current middleware, subsequent routes never run, and the browser waits until the request times out. When an endpoint appears unresponsive, check for a missing next() call.

Q2: How does middleware differ from a route handler?

They are fundamentally the same kind of function. By convention, functions that process or check requests without ending them are called middleware, while those that send the final response are called route handlers. Registering them with app.use or on a route determines their scope.

Q3: Can express.json() parse form data?

No. It parses request bodies with Content-Type: application/json. Traditional form submissions (application/x-www-form-urlencoded) require another built-in middleware, express.urlencoded({ extended: true }), which is less common in projects with separate frontends and backends.

Q4: Must the static file directory be called public?

No. express.static('dist') and express.static('assets') work too. Express serves whichever directory you specify. The name public is just a community convention.


🧪 Exercise

Write middleware that measures request duration: record the time when a request arrives, then print the elapsed milliseconds when the response finishes.

app.js
import express from 'express';

const app = express();

// Write your code here (hint: use Date.now() before next() and in a res finish event listener to calculate the duration after the response finishes)

app.get('/', (req, res) => {
    res.send('Home page');
});

app.listen(3000);

🎉 You now understand middleware, a core Express mechanism! Next, we will review the most useful APIs on the request and response objects.