How to Handle HTTP Error Using Interceptor in Axios

August 21, 2021

Interceptor in axios can be attached to a request or a response. And they’re executed before or after every request and response globally.

One of the most common use case is handling Unauthorized request.

Let’s see how to handle those errors globally.

Handling error message in Axios using Interceptor

In our example, we’re going to listen for 401/403 HTTP Code in response and redirect them to login page.


npm i axios


const axios = require('axios');
// import axios from "axios";

  res => res,
  err => {
    // Any HTTP Code which is not 2xx will be considered as error
    const statusCode = err.response.status;
    if (statusCode === 401 || statusCode === 403) {
      window.location = '/login';

    throw err;


👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP