Node.js
Summary - Middleware
Combine app.use, Router and error middleware to write a logging system.
Summary: Logging system
In this lesson we combine what we learned into a logging system: global logger, router and error middleware together.
The flow is: app.use logs all requests; express.Router() groups routes under /api; error middleware catches unexpected situations. When a request arrives the logger runs first, then the route in the router. If an error occurs next(err) passes to the error middleware. This is the skeleton of real Express apps: modular routing + central logging + consistent error handling.
Combining the pieces
The system has three parts. First the global logger: app.use((req, res, next) => { console.log(req.method + " " + req.url); next(); });. Second the router: router.get("/items", handler) and app.use("/api", router). Third the error middleware: app.use((err, req, res, next) => { ... }).
These three parts work together. When a /api/items request arrives: the logger prints GET /api/items, the router finds the /items route and sends a response. On a /boom request: the logger runs, the route calls next(err), the error middleware catches it. Each part has a separate responsibility: logging, routing, error handling. This separation makes the code easier to maintain.
Exercise Build the logging system
Define const router = express.Router(). Add a logger with app.use: console.log(req.method + " " + req.url); next();. Add router.get("/items", (req, res) => res.send("Items")) and mount with app.use("/api", router). Add app.get("/boom", (req, res, next) => next(new Error("Crashed"))). Add 4-parameter error middleware: console.log("Error: " + err.message); res.status(500).send("Error"). The server requests /api/items.
Show example solution
const express = require("express");
const app = express();
const router = express.Router();
app.use((req, res, next) => {
console.log(req.method + " " + req.url);
next();
});
router.get("/items", (req, res) => res.send("Items"));
app.use("/api", router);
app.get("/boom", (req, res, next) => next(new Error("Crashed")));
app.use((err, req, res, next) => {
console.log("Error: " + err.message);
res.status(500).send("Error");
});
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/api/items", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
Which middleware logs all requests?
app.use((req, res, next) => { console.log(req.url); next(); })
- express.json()
- router.get
- app.use (logger)
- res.status(500)
Show answer
app.use (logger) — A logger added with app.use runs on all requests.
-
Match each piece to its role
- app.use (logger)
- Logs all requests
- express.Router()
- Groups /api routes
- next(new Error())
- Throws an error
- (err, req, res, next)
- Error middleware signature
Next lesson: Route parameters