Node.js: how to create HTTP redirects

Node.js: how to create HTTP redirects

In Node.js, HTTP redirects can be implemented using the core modules http and https.

HTTP redirects are a way for web servers to inform a client that the requested resource has been moved to a new location. Redirects are performed by sending a response with a status code indicating that the requested resource has been moved, along with a Location header specifying the new location. In Node.js, HTTP redirects can be implemented using the core modules http and https.

There are several types of HTTP redirects, each with a different status code and meaning. The most common types of redirects are 301 (Moved Permanently), 302 (Found) and 307 (Temporary Redirect). In Node.js, you can use the statusCode property of the response object to specify the status code of the redirect.

Here is an example of how to implement a 301 redirect in Node.js using the http module:


'use strict';

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 301;
  res.setHeader('Location', 'http://www.example.com');
  res.end();
});
server.listen(3000);

In this example, when a client makes the request, it will receive a 301 redirect response with an HTTP Location header set to http://www.example.com. This will cause the client to automatically request the new location.

If you want to perform a temporary redirect, you can use the 307 status code instead:


'use strict';

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 307;
  res.setHeader('Location', 'http://www.example.com');
  res.end();
});
server.listen(3000);

HTTP redirects are often used to improve the user experience by redirecting users to the correct URLs. For example, you can use redirects to redirect users from old abandoned URLs to new ones, or to redirect them from pages without HTTPS to pages with HTTPS.