Node.js
express.Router
Learn modular routing with express.Router.
Modular routing with express.Router
express.Router() creates a router object. A router can add routes like app but is mounted under a specific prefix with app.use. This lets you split routes into separate files.
Example: const router = express.Router(); router.get("/hello", handler); app.use("/api", router);. This handles a /api/hello request. The router uses router.get instead of app.get. You can mount multiple routers under different prefixes to split a large API into modules: a user router under /api/users, a product router under /api/products. Each router is defined in a separate file and mounted in the main app. This keeps the code organized.
Mounting a router
You mount a router with app.use(prefix, router). Example: app.use("/api", router). After this all routes in the router are accessible under the /api prefix. The router.get("/hello", ...) route handles a /api/hello request.
Paths inside a router are written without the prefix. You write router.get("/hello"), not router.get("/api/hello"). Express strips the prefix when forwarding the request to the router. This makes the router prefix-independent: you can mount the same router under /api or /v2 without changing the code inside. This flexibility makes patterns like API versioning easy.
Exercise Write a modular route with Router
Define const router = express.Router(). Add router.get("/hello", (req, res) => res.send("Hello")). Mount with app.use("/api", router). The server requests /api/hello.
Show example solution
const express = require("express");
const app = express();
const router = express.Router();
router.get("/hello", (req, res) => res.send("Hello"));
app.use("/api", router);
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/api/hello", (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.get
- Adds a route to router
- app.use('/api', router)
- Mounts the router
- /api/hello
- Full request path
-
Complete the router mount call
app.____("/api", router);
Show answer
app.use("/api", router);
-
What does express.Router() return?
const router = express.Router();
- Bir dize
- Bir router nesnesi
- A number
- Bir dizi
Show answer
Bir router nesnesi — express.Router() returns a router object.
Next lesson: Route groups