axios or fetch? Interceptors, cancelling and token refresh

With Node 18, fetch is finally global on the server as well as in every browser. (Node still prints an 'experimental' warning the first time you use it.

With Node 18, fetch is finally global on the server as well as in every browser. (Node still prints an “experimental” warning the first time you use it.) So it’s a fair question: why keep axios at all?

The honest answer is that for simple apps, you don’t need it. But axios still does a few things that are tedious to rebuild, and one of them, refreshing an expired token for many requests at once, is easy to get subtly wrong.

The differences that matter

fetch axios
HTTP 404 or 500 resolves, res.ok is false rejects with an AxiosError
JSON call res.json() yourself parsed into res.data
Timeout signal: AbortSignal.timeout(ms) timeout: ms option
Interceptors write your own wrapper built in
Upload progress not available onUploadProgress in browsers

The first row is the one that bites. This is a common bug with fetch:

try {
  const res = await fetch('/api/items/42');
  const item = await res.json(); // runs for a 404 too
} catch {
  // only network errors land here
}

A 404 is a successful request, so fetch resolves. With axios the same call rejects, and the error carries the response:

try {
  const { data } = await axios.get('/api/items/42');
} catch (error) {
  error.code;            // 'ERR_BAD_REQUEST'
  error.response.status; // 404
  error.response.data;   // the server's error body
}

If that’s all you need, a ten-line wrapper around fetch is enough:

export async function getJson(url, options) {
  const res = await fetch(url, options);
  if (!res.ok) {
    const error = new Error(`HTTP ${res.status}`);
    error.status = res.status;
    error.body = await res.json().catch(() => null);
    throw error;
  }
  return res.json();
}

Where axios earns its place is interceptors: code that runs on every request and every response, in one place.

Cancelling: use AbortController

Older axios code uses CancelToken. It has been deprecated since 0.22. Use the same AbortController you’d use with fetch:

useEffect(() => {
  const controller = new AbortController();

  axios
    .get(`/api/search?q=${query}`, { signal: controller.signal })
    .then((res) => setResults(res.data))
    .catch((error) => {
      if (axios.isCancel(error)) return; // we cancelled it, not an error
      setError(error);
    });

  return () => controller.abort();
}, [query]);

A cancelled request rejects with a CanceledError (code ERR_CANCELED), and axios.isCancel() tells you which kind of rejection you have. Without that check, every fast typist triggers your error message.

Refreshing a token without a stampede

The classic setup: short-lived access tokens, and a refresh endpoint that issues a new one. When a request comes back 401, refresh and retry.

The naive version works in testing and breaks in production. A page that loads makes five requests at once. All five get a 401, all five call the refresh endpoint, and depending on your backend, the second refresh invalidates the first, so some retries still fail.

The fix is to share one refresh between everyone who needs it:

import axios from 'axios';

export function createApi(baseURL, auth) {
  const api = axios.create({ baseURL, timeout: 10_000 });

  api.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${auth.getAccessToken()}`;
    return config;
  });

  let refreshing = null; // one refresh at a time, shared

  api.interceptors.response.use(
    (response) => response,
    async (error) => {
      const original = error.config;
      if (error.response?.status !== 401 || original._retried) {
        throw error;
      }
      original._retried = true;

      refreshing ??= axios
        .post(`${baseURL}/auth/refresh`)
        .then((res) => auth.setAccessToken(res.data.accessToken))
        .finally(() => { refreshing = null; });

      await refreshing;
      return api(original); // the request interceptor adds the new token
    },
  );

  return api;
}

Three details do the work:

  • refreshing ??= … starts a refresh only if one isn’t already running. Every other 401 waits on the same promise. I tested it with three parallel requests and a stale token: three 401s, one refresh call, three successful retries.
  • _retried stops a loop. If the retry gets a 401 too, the refresh didn’t help, so give up instead of refreshing forever.
  • The refresh uses plain axios, not api. Otherwise the refresh request goes through the same interceptor, and a 401 from the refresh endpoint would try to refresh itself.

If the refresh fails, await refreshing throws, and every waiting request fails with it. That’s usually the moment to send the user to the login page.

Timeouts

axios has no timeout by default, and neither does fetch. A request to a server that never answers will wait as long as the connection stays open. Set one on the instance:

const api = axios.create({ baseURL, timeout: 10_000 });
// on timeout: error.code === 'ECONNABORTED'

With fetch, pass signal: AbortSignal.timeout(10_000).

So which one?

  • A few calls, no auth flow: fetch and a small wrapper. One less dependency.
  • An app with auth, retries, shared headers and error handling: axios. Interceptors keep all of that in one file instead of in every call.
  • Either way: cancel requests you no longer need, set a timeout, and handle HTTP errors explicitly. Those three cause more real bugs than the choice of library.