Follow Redirects

1.16.0 · active · verified Tue Apr 21

follow-redirects is a Node.js utility that provides a drop-in replacement for the native `http` and `https` modules, automatically handling HTTP and HTTPS redirects transparently. Currently stable at version 1.16.0, the package sees regular maintenance with patch and minor releases, indicating active development and bug fixes. Its core functionality enables developers to make network requests without manually inspecting and reissuing requests for 3xx status codes, simplifying client-side HTTP interactions significantly. Unlike the built-in Node.js modules, `follow-redirects` abstracts away the complexity of redirect chains, offering a more robust and developer-friendly experience for fetching resources across multiple redirects. It provides configurable limits for maximum redirects and response body length, which can be set both globally for all requests or individually for specific requests.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic GET and POST requests using `follow-redirects`, showing how to retrieve the final URL after redirects and how to configure both global and per-request options for maximum redirects and body length.

const { http, https } = require('follow-redirects');
const url = require('url');

// Example 1: Simple GET request with redirect following
// Using a reliable test service for redirects
http.get('http://httpbin.org/redirect/3', response => {
  console.log(`GET Status Code: ${response.statusCode}`);
  console.log(`GET Final URL: ${response.responseUrl}`);
  let data = '';
  response.on('data', chunk => {
    data += chunk;
  });
  response.on('end', () => {
    console.log('GET Response body length:', data.length);
  });
}).on('error', err => {
  console.error('GET Error:', err.message);
});

// Example 2: POST request demonstrating global and per-request options
// Setting global max redirects (default is 21)
followRedirects.maxRedirects = 5; 
// Setting global max body length (default is 10MB)
followRedirects.maxBodyLength = 1 * 1024 * 1024; // 1 MB

const postOptions = url.parse('https://postman-echo.com/post');
postOptions.method = 'POST';
postOptions.headers = {
  'Content-Type': 'application/json',
  'User-Agent': 'follow-redirects-example/1.0'
};
// Override global maxRedirects for this specific POST request
postOptions.maxRedirects = 2;

const postData = JSON.stringify({ message: 'Hello from follow-redirects!', source: 'quickstart' });

const postReq = https.request(postOptions, response => {
  console.log(`POST Status Code: ${response.statusCode}`);
  console.log(`POST Final URL: ${response.responseUrl}`);
  let data = '';
  response.on('data', chunk => {
    data += chunk;
  });
  response.on('end', () => {
    console.log('POST Response body:', JSON.parse(data));
  });
}).on('error', err => {
  console.error('POST Error:', err.message);
});

postReq.write(postData);
postReq.end();

view raw JSON →