Search code examples
axiosinterceptor

What is the difference between axios interceptor and default header?


I'm curious about the difference between axios interceptor and default header.

I want to add authorization in header.

I know I can manage authorization header with axios interceptor and default header. (Attach Authorization header for all axios requests)

I'm not sure when to use the interceptor and default header respectively.

Is it simply that axios provides two methods?


Solution

  • Default headers are assigned statically. The values you place into them must be known at the time your code executes.

    axiosOrInstance.defaults.headers.common["x-value"] = "some value you must know";
    

    Interceptors are functions that execute per request / response. This means they can access values that might not have been available earlier or even values specific to the current request.

    axiosOrInstance.interceptors.request.use(config => ({
      ...config,
      headers: {
        ...config.headers,
        "x-value": "whatever"
      }
    }), null, {
      synchronous: true,
      runWhen: config => config.url === "only/run/for/this/url"
    })
    

    They can also be asynchronous and make other async calls before resolving

    axiosOrInstance.interceptors.request.use(async config => {
      const someValue = await getSomeAsyncValue()
      return {
        ...config,
        headers: {
          ...config.headers,
          "x-value": someValue
        }
      };
    });