Node.js Express Middleware

Functions that run between request and response.

✍️ 2 exercises in this lesson

Middleware functions receive (req, res, next). They can read or modify the request, end the response, or call next() to continue.

Uses: logging, authentication, parsing bodies, serving static files (express.static("public")), CORS and error handling.

An error-handling middleware has four arguments: (err, req, res, next).

Key Takeaways: Node.js Express Middleware

Mastering Node.js Express Middleware helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Node.js Express Middleware Code Example

Node.js
import express from "express";
const app = express();

// Logger for every request
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// Simple auth for /admin routes
function requireKey(req, res, next) {
  if (req.query.key !== "secret") return res.status(401).send("Unauthorized");
  next();
}

app.get("/admin", requireKey, (req, res) => res.send("Admin area"));
app.get("/boom", () => { throw new Error("Something broke"); });

// Error handler
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});

app.listen(3000);
Output
GET /admin
→ 401 Unauthorized
GET /admin?key=secret
→ Admin area
GET /boom
→ 500 {"error":"Something broke"}
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Node.js Express Middleware Practice Exercises

Check what you learned in “Node.js Express Middleware”.

/ 2 solved
Fill in the blank

Pass control to the next middleware.

app.use((req, res, next) => {
  console.log(req.url);
  ();
});
✓ Correct! Not quite. Try again.
Multiple choice

How many arguments does an error-handling middleware have?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services