Routing deep dive in expressjs

basic · Express.js — Web APIs & middleware

1. The Theory: Modular & Hierarchical Routing Theory: In a basic setup, developers often put all routes in one file. As the app grows, this becomes a "spaghetti" mess . Separation of Concerns: Each resource (Users, Posts, Jobs) should have its own dedicated file . Hierarchical Relationship: Some resources "belong" to others . For example, a post doesn't exist in a vacuum—it belongs to a user . Hierarchical routing reflects this relationship in the URL structure: /api/users/:userId/posts . 2. Level 1: Resource Routing Theory: At the first level, we define the base resource. In Express, we use the Router object to create a mini-app that only handles a specific path prefix . The Process (routes/userRoutes.js): const express = require('express'); const router = express.Router(); // This matches: GET /api/users router.get('/', (req, res) => {   res.json({ message: 'List of all users' }); }); // This matches: GET /api/users/:id router.get('/:id', (req, res) => {   res.json({ message: `Fetching profile for user: ${req.params.id}` }); }); module.exports = router; 3. The "Deep Routing" Theory: MergeParams Theory: By default, parameters (like :id ) are local to their specific router . If you want a child router (Posts) to access a variable defined in a parent route (Users), you must use mergeParams: true . Without it: req.params.id would be undefined inside the post routes . With it: The child "inherits" the parameters from the parent route path . The Process (routes/postRoutes.js): app.js — entry point, mounts all routers const express = require('express'); const app = express(); const userRoutes = require('./routes/userRoutes'); // All user-related routes live under /api/users app.use('/api/users', userRoutes); app.listen(3000, () => console.log('Server running on port 3000')); routes/userRoutes.js — parent router, owns the :id param const express = require('express'); const router = express.Router(); const postRoutes = require('./postRoutes'); // GET /api/users router.get('/', (req, res) => { res.json({ message: 'List of all users' }); }); // GET /api/users/:id router.get('/:id', (req, res) => { res.json({ message: `User profile for ID: ${req.params.id}` }); }); // ⬇️ This is the key line — any request hitting /:id/posts // gets handed off to postRoutes. The :id param is captured HERE. router.use('/:id/posts', postRoutes); module.exports = router; routes/postRoutes.js — child router, NEEDS :id from parent const express = require('express'); // Without mergeParams: true → req.params.id is undefined in this file // With mergeParams: true → req.params.id is inherited from userRoutes const router = express.Router({ mergeParams: true }); // GET /api/users/:id/posts router.get('/', (req, res) => { res.json({ message: `All posts by User ID: ${req.params.id}` // req.params.id works ONLY because of mergeParams: true }); }); // GET /api/users/:id/posts/:postId router.get('/:postId', (req, res) => { res.json({ message: `Post ${req.params.postId} by User ${req.params.id}` // req.params.id → from parent (userRoutes) via mergeParams // req.params.postId → from this route's own /:postId }); }); module.exports = router; 4. The Integration Process Theory: Your main entry file ( app.js or server.js ) acts as the "Switchboard" . It connects the incoming request to the correct modular file based on the path . const express = require('express'); const app = express(); const userRoutes = require('./routes/userRoutes'); const postRoutes = require('./routes/postRoutes'); // Mount Level 1 routes app.use('/api/users', userRoutes); // Mount Deep Routes // We tell Express: Any request to /api/users/:id/posts should be handled by postRoutes app.use('/api/users/:id/posts', postRoutes); app.listen(3000, () => console.log('Server is running on port 3000')); .............................................................................................................................................................................................................

Back to Express.js — Web APIs & middleware

Browse all study material on Careeroza