← Back to Node.js Course | Chapter 7: Express.js Basics | Lesson 4 of 7

Middleware

Middleware are functions that run in order on every request before your route, able to change request and response.

In this page:

  1. Middleware
Syntax
javascript
app.use((req, res, next) => {
  // modify req or res
  next();
});

Middleware

A middleware has the signature (req, res, next). It can modify req or res, end the response, or call next to pass control on.

Register with app.use. Built-in ones include express.json and express.static, and third-party ones cover logging, CORS and auth.

Note: Forgetting next() makes requests hang.

Example: Middleware

bash
const express = require("express");
const app = express();
app.use((req, res, next) => {
  req.startedAt = Date.now();
  console.log(req.method, req.url);
  next();
});
app.use(express.json());
app.get("/", (req, res) => res.send("ok in " + (Date.now() - req.startedAt) + "ms"));
app.listen(3000);

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting to call next
  2. Registering middleware after routes
  3. Calling next after sending a response
Chapter Summary
  • Signature is (req, res, next)
  • app.use registers it
  • next passes control
  • Order matters
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.