Express JS Router

πŸ“† Last updated Sep 03, 2019 πŸ‘· By, Chandan Tudu
Express JS Router

Create routes using the Express JS Router

In this chapter, you will learn about the express js router. Basically, It is used to creating routes.

Getting started

So go to your desktop and create a new folder and name it as you wish. This is our app folder.

Then go inside the app folder(express route) and here initialize the npm by executing the npm init command.

After initializing the npm now install express.js. To install express run npm install express --save command on your terminal.

Make sure that your app folder is selected on your terminal.

Files creation

Inside the app folder, we will create two files one is index.js file and another routes.js.


To create routes we will use express.Router. The express.Router class is used to create modular, mountable route handlers.

Note: A Router instance is a complete middleware and routing system.

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    res.send('<h1>Home Page</h1>');

router.get('/about', (req, res) => {
    res.send('<h1>About Page</h1>');

module.exports = router;


Now in the index.js we will be importing routes and applying as a middleware.

const express = require('express');
const app = express();
const routes = require('./routes');
// Applying as Middleware

app.listen(3000, () => console.log('Your app listening on port 3000'));


Browser Output
Home Page


Browser Output
About Page




Browser Output
Home Page


Browser Output
About Page


In all the above examples, you have to notice that –


Both work the same. But, you can avoid that by enabling the router’s strict mode.

Enable router strict mode –

const router = express.Router({strict:true});

Next is – Retrieve Post Data Using Express JS

Previous is – Express JS Route Handler

Leave a Reply

Your email address will not be published. Required fields are marked *