Sobes.tech
Middle

Tell me more about Axios interceptors — why did you need them?

sobes.tech AI

Answer from AI

Axios interceptors are functions that allow you to intercept requests or responses before they are handled in your code. They are useful for centralized management of logic related to HTTP requests.

For example, interceptors can be used to:

  • Automatically add authorization tokens to all outgoing requests.
  • Log or modify requests and responses.
  • Handle errors globally, such as automatically refreshing a token upon receiving a 401 Unauthorized.

Example of using an interceptor to add a token:

axios.interceptors.request.use(config => {
  const token = localStorage.getItem('authToken');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});
Tell me more about Axios interceptors — why did you… - sobes.tech