Express JS – Routing
When building scalable web applications, organizing your routes efficiently is key. [Link], a minimal
and flexible [Link] framework, provides an easy way to manage routing using its Router class. If
you've worked with simple route definitions in Express before, using [Link]() will take your
application to the next level in terms of structure and maintainability.
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 their
respective handlers.
What is the Express Router?
The Router in [Link] is a mini Express application without a complete set of middleware like the
main app object ( app ). It provides a way to create modular and mountable route handlers. This allows
you to keep your routes organized and manageable, especially in large applications.
While in smaller applications you may define routes directly on the app object, in larger projects, using
a Router helps break down the code into smaller, reusable components.
Think of a Router as a mini Express app that you can attach routes to and then plug into your main
Express app. This way, you can modularize routes based on features, resource types, or sections of
your app.
Why Use an Express Router?
Using a router has several benefits:
1. Code Organization: It allows you to split your routes across different files or modules, making your
code easier to manage.
2. Reusability: You can reuse route modules across different parts of your application or even different
projects.
3. Scalability: As your application grows, managing everything in one file becomes hard. Routers
make scaling your codebase simpler.
Setting Up and Using the Router
Let’s go step by step to set up and use an Express Router.
Step 1: Install Express
First, make sure you have Express installed:
npm install express
Step 2: Create a Simple Express App
Let’s start with a basic Express app. Create an [Link] file:
const express = require('express');
const app = express();
const port = 3000;
[Link](port, () => {
[Link](`Server running at [Link]
});
Step 3: Defining Routes Without a Router
If you’re not using a router, you would define routes directly on the app object like this:
[Link]('/', (req, res) => {
[Link]('Home Page');
});
[Link]('/about', (req, res) => {
[Link]('About Page');
});
While this is fine for smaller applications, as your app grows, this can quickly become overwhelming.
Here’s where the Router comes in.
Step 4: Using [Link]()
Creating a Router
Let’s refactor the previous example by creating a Router for the /about route.
1. Create a separate router file (e.g., [Link] ):
const express = require('express');
const router = [Link]();
// Define the routes for this router
[Link]('/', (req, res) => {
[Link]('About Page');
});
[Link] = router;
In your main [Link] , you’ll now import the router and tell your main app to use it:
const express = require('express');
const aboutRoutes = require('./aboutRoutes'); // Import the router
const app = express();
const port = 3000;
// Use the router for the /about path
[Link]('/about', aboutRoutes);
[Link]('/', (req, res) => {
[Link]('Home Page');
});
[Link](port, () => {
[Link](`Server running at [Link]
});
Now, the /about route is handled by the aboutRoutes router. If you visit
[Link] , you’ll see the response from the router.
Step 5: Organizing Routes with Multiple Routers
One of the great things about Express Router is that you can create multiple routers, each handling a
different section of your app.
Example: Adding a Users Router
1. Create a new router file for the /users routes (e.g., [Link] ):
const express = require('express');
const router = [Link]();
// Define routes for users
[Link]('/', (req, res) => {
[Link]('Users Home Page');
});
[Link]('/:id', (req, res) => {
const userId = [Link];
[Link](`User ID: ${userId}`);
});
[Link] = router;
Update your [Link] to use both routers:
const express = require('express');
const aboutRoutes = require('./aboutRoutes');
const usersRoutes = require('./usersRoutes');
const app = express();
const port = 3000;
[Link]('/about', aboutRoutes); // Use the /about router
[Link]('/users', usersRoutes); // Use the /users router
[Link]('/', (req, res) => {
[Link]('Home Page');
});
[Link](port, () => {
[Link](`Server running at [Link]
});
In this example, we have two routers: one for the /about path and one for the /users path. This
modular approach keeps your codebase cleaner and easier to maintain.
Middleware with Routers
Express Router supports middleware, allowing you to run custom logic for specific routes or groups of
routes.
Applying Middleware to a Router
For example, let’s add a logging middleware that logs the request URL and time for all routes within a
router.
1. Modify your [Link] file:
const express = require('express');
const router = [Link]();
// Middleware that logs the request details
[Link]((req, res, next) => {
[Link](`Request URL: ${[Link]}, Time: ${new
Date().toISOString()}`);
next();
});
[Link]('/', (req, res) => {
[Link]('About Page');
});
[Link] = router;
Now, every time a request hits any of the routes within the /about path, the middleware will log the
request URL and time.
Route Parameters with Routers
You can use route parameters in routers just like in regular routes. Route parameters allow you to
capture dynamic segments of the URL.
For example, in our [Link] , we already defined a parameterized route:
[Link]('/:id', (req, res) => {
const userId = [Link];
[Link](`User ID: ${userId}`);
});
In this case, :id is a route parameter. So, if a user visits /users/123 , the app will respond with User
ID: 123 .
CONCLUSION
[Link]() is such a useful tool to help us organize our routes in an exoress application to help
us stay being able to maintain the project as it scales more, organizing your routes and middlware files
in their respective directories is also crucial so we separate concerns as much as possible and maintain
an organized codebase that is easy to work with for both us and whoever will be in charge of the
project.