How to Debug Axios Interceptors in React

Debugging Axios interceptors in React can be challenging because they operate silently behind the scenes of your HTTP requests and responses. This article provides a practical guide on how to inspect, log, and troubleshoot both request and response interceptors using browser developer tools, strategic console logging, and breakpoints to ensure your global API configurations function correctly.

Use Console Logging for Quick Visibility

The quickest way to debug interceptors is by adding explicit console.log and console.error statements inside your interceptor functions. This allows you to inspect the outgoing request configuration and the incoming response data in real-time.

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
});

// Debugging Request Interceptor
api.interceptors.request.use(
  (config) => {
    console.log('AXIOS REQUEST:', {
      url: config.url,
      method: config.method,
      headers: config.headers,
      data: config.data,
    });
    return config;
  },
  (error) => {
    console.error('AXIOS REQUEST ERROR:', error);
    return Promise.reject(error);
  }
);

// Debugging Response Interceptor
api.interceptors.response.use(
  (response) => {
    console.log('AXIOS RESPONSE:', {
      status: response.status,
      data: response.data,
    });
    return response;
  },
  (error) => {
    console.error('AXIOS RESPONSE ERROR:', {
      message: error.message,
      response: error.response,
    });
    return Promise.reject(error);
  }
);

export default api;

Utilize Browser Developer Tools and Breakpoints

For a deeper inspection, rely on your browser’s Developer Tools (F12) rather than just logs.

  1. Insert the debugger Statement: Place a debugger; statement directly inside the interceptor function where you want to pause execution.
  2. Inspect the Scope: When the browser pauses execution, open the Sources tab. You can hover over variables (like config or response) to inspect their current state, headers, and payload.
  3. Step Through Execution: Use the “Step over” and “Step into” buttons to watch how your React application handles the promise chain after the interceptor runs.

Analyze the Network Tab

The Network tab in your browser’s developer tools is crucial for verifying if your request interceptor actually modified the request.

Common Interceptor Pitfalls to Check

If your interceptor is not behaving as expected, verify these common configuration mistakes: