Skip to main content

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:

  1. Read or modify the req object (the request);
  2. Read or modify the res object (the response);
  3. Stop the request (e.g. return an error or a response);
  4. Pass control onward, by calling the next() function.

You can picture it like this:

javascript
Client[Middleware 1][Middleware 2][Route Handler]Response

2. A simple middleware example

javascript
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:

javascript
GET / The method and URL get logged The response is sent

3. What a middleware's structure looks like

javascript
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

TypeWhere it's usedExample
Application-levelApplied to the whole appapp.use(...)
Router-levelOnly for a specific routerrouter.use(...)
Built-inBuilt into Express (express.json(), express.static())
Third-partyExternal packages (e.g. morgan, cors, helmet)
Error-handlingHandle errors, take 4 arguments (err, req, res, next)

5. An example with several middleware

javascript
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 /:

javascript
First middleware Second middleware Third: the route

6. Error-handling middleware

Error-handling middleware in Express always takes 4 arguments: (err, req, res, next)

javascript
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

javascript
// 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

MiddlewarePurpose
express.json()Parses a JSON request body
express.urlencoded()Parses data from HTML forms
express.static()Serves static files (HTML, CSS, JS, images)
PackagePurpose
morganRequest logging
corsAllowing cross-origin requests
helmetHardening HTTP headers
express-sessionUser 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 req and res;
  • 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.