Navigation

Node.js

How to Follow Redirects in HTTP Requests

Handle HTTP redirects automatically in Node.js with fetch() and manual redirect control. Simple solution for 301, 302, and other redirect status codes.

Table Of Contents

Problem

Your HTTP requests hit redirect responses (301, 302, etc.) and you need to follow them automatically or handle redirects manually with custom logic.

Solution

// Automatic redirect following (default behavior)
async function fetchWithAutoRedirect(url) {
  const response = await fetch(url, {
    redirect: 'follow' // Default: automatically follow redirects
  });
  
  console.log('Final URL:', response.url);
  console.log('Was redirected:', response.redirected);
  
  return await response.json();
}

// Manual redirect handling
async function fetchWithManualRedirect(url) {
  const response = await fetch(url, {
    redirect: 'manual' // Don't follow redirects automatically
  });
  
  if (response.status >= 300 && response.status < 400) {
    const redirectUrl = response.headers.get('Location');
    console.log(`Redirect detected: ${response.status} -> ${redirectUrl}`);
    
    // Follow redirect manually
    return await fetch(redirectUrl);
  }
  
  return response;
}

// Limited redirect following
async function fetchWithLimitedRedirects(url, maxRedirects = 5) {
  let currentUrl = url;
  let redirectCount = 0;
  
  while (redirectCount < maxRedirects) {
    const response = await fetch(currentUrl, {
      redirect: 'manual'
    });
    
    if (response.status >= 300 && response.status < 400) {
      currentUrl = response.headers.get('Location');
      redirectCount++;
      console.log(`Redirect ${redirectCount}: ${currentUrl}`);
    } else {
      return response;
    }
  }
  
  throw new Error(`Too many redirects (${maxRedirects})`);
}

Explanation

fetch() follows redirects automatically by default with redirect: 'follow'. Use redirect: 'manual' to handle redirects yourself by checking the Location header.

The response.redirected property tells you if redirects occurred, and response.url shows the final URL after redirects. Manual handling is useful for logging redirect chains or implementing custom redirect limits.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Node.js