Avoiding Redirects In Axios

Jun 26, 2025

I had a failing test when Axios made a request to one of my API endpoints. The test reported a failure to connect to the server. That was weird because I was sure the server was up and running. It turned out the endpoint I was testing implemented an HTTP redirect to an unavailable location. Axios was following the redirect and trying to connect to that location, which is why I was seeing a failure to connect to the server.

To avoid that, we can configure Axios not to follow redirects

test('should redirect to correct location', async () => {
  const response = await axios.get('http://example.com', {
    maxRedirects: 0,
    validateStatus: null
  });

  expect(response.status).toBeGreaterThanOrEqual(300);
  expect(response.status).toBeLessThan(400);
  expect(response.headers['location']).toBe('https://expected.com/target');
});

#javascript #axios