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.

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
How to Redirect Express Routes With Query Params
Many routes contain additional query strings or parameters. While redirecting to another route, you can pass those query strings and parameters.
For example, I have a old-url
route in my Express app that takes 2 query strings: page
and skip
. I want to attach these query strings while redirecting to my new-url
route.
router.get('/old-url', (req, res) => {
const { page, skip } = req.query
res.redirect(301, `/new-url?page=${page}&skip=${skip}`)
})
router.get('/new-url', (req, res) => {
console.log(req.query)
// { page: '3', skip: '20' }
res.status(200).send('<h1>New URL</h1>')
})
Here I am extracting the query strings from req.query
object. Then you have to create a string using template literals with those queries for the res.redirect()
method.
In this way, you can attach your queries to the redirect URL. But if you don't want to do it manually, there is another easy way.
const querystring = require('querystring')
router.get('/old-url', (req, res) => {
const query = querystring.stringify(req.query)
// page=3&skip=20
res.redirect(301, `/new-url?${query}`)
})
router.get('/new-url', (req, res) => {
console.log(req.query)
// { page: '3', skip: '20' }
res.status(200).send('<h1>New URL</h1>')
})
You can generate a URL query string from the req.query
object. Then you just have to add that string to your redirected path.
As you can see, you don't have to access each query string from the req.query
object manually. If your route accepts multiple queries, you can follow this process.
Redirect Express Routes With URL Parameters
If your route has URL parameters, you can also use them with res.redirect()
method. Get the URL parameters from the req.params
object and add them to the redirected path.
router.get('/old-url/:id', (req, res) => {
const { id } = req.params
res.redirect(301, `/new-url/${id}`)
})
router.get('/new-url/:id', (req, res) => {
const { id } = req.params
res.status(200).send(`<h1>New URL: ${id}</h1>`)
})
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 Code | Meaning | Description |
300 | Multiple Choices | There are multiple responses to the request. The user should choose one of them. |
301 | Moved Permanently | The target content has been moved to a new URL permanently. |
302 | Found | A new URL is given for the requested URL temporarily. |
303 | See Other | This response is sent by the server to direct a client to get the content from another URL using a GET request. |
304 | Not Modified | It tells the clients that the response has not been modified so that they can use the cached version. |
307 | Temporary Redirect | Direct the client to get the resources from another URL but using the same method as the previous one. |
308 | Permanent Redirect | The 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 what 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.