Expressjs Router Explained with Examples

ExpressJS Router explained with examples | NodeJS

ExpressJS Router is a middleware in the Express.js framework that allows you to organize your routes and middleware functions into smaller, modular, and reusable pieces of code. It can be used to create multiple routers in a single application.

Express.js is a popular framework for building web applications in Node.js. It provides a simple, powerful way to create servers and handle HTTP requests. However, as your application grows in size and complexity, it can become challenging to manage your routes and middleware functions. One way to solve this problem is to use Express Router (opens in a new tab).

In this blog post, we’ll explore using Expressjs Router to create clean and maintainable routes in an Express.js application.

A Basic Express Application

Before we dive into using Express Router, let’s create a basic Express.js application. Open your favorite text editor and create a new file called app.js. In this file, we’ll create a simple Express.js application.

const express = require("express");
const app = express();
 
// route for home page
app.get("/", (req, res) => {
  res.send("Hello World!");
});
 
// route for user profile page
app.get("/profile", (req, res) => {
  res.send("User profile");
});
 
// route for updating user profile
app.put("/profile", (req, res) => {
  // update user profile logic
});
 
// route for deleting user account
app.delete("/account", (req, res) => {
  // delete user account logic
});
 
// route for login page
app.get("/login", (req, res) => {
  res.send("Login");
});
 
// route for login post request
app.post("/login", (req, res) => {
  // login logic
});
 
// route for registration page
app.get("/register", (req, res) => {
  res.send("Register");
});
 
// route for registration post request
app.post("/register", (req, res) => {
  // registration logic
});
 
// route for logout
app.get("/logout", (req, res) => {
  // logout logic
});
 
// start server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

In the code above, we first require the express module and create an instance of it. We’ve created multiple routes for editing the user profile and managing authentication.

With the number of routes increasing the code becomes messier and more difficult to understand.

The solution is to modify this working code to divide it into different routes based on their category (in our case, it’s user profile management and authentication management).

Modified using Router

Create a routes Directory, and create two different routes. Here the routes contains the two router files user.js and auth.js.

project/
├── node_modules/
├── routes/
│   ├── user.js
│   └── auth.js
├── app.js
└── package.json
const express = require("express");
const app = express();
 
const userRouter = require("./routes/user");
const authRouter = require("./routes/auth");
 
app.use("/user", userRouter);
app.use("/auth", authRouter);
 
// start server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

When we use app.use('/user', userRouter), we are telling Express to use the userRouter middleware for all routes that start with /user. Similarly, userRouter is used for all routes that start with /user.

Read More: How to use Express Middlewares with examples

Since you’re using app.use('/auth', authRouter), previously if you used to post on /register path to register a user, if you want to do the same, now you would need to send a request to /auth/register instead.

Now, let’s take a look at the user.js and auth.js files:

const express = require("express");
const router = express.Router();
 
// route for user profile page
router.get("/profile", (req, res) => {
  res.send("User profile");
});
 
// route for updating user profile
router.put("/profile", (req, res) => {
  // update user profile logic
});
 
// route for deleting user account
router.delete("/account", (req, res) => {
  // delete user account logic
});
 
module.exports = router;
const express = require("express");
const router = express.Router();
 
// route for login page
router.get("/login", (req, res) => {
  res.send("Login");
});
 
// route for login post request
router.post("/login", (req, res) => {
  // login logic
});
 
// route for registration page
router.get("/register", (req, res) => {
  res.send("Register");
});
 
// route for registration post request
router.post("/register", (req, res) => {
  // registration logic
});
 
// route for logout
router.get("/logout", (req, res) => {
  // logout logic
});
 
module.exports = router;

Basically, we are diving User management functions, and Authentication functions into two separate files so they don’t become almost unmanageable later.

Summing up

ExpressJS router along with controllers can be really useful to write easily management & clean code.

In your project, you’ll have numerous types of functions to take care of. With help of Routers, all those will be easily manageable.

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.