0
0
ReactHow-ToBeginner · 4 min read

How to Use Interceptors with Axios in React: Simple Guide

In React, you use axios.interceptors.request.use and axios.interceptors.response.use to add interceptors that run before requests or after responses. These interceptors let you modify requests, add headers, or handle errors globally in your app.
📐

Syntax

Axios interceptors have two main types: request and response. You add them using axios.interceptors.request.use(onSuccess, onError) and axios.interceptors.response.use(onSuccess, onError). Each takes two functions: one for success and one for error handling.

The success function receives the request or response object and must return it or a modified version. The error function handles any errors and can return a rejected promise.

javascript
axios.interceptors.request.use(
  function (config) {
    // Modify request config before sending
    return config;
  },
  function (error) {
    // Handle request error
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  function (response) {
    // Process response data
    return response;
  },
  function (error) {
    // Handle response error
    return Promise.reject(error);
  }
);
💻

Example

This example shows how to add interceptors in a React component to add an authorization header to every request and log errors globally.

javascript
import React, { useEffect } from 'react';
import axios from 'axios';

function App() {
  useEffect(() => {
    // Add request interceptor
    const requestInterceptor = axios.interceptors.request.use(
      config => {
        config.headers.Authorization = 'Bearer my-token';
        return config;
      },
      error => {
        console.error('Request error:', error);
        return Promise.reject(error);
      }
    );

    // Add response interceptor
    const responseInterceptor = axios.interceptors.response.use(
      response => response,
      error => {
        console.error('Response error:', error.response?.status);
        return Promise.reject(error);
      }
    );

    // Cleanup interceptors on unmount
    return () => {
      axios.interceptors.request.eject(requestInterceptor);
      axios.interceptors.response.eject(responseInterceptor);
    };
  }, []);

  const fetchData = async () => {
    try {
      const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
      alert('Title: ' + res.data.title);
    } catch (error) {
      alert('Error fetching data');
    }
  };

  return (
    <div>
      <h1>Axios Interceptors Example</h1>
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
}

export default App;
Output
When clicking 'Fetch Data', an alert shows the post title fetched with the Authorization header added automatically. Errors log to console.
⚠️

Common Pitfalls

  • Not ejecting interceptors on component unmount can cause memory leaks and duplicate interceptors.
  • Forgetting to return the config or response in success handlers breaks the request/response chain.
  • Adding interceptors inside render or outside useEffect can cause multiple interceptors to stack up.
  • Not handling errors properly in interceptors can cause unhandled promise rejections.
javascript
/* Wrong: Adding interceptor inside render causes duplicates */
function Wrong() {
  axios.interceptors.request.use(config => config);
  return <div>Wrong</div>;
}

/* Right: Add interceptor once inside useEffect and eject on cleanup */
function Right() {
  React.useEffect(() => {
    const id = axios.interceptors.request.use(config => config);
    return () => axios.interceptors.request.eject(id);
  }, []);
  return <div>Right</div>;
}
📊

Quick Reference

Remember these tips when using axios interceptors in React:

  • Use useEffect to add interceptors once on mount.
  • Always eject interceptors on unmount to avoid duplicates.
  • Return the config or response in success handlers.
  • Handle errors by returning Promise.reject(error).
  • Use interceptors to add headers, log, or handle errors globally.

Key Takeaways

Add axios interceptors inside React's useEffect to run them once on mount.
Always eject interceptors on component unmount to prevent memory leaks.
Return the request config or response in interceptor success handlers to keep the chain working.
Use interceptors to add headers or handle errors globally in your React app.
Avoid adding interceptors inside render or outside useEffect to prevent duplicates.