Deep Routing

What is “Deep Routing”?

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'));



.............................................................................................................................................................................................................

Examples

1. GET: Read Data


Theory: GET is used to fetch information from the server. It is considered "Safe" because it should never modify the database state. It is also Idempotent, meaning calling it 1 or 100 times results in the same data output without side effects.

// Fetching all users
app.get('/users', (req, res) => {
  // Logic to fetch from DB
  res.status(200).json({ success: true, data: [] });
});



2. POST: Create Data


Theory: POST is used to submit data to be processed, resulting in the creation of a new resource. Unlike GET, POST is not idempotent—if you click "Submit" twice, you might accidentally create two identical records in your database.


app.post('/users', (req, res) => {

const newUser = req.body; // Data sent from frontend
  // Logic to save to DB
  res.status(201).json(newUser); // 201 means "Created"
});



3. PUT vs. PATCH: The Update Theory


Theory: Both are used for updates, but they handle data differently.

  • PUT (Full Replace): Expects the entire object. If you only send a "name," it may nullify the "email" and "age" fields because it replaces the whole record. It is Idempotent.

  • PATCH (Partial Update): Only modifies the specific fields you send. If you only send a "name," the "email" remains untouched.



// PUT: Overwrite the whole user
app.put('/users/:id', (req, res) => {
  res.json({ message: 'Resource fully replaced' });
});

// PATCH: Update only the provided fields
app.patch('/users/:id', (req, res) => {
  res.json({ message: 'Resource partially modified' });
});


4. DELETE: Remove Data


Theory: DELETE is used to remove a specific resource. Like PUT and GET, it is Idempotent; once a resource is deleted, calling the same delete request again doesn't change the fact that the resource is gone.



app.delete('/users/:id', (req, res) => {
  // Logic to find by ID and remove
  res.json({ message: `Resource with ID ${req.params.id} deleted` });
});


..............................................................................................................................................................................................................