Redirect with ExpressJS
Overview
Imagine you're at Disneyland and you're trying to get to the next ride. You ask a cast member for directions, and they tell you that the fastest way to get there is to take a shortcut through Fantasyland. However, when you get to Fantasyland, you see that the ride you wanted to go on is closed for maintenance.
You could keep walking around Fantasyland, hoping to find another ride that you'd like. Or, you could go back to the cast member and ask for a different route to your original destination.
When you encounter an inaccessible route or resource in Express.js, it's similar to seeking a ride at Disneyland that's closed for maintenance. Redirect in Express.js provides a new URL, and the browser receives a temporary redirect HTTP response with a new URL, which "redirects" the user to a new location.
Introduction to Redirect with ExpressJS
The res. redirect() method in ExpressJS can be used to execute a redirect. The client is given navigation instructions by this function, which accepts a URL as a parameter.
Redirecting is a crucial component of web development as it can assist us in handling user identification, adapting to structural changes, and improving user experience.
res.redirect() Function
The URL derived from the given path is redirected by the res. redirect() function, with the stated status being an integer (positive) that reflects an HTTP status code. A "302 Found" status is usual.
The browser will make a new HTTP request to the URL given in the parameter when the res. redirect() method is invoked. Depending on the procedure used to submit the initial request, this new request may be either a GET or a POST request.
You can add query parameters to the redirect URL in addition to just rerouting the visitor to a new URL. These parameters may be used to transmit information between sites or carry out particular tasks on the destination page.
Syntax
Parameter
Two parameters are accepted by the function as mentioned above:
- status: This parameter holds the HTTP status code. It's important to note that this is an optional parameter
- path: This parameter describes the path.
Return
It returns an Object.
Type paths we can enter
- Any worldwide URL can be entered. e.g: https://www.scaler.com/topics/
- The path may be relative to the hostname's base. e.g : if the current URL is http://hostname/user/cart and we use a relative path of /user, it will redirect to http://hostname/user
- The path can be relative to the current URL e.g : /addtocart with relative to http://hostname/user/ will redirect to http://hostname/user/addtocart
Examples
Example 1
In this example, code is designed to demonstrate how the res. redirect() function in Express.js can be utilized to redirect users to a different page when they access the root path ("/") with a GET request. If a user tries to access the root path of the website, they will be automatically directed to a different page.
Moreover, when a user accesses the "/user" path with a GET request, a message will be displayed stating` "Redirected to User Page" which then serves as confirmation that the user has been redirected to the desired page.
Console Output:
Browser Output:
Now open the browser and go to http://localhost:3000/, now on your screen you will see the following output:
Example 2
In this example, we see how we can authenticate and redirect users when they request the "/verify" path by the use of middleware in Express.js. When users make a GET request to the "/user" path we want to see a "User Page" message.
Console Output:
Now open the browser and go to http://localhost:3000/verify`, now check your console and you will see the following output:
Browser Output:
And you will see the following output on your browser:
Example 3
To pass data between route handlers using the next() function we can look at the following example
Example 4
HTTP redirects using ExpressJS by flash notifications
The HTTP redirect with a message to display in the views is a feature that is already present in frameworks like Laravel, and connect-flash is a module that actually lets us add it.
This module is built on the sessions that the express-session module allows us to create and manage. We then make a session and add the module as middleware to use it in Express.
Let's see it in action
The flash() method is added by this middleware for the sake of requesting an object. By the use as a setter, one can set up a message like this
We can retrieve the message using the same method as the getter because the key is the only argument.
the following information is displayed in the views:
<% if (message) { %>
<div class="alert alert-info"><%= message %></div>
<% } %>
This module thus effectively uses a feature that is very beneficial when carrying out HTTP transfers without a query string.
Basic use of res.redirect() function
By utilizing the res.redirect() function, you can send an HTTP response that includes a status code of 302, which redirects the user to a different URL. Once the redirect occurs, the HTTP client (such as a browser or Axios) will make a new HTTP request to the new URL.
The res.redirect() function allows you to create HTTP statuses other than 302 as well. Search engines will continue to crawl the original URL because the 302 states are viewed as temporary redirects. If you want to demonstrate that the URL has changed forever, you should transmit a response with HTTP status 301.
Handling POST Requests
There are some nuances in choosing the right status number for POST requests. Technically, HTTP 301 and 302 redirects don't always have to use the same technique or have the same content. HTTP 307 and HTTP 308 should be used instead of HTTP 302 and HTTP 301 respectively when forwarding a POST request.
Conclusion
- The res.redirect() method in ExpressJS can be used to execute a redirect. The client is given navigation instructions by this function, which accepts a URL as a parameter
- You can add query parameters to the redirect URL in addition to just rerouting the visitor to a new URL. These parameters may be used to transmit information between sites or carry out particular tasks on the destination page
- Search engines will continue to crawl the original URL because the 302 state is viewed as a temporary redirect. If you want to demonstrate that the URL has changed forever, you should transmit a response with HTTP status 301.
- HTTP 307 and HTTP 308 should be used instead of HTTP 302 and HTTP 301 respectively when forwarding a POST request
- The line app.get('*', handleRedirect) creates a route for all GET requests and sends them to the handleRedirect function to be redirected to the targetUrl. * is a wildcard that fits any path