What is middleware in Express.js?
1. What middleware is in Express.js
Middleware is a function that runs between receiving the request (Request) and sending the response (Response).
Every middleware can:
- Read or modify the
reqobject (the request); - Read or modify the
resobject (the response); - Stop the request (e.g. return an error or a response);
- Pass control onward, by calling the
next()function.
You can picture it like this:
Client → [Middleware 1] → [Middleware 2] → [Route Handler] → Response2. A simple middleware example
const express = require('express');
const app = express();
// Middleware: logging every request
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // pass control to the next handler
});
app.get('/', (req, res) => {
res.send('Home page');
});
app.listen(3000, () => console.log('Server running'));On every request:
GET /
→ The method and URL get logged
→ The response is sent3. What a middleware's structure looks like
function middleware(req, res, next) {
// 1. Do something with the request
// 2. Optionally modify res (e.g. add a header)
// 3. Must call next() if we want to continue the chain
}If next() is not called, the chain breaks,
Express never reaches the next middleware or route.
4. Types of middleware in Express
| Type | Where it's used | Example |
|---|---|---|
| Application-level | Applied to the whole app | app.use(...) |
| Router-level | Only for a specific router | router.use(...) |
| Built-in | Built into Express (express.json(), express.static()) | |
| Third-party | External packages (e.g. morgan, cors, helmet) | |
| Error-handling | Handle errors, take 4 arguments (err, req, res, next) |
5. An example with several middleware
app.use(express.json()); // a built-in middleware for JSON parsing
app.use((req, res, next) => {
console.log('First middleware');
next();
});
app.use((req, res, next) => {
console.log('Second middleware');
next();
});
app.get('/', (req, res) => {
res.send('Third: the route');
});Output for GET /:
First middleware
Second middleware
Third: the route6. Error-handling middleware
Error-handling middleware in Express always takes 4 arguments:
(err, req, res, next)
app.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(500).send('Something went wrong');
});This middleware is called whenever an error happens somewhere in the code, or you call next(err).
7. A practical middleware example
// Checking a token
function authMiddleware(req, res, next) {
if (req.headers.authorization === 'secret123') {
next(); // all good, continue
} else {
res.status(401).send('Access denied');
}
}
app.get('/private', authMiddleware, (req, res) => {
res.send('Secret information');
});Now /private is only reachable with the correct header.
8. Express's built-in middleware
| Middleware | Purpose |
|---|---|
express.json() | Parses a JSON request body |
express.urlencoded() | Parses data from HTML forms |
express.static() | Serves static files (HTML, CSS, JS, images) |
9. Popular third-party middleware
| Package | Purpose |
|---|---|
| morgan | Request logging |
| cors | Allowing cross-origin requests |
| helmet | Hardening HTTP headers |
| express-session | User sessions |
| body-parser (deprecated, now built in) | Request-body parsing |
10. Summary
Middleware in Express.js is functions that run in the HTTP request-processing chain.
They can:
- modify
reqandres;- perform checks, logging, parsing, etc.;
- pass control onward via
next();- handle errors.
Middleware is what makes Express a flexible, modular, and extensible framework.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.