Handling 302 Redirects with Axios in JavaScript

Processing 302 Redirects with Axios

Implementation Workflow

The workflow for handling 302 redirects involves these key stages:

1. Initial Request → 302 Response → Extract Location → Follow Redirect → Final Response

Implementation Steps

  1. Configure Axios Instance

Create an Axios instance with redirect handling disabled to manually process 302 responses:

const axiosInstance = axios.create({
  maxRedirects: 0,
  validateStatus: status => status < 400 || status === 302
});
  1. Initial Request and Redirect Detection

Send the enitial request and check for 302 status:

axiosInstance.get('https://example.com/api')
  .then(response => {
    if (response.status === 302) {
      const redirectUrl = response.headers.location;
      return handleRedirect(redirectUrl);
    }
    return processResponse(response);
  })
  .catch(handleError);
  1. Redirect Handler Functon

Implmeent the redirect processing logic:

function handleRedirect(url) {
  return axios.get(url)
    .then(processResponse)
    .catch(handleError);
}

function processResponse(response) {
  // Handle successful response data
  return response.data;
}

function handleError(error) {
  console.error('Request failed:', error);
  throw error;
}
  1. Complete Implementation

Combining all components into a unified solution:

async function fetchWithRedirects(url) {
  try {
    const response = await axiosInstance.get(url);
    
    if (response.status === 302) {
      return await axios.get(response.headers.location);
    }
    
    return response.data;
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}

Tags: axios javascript HTTP redirects web-development

Posted on Sun, 19 Jul 2026 16:13:23 +0000 by nileshn