Node.js
Router middleware
Learn to use middleware at the Router level.
Router middleware
express.Router() creates a router object. A router can add middleware and routes like app, but is mounted under a specific path prefix. router.use(fn) runs only for routes within that router.
Example: const router = express.Router(); router.use((req, res, next) => { console.log("Router: " + req.url); next(); }); router.get("/list", handler); app.use("/api", router);. Here router.use runs only for routes under /api. The difference from app.use is scope: app.use is app-wide, router.use is router-only. This makes it easy to split an API into modules.
router.use vs app.use
app.use runs app-wide, router.use runs only within that router. When a router is mounted with app.use("/api", router), its middlewares run only for requests starting with /api.
Inside a router, req.url shows the part after the mount path. For example, on a /api/list request the router middleware sees req.url as /list. This lets the router keep its own path logic independent. You can mount the same router under different prefixes: app.use("/api", router); app.use("/admin", router);. This improves code reuse.
Exercise Add Router middleware
Define const router = express.Router(). Add router.use((req, res, next) => { console.log("Router: " + req.url); next(); }). Add router.get("/list", (req, res) => res.send("List")). Mount with app.use("/api", router). The server closes itself.
Show example solution
const express = require("express");
const app = express();
const router = express.Router();
router.use((req, res, next) => {
console.log("Router: " + req.url);
next();
});
router.get("/list", (req, res) => res.send("List"));
app.use("/api", router);
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/api/list", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
Match each piece to its role
- express.Router()
- Creates a router object
- router.use
- Adds middleware to router
- app.use('/api', router)
- Mounts the router
- router.get
- Adds a route to router
-
Complete the router.use call
router.____((req, res, next) => { console.log("Router: " + req.url); next(); });
Show answer
router.use((req, res, next) => { console.log("Router: " + req.url); next(); });
-
What does app.use('/api', router) do?
app.use("/api", router)
- Deletes the router
- Moves all routes to /api
- Creates a router
- Mounts the router with the /api prefix
Show answer
Mounts the router with the /api prefix — The router is mounted under the /api prefix.
Next lesson: Error middleware