Easy Ways to Redirect URL in Node.js (Express & HTTP Module)

Robin
September 2, 2022

We often face the requirement to redirect from one URL to another in Node.js while creating a web server. We can develop a server using a framework like Express or using the Node.js core HTTP module.

The Express framework has a res.redirect() method that redirects from an URL to a different URL with the 302 status code by default. It also accepts other status codes if necessary. The browsers will understand the redirect and load from the new URL.

There are many situations where we need to use redirects in our applications. If you change the domain name of your website, you will want to redirect the users to the new domain.

Sometimes we move a page to a different URL. We can also redirect from HTTP to HTTPS in a Node.js server using the following techniques.

In this article, we will create servers using the Express framework and the Node.js HTTP module. You will learn how to redirect from both servers.

Easy Ways to Redirect URL in Node.js (Express & HTTP Module)

Node.js Redirect Using Express res.redirect() Method

When you create a route in the express server, you automatically get access to the request and response objects. These objects have different properties and methods.

One of them is redirect() method in the response object. This method is used to redirect from one route to another within the same domain. You can also use this method to redirect your user to an external URL.

          const express = require('express');

const app = express();

app.post('/login', (req, res) => {
    // Validate username and password

    res.redirect('/dashboard');
});

app.get('/dashboard', (req, res) => {
    // Validate if user is already logged in

    res.status(200).send('<h1>Dashboard</h1>');
});

app.listen(3000, () => {
    console.log('Server is running at http://localhost:3000');
});

        

I have added 2 routes "/login" and "/dashboard" in my express server. When a user provides a valid username and password, I will redirect that user to the dashboard route.

That's why at the end of the "/login" route, I will call the res.redirect() method with the URL for the dashboard route. You can use both relative URLs and absolute URLs in this method.

By default the res.redirect() method will send the response with the 302 status code. But you can set other status codes if you need.

          res.redirect(301, '/products');
        

If you want to set a custom status code for your redirect, you will pass your status code as the first parameter in this method. Then you can write the target URL in the second parameter.

This will override the default status code for the redirect() method and express server will it instead.

          res.redirect(301, 'https://www.example.com');
        

When we use a relative path, it redirects to the same domain. But you are not limited to using the relative URLs only. You can redirect your users to an external website using an absolute URL.

In this example, I am redirecting my users to a totally different website using its domain name.

          res.redirect('back');
        

You can also go back to the previous page by using "back" to the res.redirect() method.

Also Read: Best Setup to Use TypeScript with Node.js and Express Project

Node.js Redirect Using Core HTTP Module

If you create the server using the Node.js HTTP module from scratch, you will not have access to the res.redirect() method. Because this method is provided by the Express framework.

But the Node.js server has two methods that you can use to redirect from one page to another. I will show you how to use both methods with examples.

Method 1: Using the setHeader() Method

The setHeader() method as the name suggests is used to set headers for the response. This method also can redirect to a new URL.

          const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.statusCode = 200;
        res.write('<html><body><h1>Home Page</h1></body></html>');
        return res.end();
    } else if (req.url === '/login') {
        // Validate username and password

        res.statusCode = 302;
        res.setHeader('location', '/dashboard');
        return res.end();
    } else if (req.url === '/dashboard') {
        // Validate if user is already logged in

        res.statusCode = 200;
        res.write('<html><body><h1>Dashboard</h1></body></html>');
        return res.end();
    }

    res.statusCode = 404;
    res.write('<html><body><h1>404 - Page Not Found</h1></body></html>');
    res.end();
});

server.listen(5000, () => {
    console.log('Server is running at http://localhost:5000');
});
        

In this server, I have "/login" and "/dashboard" routes. You have to create each route by checking the req.url property. I am calling the res.setHeader() method inside the "/login" block.

The res.setHeader() method accepts 2 parameters: Header name and Header value. You have to set "location" as the header name. For its value, you need to give the target URL.

Just calling the setHeader() method will not work. Status code is also necessary for the Node.js redirects. I am setting the 302 status code using the res.statusCode property.

Method 2: Using the writeHead() Method

The writeHead() method can redirect to an URL. You can also set both the target URL and status code with this method. You don't have to define the status code separately.

          const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.statusCode = 200;
        res.write('<html><body><h1>Home Page</h1></body></html>');
        return res.end();
    } else if (req.url === '/login') {
        // Validate username and password

        res.writeHead(302, {
            location: '/dashboard',
        });
        return res.end();
    } else if (req.url === '/dashboard') {
        // Validate if user is already logged in

        res.statusCode = 200;
        res.write('<html><body><h1>Dashboard</h1></body></html>');
        return res.end();
    }

    res.statusCode = 404;
    res.write('<html><body><h1>404 - Page Not Found</h1></body></html>');
    res.end();
});

server.listen(5000, () => {
    console.log('Server is running at http://localhost:5000');
});
        

You can call this method with the status code in the first parameter and an object in the second parameter. The object will have a "location" property with the URL.

Both methods can redirect to an external website by using an absolute URL.

          // Using setHeader() method
res.statusCode = 301;
res.setHeader('location', 'https://www.example.com');

// Using writeHead() method
res.writeHead(301, {
    location: 'https://www.example.com',
});
        

I am redirecting to a different domain with a 301 status code. You can use any other status codes if necessary. Now, it's up to you which method you want to apply in your application.

Different Status Codes For Redirect

HTTP status codes are numbers that describe the response. When a server returns a response, it also comes with a status code. The browsers or any other clients understand the response by watching the code.

We use 3xx status codes for any type of redirect. This is the list of status codes that you can use:

Status CodeMeaningDescription
300Multiple ChoicesThere are multiple responses to the request. The user should choose one of them.
301Moved PermanentlyThe target content has been moved to a new URL permanently.
302FoundA new URL is given for the requested URL temporarily.
303See OtherThis response is sent by the server to direct a client to get the content from another URL using a GET request.
304Not ModifiedIt tells the clients that the response has not been modified so that they can use the cached version.
307Temporary RedirectDirect the client to get the resources from another URL but using the same method as the previous one.
308Permanent RedirectThe resource URL has been moved to a new URL permanently. The clients have to use the same method.

These are the available status codes for redirections. You need to choose and use one based on the response type.

Also Read: How to Set and Get Cookies in Node.js Express Server

Conclusion

You can use both the Node.js native module and Express framework to redirect a user from one page to another. They have different methods to get the job done.

The Express framework also uses native methods to perform redirections. It doesn't matter whatever framework you use for your project, now you know how redirection works in a Node.js server.

I hope you have understood today's topic and you will be able to redirect to an URL in Node.js using the Express and HTTP module.

Related Posts