DEV Community

Cover image for Creating Axios Interceptor in React and NextJs
Sandesh Rauth
Sandesh Rauth

Posted on

Creating Axios Interceptor in React and NextJs

Hello and welcome to this article on creating an Axios interceptor in React and Next.js. In this article, we'll cover how to set up and use Axios, as well as how to create an interceptor that can automatically refresh tokens.

Step 1: Initializing the Project
First, we need to initialize the project with the following command: yarn create react-app <app-name> or npx create-react-app <app-name>. This command will create a new React app with the name of your choice.

Step 2: Creating the Axios Configuration File
Now that we have a new React app, we can create the directory service and create a file named axiosConfig.ts inside it. Here's the code you need to put in that file:

import axios from 'axios';
import { getToken, setToken } from '../../../utils/localStorage';
import { redirect } from "react-router-dom";
import { getRefreshToken } from '../login';

const statusCode = [401,402,403]
const HttpAuthInstance = axios.create({
    baseURL: process.env.REACT_APP_BASE_URL,
    headers: {
        "Authorization": "Bearer" + " " + getToken("token").accessToken
    }
})

HttpAuthInstance.interceptors.response.use((response) => {
    return response;
}, (error) => {
    if (statusCode.indexOf(error?.response?.status) !== -1) {
        getRefreshToken(getToken("token")?.refreshToken).then(res=>setToken("token",res?.data))
    }
})

export default HttpAuthInstance;
Enter fullscreen mode Exit fullscreen mode

This code sets up an Axios instance that includes a base URL and headers with an authorization token. It also sets up an interceptor that checks for certain error status codes and refreshes the token if necessary.

Step 3: Using the Axios Configuration File
To use this Axios instance in your application, simply import it into the file where you need to make API calls. Here's an example of how to do that:

import HttpAuthInstance from './service/axiosConfig';

HttpAuthInstance.get('/api/users').then(response => {
    console.log(response.data);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we're making a GET request to the /api/users endpoint and logging the response data to the console.

That's it! With this Axios interceptor, your application will automatically refresh tokens when necessary, making it more secure and efficient. I hope you found this article helpful and informative. Happy coding!

Top comments (0)