Express.js - routers
In this article, we would like to show you how to use routers in Express.js.
Normally, we define routes in Express.js using the following syntax:
xxxxxxxxxx
app.httpMethod(path, handler);
Where:
httpMethod
is one of the following requests:- GET
- POST
- PUT
- PATCH
- DELETE
path
is the route at which the request will run.
Practical example:
xxxxxxxxxx
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.send('Welcome to the users page!');
});
app.listen(5000);
Now, when we run the application and go to the localhost:5000/users we get the following result:

We can also define multiple different methods (such as GET, POST... ) for the same route.
Example:
xxxxxxxxxx
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.send('Welcome to the users page!');
});
app.post('/users', (req, res) => {
// ...
res.send('User created successfully');
});
app.listen(5000);
To easy maintain the application we need to separate the routes dedicated for users from our main index.js file. To do so we will use express.Router.
1. The first thing we need to do is create a new directory called routes and a file for our users routes - users.js. The project structure should now look as follows:
xxxxxxxxxx
project/
├─ node_modules/
└─ routes/
└─ users.js
├─ index.js
├─ package.json
└─ package-lock.json
2. Inside the users.js file, import express.Router and move the users requests from index.js to it.
users.js file:
xxxxxxxxxx
const express = require('express');
const router = express.Router();
// routes from index.js
router.get('/', (req, res) => {
res.send('Welcome to the users page!');
});
router.post('/', (req, res) => {
// ...
res.send('User created successfully');
});
//export this router to use it in index.js
module.exports = router;
Note:
Notice that now we use
router
instead ofapp
and we don't write'/users'
in the request path. We will specify it later in the index.js file.
3. Import the router
inside index.js file and specify the route.
xxxxxxxxxx
const express = require('express');
const app = express();
// import the router
const users = require('./routes/users.js');
// specify the route '/users' for '/' in users.js file
app.use('/users', users);
app.listen(5000);
Now the app.use()
function call on route '/users' attaches the users router with this route. Whatever requests our app gets at the '/users'
, will be handled by our users.js router. The '/'
route in users.js file is actually a subroute of '/users'
.
Run the app and go to the http://localhost:5000/users to see the result.
Result:
