Modular Route Routers
The Traffic Jam
Section titled “The Traffic Jam”If we keep piling every single route into our main app.js file, we’re going to create a massive traffic jam. Navigating a 500-line file to find one route is like trying to drive through downtown during rush hour—inefficient and infuriating.
We use Express Router to build modular, “local” road networks.
Modular Express Lanes
Section titled “Modular Express Lanes”
Fig 1: Segregated Traffic. Clean lines, high speed.
Professor Solo’s Directive (Speed vs Sanity): When we talk about “speed” here, we are talking about development speed. Splitting your code into multiple files does not make the Node server run faster. In fact, it’s technically a microsecond slower due to the extra file lookups.
But we don’t care. We do this because working on a 10,000 line
app.jsfile is a nightmare. Modular code enables teams to move fast without crashing into each other.
The Router Module
Section titled “The Router Module”- Create a Router File (e.g.,
routes/thingRouter.js). - Define Routes on that router, not the main app.
- Export the router.
routes/thingRouter.js
Section titled “routes/thingRouter.js”const express = require('express');const router = express.Router(); // A mini-app instance
// We define our routes here// Note: We are using the FULL path for now.router.get('/things', (req, res) => { res.send('List of Things');});
router.get('/things/:id', (req, res) => { res.send('Details of Thing');});
module.exports = router;Now we have a self-contained module. But it’s not connected to the highway yet.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Router (No Base Path) - Demo Repo
Express Router API