What is the Use of Router in Express.js ?
Last Updated :
08 Jan, 2025
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.
Similar Reads
What is the use of Backbone.js router ?
Backbone.js is a compact library used to organize JavaScript code. It is additionally regarded as an MVC/MV* framework. MVC is essentially an architecture paradigm for designing user interfaces, in case you are unfamiliar. It allows you to develop front-end applications in a much easier way by imple
3 min read
What is the use of next() function in Express.js ?
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss, the use of the next() function in every middleware of the express.js. There ar
2 min read
What is Express-rate-limit in Node.js ?
express-rate-limit is a middleware for Express.js applications that helps control the rate at which requests can be made to the server. It is particularly useful for preventing abuse by limiting the number of requests a client can make to your API within a specific time frame. This can help mitigate
3 min read
What is routing in Express?
In web applications, without routing it becomes difficult for the developers to handle multiple different requests because they have to manually process each URL request in a single function this problem was solved by the express router which provides a structured way to map different requests to th
5 min read
What is the use of the Fetch API in JavaScript ?
The Fetch API in JavaScript provides a modern, powerful, and flexible way to make HTTP requests from web browsers or Node.js environments. Its primary purpose is to facilitate fetching resources, typically data, from servers or other sources across the web. In simple terms, the Fetch API in JavaScri
2 min read
Express.js | router.use() Function
The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. Syntax: router.use( path, function )Parameters: Path: It is the path to this middleware, if we can have /user, now this middlewa
2 min read
What is Middleware in Express.js ?
Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
2 min read
Understanding the Function of a Wildcard Route in Express.js
In this article, we are going to learn about the Wildcard Route and its functions. Wildcard routes are the default case route. If a client requests a route that does not exist on the server, that particular route will be routed to the wildcard route; it is also known as the Error 404 route. Approach
2 min read
What is the purpose of module.exports in node.js ?
The module.exports is actually a property of the module object in node.js. module. Exports is the object that is returned to the require() call. By module.exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() meth
3 min read
What is the purpose of the compression middleware in Express JS ?
Middleware in Express JS is like a set of tools or helpers that helps in managing the process when your web server gets a request and sends a response. Mainly itâs work is to make the ExpressJS framework more powerful and flexible. It allows users to insert additional steps or actions in the process
2 min read