How do you handle nested routes in Express.js?

In this article we are going to learn that how can we setup nested routes in Express JS. Nested routes are the routes that are defined within other routes. This is used to organize your code.

We are going to implement the nested routes using the below given two approaches.

Table of Content

  • Using Express JS
  • Using Express JS Router

Using Express JS

We are going to create nested routes by using Express JS only, in which we will create nested routes with HTTP methods only, and we do not need to use any other module in it.

Syntax:

app.get('base URL',()=>{})
app.get('base URL/Nested URL',()=>{})

Example: Implementation of above approach.

Javascript




// Server.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
 
// Parent Route
app.get("/", (req, res) => {
    console.log("GET Request Successfull!");
    res.send("Get Req Successfully initiated");
})
 
// Nested Route
app.get("/user", (req, res) => {
    res.send(`Client is requesting for USER Data`)
})
 
// Nested Route
app.get("/user/:id", (req, res) => {
    res.send(`Client required ID -> ${req.params.id}`)
})
 
app.listen(PORT, () => {
    console.log(`Server established at ${PORT}`);
})


Output:

Using Express JS Router

Through the Express JS Router, we will create a base URL, and then we can directly use the router to implement a nested URL through it. The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. 

Syntax:

express.Router( [options] )

Example: This example implements nested routing using Express JS Router

Javascript




// Server.js
const express = require('express');
const app = express();
const PORT = 3000;
const router = express.Router();
 
// Nested Route
router.get('/', (req, res) => {
    res.send("USER NESTED API IS Endpoint!");
})
 
// Another Nested Route
router.get('/api', (req, res) => {
    res.send("/API endpoint")
})
// Parent Route
app.use('/user', router);
app.listen(PORT, () => {
    console.log(`Server established at ${PORT}`);
})


Output:



Contact Us