ReactJS – Axios Interceptors

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to learn how to intercept every request or response that is being sent by Axios Interceptors in a React application.

Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.


In this example, we will build a React application that automatically checks and logs the status code that is sent by the server while sending a POST request from our React application.

We have to set all the configuration in the most global file, i.e. index.js, to intercept every request/response.


import React from 'react';
import App from './App';
import ReactDOM from 'react-dom';
import axios from 'axios';

// For GET requests
   (req) => {
      // Add configurations here
      return req;
   (err) => {
      return Promise.reject(err);

// For POST requests
   (res) => {
      // Add configurations here
      if (res.status === 201) {
         console.log('Posted Successfully');
      return res;
   (err) => {
      return Promise.reject(err);

      <App />


import React, { useEffect, useState } from 'react';
import './App.css';
const App = () => {
   const [data, setData] = useState(null);
   const [val, setVal] = useState('');
   const [fetchData, setFetch] = useState(false);

   useEffect(() => {

      if (fetchData) {
         const payload = {
            method: 'POST',
            body: JSON.stringify({ title: val }),
         };'', payload)
.then((res) => setData(;
   }, [fetchData]);
   return (
      {data && <h1>Your data is saved with Id: {data}</h1>}
         placeholder="Title of Post"
         onChange={(e) => setVal(}
      <button onClick={() => setFetch(true)}>Save Data</button>
export default App;

In the above example, when the request is sent with the data, the response is intercepted and if the status code is 201, then it will log the message 'Posted Successfully'.


This will produce the following result.

Published on 18-Mar-2021 11:28:41