Categories: Express JS

Express Router: No. 1 Easy static & dynamic routing tutorial

Express router helps in defining URL for web applications and APIs. It makes easier to create SEO friendly URLs.

What is express router?

When we are dealing with complex applications which needs a big list of routes, it becomes difficult to handle everything in single index.js file. To avoid this, we can use Express.Router and create a separate file named routes.js in the same directory where index.js exists. Now add the following code in your routes.js file. All the express router routes will be added in routes.js file.

var express = require('express');
//initialize router
var router = express.Router();

//get request
router.get('/home', function(request, response){
    response.send("Welcome to GET");
});
//post request
router.post('/home', function(request, response){
    response.send("Welcome to POST");
});

//it enables to include this file's code in index.js file
module.exports = router;

Update your index.js as below:

//imports express module
let express = require('express');
//initializes express app
let app = express();
//import routes
let routes = require('./routes.js');

app.use('/routes', routes);

//listens to server at port 3000
app.listen(3000);

Now you will not be able to access directly http://localhost:3000/home. To access home, you will need to route through /routes as http://localhost:3000/routes/home . This is useful when you want to separate routes belonging to one module in one file. It makes easier to maintain the routes for complex applications.

Look at one thing, you can access home but cannot pass any value to it. Home page of any website is common for all the users, but profile of each user is different. If you have knowledge of databases, id is a primary key assigned to every record in a table. What if you are required to fetch a user profile like facebook user profile link.

We have only studied static routing in Express JS yet. Now we will move towards learning Dynamic Routing in Express JS which will help us in building URLs as per our requirements.

Dynamic Routing and URL Building in Express JS

Dynamic Routing allows us to pass parameters and values in routes on the basis of which the server processes our request and sends back the response. This is not fixed or static. The value of parameter can be changed.

For understanding purpose, let’s see Facebook profile link https://fb.com/itsaareez1 where itsaareez1 is profile’s username. Every user has a unique username so, this value will vary according to user. This is dynamic routing.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//where username is variable starting with colon
app.get('profile/:username', function(request, response){
    response.send('Welcome to ' + request.params.username + ' profile.');
});

//listens to server at port 3000
app.listen(3000);

You can see I have accessed http://localhost:3000/profile/itsaareez1 and received response Welcome to itsaareez1 profile.

Now let’s pass BestCyberHacks as value, you will see the result as below.

You can also pass multiple parameters to URL in Express JS. The following code takes username and post id as parameter.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//where username is variable starting with colon
app.get('/profile/:username/:post_id', function(request, response){
    response.send('Welcome to ' + request.params.username + ' profile. We are fetching post_id' 
    + request.params.post_id);
});

//listens to server at port 3000
app.listen(3000);

The output of above code is given below.

In the above examples, we have used request.params.parameter_name to access the given value where parameter_name is replaced with original parameter name.

Pattern Matched Routes in Express JS

Express router also supports pattern matching in its routing to restrict the values passed to URL parameter. For example, if you want to take minimum and maximum 2 digits numeric post_id, you may use regular expressions as [0-9]{2} where we limit the length in curly bracket and define range in square brackets enclosed in parentheses.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//where username is variable starting with colon
app.get('/profile/:username/:post_id([0-9]{2})', function(request, response){
    response.send('Welcome to ' + request.params.username + ' profile. We are fetching post_id' 
    + request.params.post_id);
});

//listens to server at port 3000
app.listen(3000);

Now I have accessed http://localhost:3000/profile/BestCyberHacks/54, it worked fine as shown below.

But when I have changed value of post_id to 1 digit or more than 2 digits, it resulted in the following error.

As only numeric value is acceptable, when I used the link http://localhost:3000/profile/BestCyberHacks/a4, it resulted in the following error.

A user can access the URL in many ways. An application has limited number of routes defined but there are unlimited possibilities that a user can enter to access. To avoid the requests for invalid routes, we may use * as route. The code is shown below.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//home route
app.get('/home', function(request, response){
    response.send('Good response!');
});
//where username is variable starting with colon
app.get('*', function(request, response){
    response.send('Invalid URL');
});

//listens to server at port 3000
app.listen(3000);

Now when you will access application using URL http://localhost:3000/home, it will give response as Good Response! But for all other URLs, application will give response Invalid URL.

In this tutorial, you have learnt about Express routerIn the next tutorial, you will learn about middleware in Express JS.

Arslan ud Din Shafiq

Alibaba Cloud MVP, Alibaba Cloud Technical Author, Dzone MVB, Software Engineer, Software Developer, Software Designer, Web Engineer, Web Developer, Web Designer, Database Designer, Database Developer, Cloud Computing Specialist, Linux Expert, Servers, 3D Modeling, Blogger, Facebook Map Editor, Google Map Editor

Share
Published by
Arslan ud Din Shafiq

Recent Posts

Serverless Computing: Benefits, Challenges, and the Code-Free Frontier

Serverless computing has become a game-changer in the cloud development landscape. By abstracting away server… Read More

27 mins ago

Demystifying the Cloud: A Guide to Cloud Storage Solutions

The digital age has brought an explosion of data. From personal photos and documents to… Read More

43 mins ago

Containers vs. Virtual Machines (VMs): Powering Up Your Cloud Environment

In the ever-evolving landscape of cloud computing, selecting the right tools for your applications is… Read More

2 hours ago

Cloud Computing: The Rocket Fuel for Business Digital Transformation

Cloud Computing is present and future of remote technologies. In today's dynamic business landscape, digital… Read More

4 hours ago

How To Set Up Secure Nginx Server Blocks on Ubuntu 22.04

NGINX Server Nginx, a popular open-source web server, excels at handling high traffic websites efficiently.… Read More

1 week ago

The Web Server Showdown: Nginx vs. Apache, LiteSpeed, Caddy, and Beyond

In the realm of web hosting, choosing the right web server is paramount. It acts… Read More

1 week ago