Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
More about Redirects
3.
Redirect with ExpressJS
3.1.
Syntax
3.2.
Example
3.3.
Implementation
3.3.1.
Installing expressJS
3.3.2.
Create the JavaScript file
3.3.3.
Run the index.js file
4.
Frequently Asked Questions
4.1.
How can we redirect with ExpressJS using a different status code?
4.2.
What are some alternatives to the res.redirect method?
4.3.
How can we redirect to a specific route using URL parameters in ExpressJS?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Redirect with ExpressJS

Author Aayush Sharma
0 upvote

Introduction

Have you ever wondered how web pages on the internet redirect you to somewhere else? You get magically transported to a webpage with a different web address when you click on a link. This is made possible with the use of redirects.

redirect with ExpressJS

Redirects refer to forwarding a user from one URL to another. These redirects are used to enhance the experience of the user. Instead of providing all the content on the same URL, the content can be distributed across multiple URLs. The user can then be redirected to relevant URLs whenever necessary.

In this blog, we will learn how to Redirect with ExpressJSExpressJS is a popular web application framework for Node.jsThis blog will increase your understanding of redirects in ExpressJS. After reading this blog, you can apply to Redirect with ExpressJS in your projects and websites. But first, let us look in a bit of detail about redirecting in general.

More about Redirects

As discussed above, Redirecting is the process of forwarding a user from one URL to another. Whenever a redirect occurs, a particular web page user is automatically sent to a different URL.
A particular HTTP status code specifies several types of Redirects. Some of the most common of them are discussed below.
 

301 Moved Permanently - This status code indicates that the requested URL has been permanently shifted to a new location.

301 Moved Permanently


302 Found - This status code signifies that the URL is temporarily moved to a new location. The original URL may be available again in the future.

302 Found


308 Permanent Redirect - This redirect was made to be used permanently. This redirect is very similar to 301. However, it ensures that the requests made to the old URL are redirected to the new URL.

308 Permanent Redirect


401 Unauthorized - This status code informs that access to the requested URL is not authorized to the user. The user should provide valid credentials to access the URL.

401 Unauthorized


404 Not Found -  This status code indicates the webpage could not be found. This usually happens when the URL is no longer available.

404 Not Found


500 Internal Server Error - This status code is shown when an internal server error prevents the server from completing the request.

500 Internal Server Error


As discussed above, each of these redirects has a specific purpose. This allows the developers to guide the users to the correct URLs and ensure a good user experience.

Redirect with ExpressJS

To use Redirect with ExpressJs, we can use the res.redirect() method. This method redirects the user to a different URL. By default, the status code set is 302 Found.

Syntax

res.redirect ( status, path)

The redirect function takes two parameters as status and path. The status parameter holds the HTTP status code, whereas the path parameter specifies the URL to which the user should be redirected.

To perform a redirect to a new URL, we need to define a routed handle and the define res.redirect() function inside it.

Example

Code

app.get("old-url" , (req,res) => {
	res.redirect(301, "new-url");
});

In the above code, 301 status indicates that the redirection is permanent. Whenever a request is made to the "old-URL," the server will redirect to the "new-URL."

We can also specify the URL directly in the res.redirect function, as shown below.

Code

app.get("old-url" , (req,res) => {
	res.redirect("https://www.codingninjas.com/");
});

Now we will discuss the steps to write a fully functioning program that uses redirect with the help of ExpressJS.

Implementation

Installing expressJS

To create a redirect with ExpressJS, we must install Express.js locally. You can install express.js by the following command.

npm install express

Create the JavaScript file

After we have installed express.js, we should create the main index.js file, which will contain the JavaScript code for redirection.

Code

const express = require("express");
const app = express();
const PORT = 3000

app.get("/" , function ( req, res) {
	console.log("redirecting to codingninjas.com");
	res.redirect("https://www.codingninjas.com/");
});

app.listen(PORT, function (err) {
	if (err) {
		console.log (err);
	}
	else{
		console.log("Listening on PORT ", PORT);
	}
});

 

Explanation 

First, we import the "express" module using the command require("express").

After that, we create an instance of the express app, which is stored in the const variable app.

Then we declare a const variable PORT and set its value to 3000, which we will use to listen to the incoming requests in the future.

Then we set up the route for the HTTP get method. It takes two arguments, the root path and the callback function. This callback function is executed when a request is made to this route.

Run the index.js file

The last step in running the server is to run the index.js file using the command given below.

node index.js

This will start the server at the specified port, which is 3000.

Output

output of console

This output shows that the server has started listening to our application on port 3000. The second line indicates that the server has successfully redirected the user to the indicated website, "codingninjas.com" in our case.

Frequently Asked Questions

How can we redirect with ExpressJS using a different status code?

ExpressJS provides the facility to redirect to any URL with any status code. By default, the status code is set to 302. We can change the status code in the res.redirect() function by passing the new status code as the first parameter.

What are some alternatives to the res.redirect method?

There are many alternatives to the res.redirect() method in Express.js. These alternate methods include manually setting the status code, using res.writeHead() and res.end() to set the headers, or using res.location() and res.statusCode to set the location and status code separately.

How can we redirect to a specific route using URL parameters in ExpressJS?

We can redirect to specific routes with URL parameters in Express.js by constructing the URL with the desired parameters. We can build the required URL as a string with the received parameters and then use it in the res.redirect function.

Conclusion

In this article, we discussed about Redirect with ExpressJS. We learnt about various types of redirects and their status codes. We also discussed how to use redirecting in your own application using ExpressJS with a fully functional codeSo now that you have learned about Redirect with ExpressJS, you can also refer to other similar articles.

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass