Middleware
Functions that run between the request and your handler — for parsing JSON, logging, auth and more.
What you will learn
- Understand the middleware concept
- Use express.json() to read request bodies
- Write your own middleware
Code that runs in the middle
Middleware are functions that sit between the incoming request and your route handler — like checkpoints a request passes through on its way in. Each one can inspect or change req/res, then call next() to pass the request along to the next checkpoint (or finally to your route).
Picture the journey of one request:
- A request arrives at the server.
- It hits
express.json(), which reads any JSON in the body and stores it onreq.body. - It hits the logging middleware, which prints the method and URL, then calls
next(). - Because
next()was called, the request reaches the matching route handler, which sends the response.
const express = require("express");
const app = express();
// Built-in middleware: parse incoming JSON into req.body
app.use(express.json());
// Custom middleware: log every request
app.use((req, res, next) => {
console.log(req.method, req.url);
next(); // pass control to the next handler
});
app.post("/users", (req, res) => {
res.json({ received: req.body }); // req.body works thanks to express.json()
});Note: Output (terminal, when a POST arrives at /users):
POST /users
Output (sent back to the caller):
{"received":{"name":"Asha"}}
app.use(...) registers a middleware that runs on every request. The first, express.json(), is built in — it turns the JSON a client sends into a usable req.body. The second is your own: it logs req.method and req.url, then calls next() so the request can continue. If you forgot next(), the request would hang forever, because nothing would pass it on. The route then echoes back req.body, which only has a value thanks to express.json().
Watch out: Without app.use(express.json()), req.body will be undefined for JSON requests. This middleware is essential for any API that receives data — add it near the top.
Tip: Middleware powers logging, authentication, CORS, body parsing, serving static files (express.static) and error handling. It is the “pipeline” every request flows through.
Q. What does app.use(express.json()) do?
✍️ Practice
- Add a logging middleware that prints the method and URL of every request.
- Add
express.json()and echo back a posted JSON body.
🏠 Homework
- Write a middleware that adds a timestamp to every request and logs it.