Follow Redirects
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
-
Error: Too many redirects. Max of 21 reached.
cause The HTTP/HTTPS request encountered more redirects than the configured `maxRedirects` limit.fixInspect the URL chain for infinite redirects or increase the `maxRedirects` option if a higher number of legitimate redirects is expected (e.g., `options.maxRedirects = 30;`). -
Error: Request body exceeded maxBodyLength limit.
cause The size of the data being sent in the request body exceeded the configured `maxBodyLength` limit.fixReduce the size of the request body, or increase the `maxBodyLength` option if larger payloads are necessary (e.g., `options.maxBodyLength = 50 * 1024 * 1024;` for 50MB). -
ReferenceError: require is not defined
cause Attempting to use `require()` syntax in an ES Module (ESM) context.fixEnsure your project is configured for CommonJS, or use dynamic `import()` if you absolutely need to load `follow-redirects` in an ESM context, though its primary API is CommonJS-oriented.
Warnings
- gotcha Exceeding the `maxRedirects` limit (default: 21) will cause an error to be emitted instead of returning a response. Ensure your requests do not enter infinite redirect loops or exceed this count for valid reasons, and handle the error.
- gotcha Sending a request body larger than `maxBodyLength` (default: 10MB) will result in an error. This prevents potential denial-of-service attacks or accidental oversized uploads.
- gotcha Global options (`followRedirects.maxRedirects`, `followRedirects.maxBodyLength`) affect all subsequent requests made via `follow-redirects` unless explicitly overridden by per-request options. This can lead to unexpected behavior if not managed carefully in a shared environment.
- gotcha The `responseUrl` property on the `response` object provides the final URL after all redirects have been followed. The original request URL is not directly available on the final response object; if needed, it must be stored prior to the request.
Install
-
npm install follow-redirects -
yarn add follow-redirects -
pnpm add follow-redirects
Imports
- { http, https }
import { http, https } from 'follow-redirects';const { http, https } = require('follow-redirects'); - followRedirects (module object)
import followRedirects from 'follow-redirects';
const followRedirects = require('follow-redirects'); - Types (for TypeScript)
import type { HttpOptions, HttpsOptions, RedirectOptions, ClientRequest, IncomingMessage } from 'follow-redirects';
Quickstart
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();