Open In App

What is the Use of Router in Express.js ?

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Express.js is a powerful and flexible web application framework for Node.js. It simplifies the process of building server-side applications and APIs by providing robust features and tools. Among these tools, routers play a pivotal role in managing and organizing the routes within an application. This article delves into the concept of routers in Express.js, explaining their purpose, how they work, and best practices for using them effectively.

What is a Router in Express.js?

In Express.js, a router is a mini-application capable of performing middleware and routing functions. It is an isolated instance of middleware and routing, allowing you to create modular and mountable route handlers. A router behaves similarly to the main express object, but it is used to handle routing for specific subsets of an application.

Routers in Express.js help in managing different parts of your application by grouping routes logically and keeping them separate from other components. This modular approach makes your application more manageable and easier to maintain.

Syntax:

express.Router( [options] )

Parameters:

This function accepts one optional parameter whose properties are shown below.

  • Case-sensitive: This enables case sensitivity.
  • mergeParams: It preserves the request params values from the parent router.
  • strict: This enables strict routing.

Return Value:

This function returns the New Router Object.

Why Use Routers in Express.js?

Modularity and Organization

Using routers allows you to break down your application into smaller, manageable chunks. Instead of having all your routes in a single file, you can divide them into different modules, each handling a specific part of the application. For instance, you can have separate routers for user management, product listings, and order processing.

Code Reusability

Routers promote code reusability by allowing you to define middleware and route handlers that can be reused across different parts of your application. You can create a router once and mount it in multiple places if necessary.

Middleware Handling

Routers can handle middleware specific to a particular route or group of routes. This means you can apply middleware to certain routes without affecting the entire application. Middleware such as authentication, logging, and input validation can be applied selectively.

Easier Testing and Debugging

With routers, each part of your application is encapsulated, making it easier to test and debug. You can test individual routers in isolation, ensuring that specific routes and their associated middleware work as expected.

Scalability

As your application grows, managing all routes in a single file can become unwieldy. Routers allow you to scale your application by keeping route definitions separate and organized, making it easier to add new features without disrupting the existing codebase.

Installation Steps

Step 1: Make a folder structure for the project.

mkdir myapp

Step 2: Navigate to project directory

cd myapp

Step 3: Initialize the NodeJs project inside the myapp folder.

npm init -y

Step 4: Install the necessary packages/libraries in your project using the following commands.

npm install express

Project Structure:

"dependencies": {
"express": "^4.19.2",
}

Example: Implementation to show the use of router in expressJS.

JavaScript
// home.js

// Importing express module
const express = require("express")

// Creating express router
const router = express.Router()

// Handling request using router
router.get("/home", (req,res,next) => {
    res.send("This is the homepage request")
})

// Exporting router
module.exports = router
JavaScript
// login.js

// Importing the module
const express = require("express")

// Creating express Router
const router = express.Router()

// Handling login request
router.get("/login", (req,res,next) => {
  res.send("This is the login request")
})

module.exports = router
JavaScript
// index.js

// Requiring module
const express = require("express")

// Importing all the routes
const homeroute = require("./routes/Home.js")
const loginroute = require("./routes/login")

// Creating express server
const app = express()

// Handling routes request
app.use("/", homeroute)
app.use("/", loginroute)

// Server setup
app.listen((3000), () => {
    console.log("Server is Running")
})

Step to run the application: Run the server.js using the following command

node server.js

Output: We will see the following output on the terminal screen.

Server is Running

Now go to http://localhost:3000/login and http://localhost:3000/home, we will see the following output on the browser screen.



Next Article

Similar Reads