How to Treat HTTP 302 as Success in Axios

By default, Axios automatically follows HTTP redirects in Node.js environments and throws an error if an unhandled 3xx status code is returned. This article explains how to configure the validateStatus and maxRedirects options in Axios to intercept HTTP 302 Found responses, prevent automatic redirection, and treat the 302 status code as a successful, resolved promise.

The Required Configuration

To handle an HTTP 302 redirect as a successful response, you must configure two specific Axios request options:

  1. validateStatus: Determines which HTTP status codes should resolve the Promise instead of rejecting it.
  2. maxRedirects: Prevents the Node.js HTTP adapter from automatically following the redirect URL.

Implementation Example

const axios = require('axios');

axios.get('https://example.com/api-endpoint', {
  // Prevent Axios from automatically following the redirect (Node.js)
  maxRedirects: 0,
  
  // Define HTTP 302 as a valid, successful status code
  validateStatus: function (status) {
    return (status >= 200 && status < 300) || status === 302;
  }
})
.then(response => {
  console.log(`Status Code: ${response.status}`);
  console.log(`Redirect Location: ${response.headers.location}`);
})
.catch(error => {
  console.error('Request failed:', error.message);
});

How It Works

The validateStatus Function

By default, Axios uses the following check to determine success:

validateStatus: function (status) {
  return status >= 200 && status < 300;
}

Any status code outside the 200–299 range triggers a rejection, causing Axios to enter the .catch() block. By modifying this function to return true when status === 302, Axios resolves the request with a full response object containing the 302 status and response headers.

The maxRedirects Option

In Node.js, Axios automatically follows redirects up to a default limit of 5. If maxRedirects is not set to 0, Axios will automatically follow the Location header to the target URL before validateStatus can evaluate the intermediate 302 response. Setting maxRedirects: 0 forces Axios to stop at the initial 302 response.

Note: In browser environments, redirect handling is managed directly by the browser's Fetch/XHR APIs and cannot be manually halted using maxRedirects.

Creating a Reusable Instance

To apply this behavior across multiple requests, define the configuration inside a custom Axios instance:

const apiClient = axios.create({
  baseURL: 'https://example.com',
  maxRedirects: 0,
  validateStatus: (status) => (status >= 200 && status < 300) || status === 302
});

// All requests made with apiClient will treat 302 as success
apiClient.get('/path')
  .then(response => {
    // Handle response
  });