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 …


This content originally appeared on DEV Community and was authored by Sandesh Rauth

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;

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);
});

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!


This content originally appeared on DEV Community and was authored by Sandesh Rauth


Print Share Comment Cite Upload Translate Updates
APA

Sandesh Rauth | Sciencx (2023-03-19T20:18:39+00:00) Creating Axios Interceptor in React and NextJs. Retrieved from https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/

MLA
" » Creating Axios Interceptor in React and NextJs." Sandesh Rauth | Sciencx - Sunday March 19, 2023, https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/
HARVARD
Sandesh Rauth | Sciencx Sunday March 19, 2023 » Creating Axios Interceptor in React and NextJs., viewed ,<https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/>
VANCOUVER
Sandesh Rauth | Sciencx - » Creating Axios Interceptor in React and NextJs. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/
CHICAGO
" » Creating Axios Interceptor in React and NextJs." Sandesh Rauth | Sciencx - Accessed . https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/
IEEE
" » Creating Axios Interceptor in React and NextJs." Sandesh Rauth | Sciencx [Online]. Available: https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/. [Accessed: ]
rf:citation
» Creating Axios Interceptor in React and NextJs | Sandesh Rauth | Sciencx | https://www.scien.cx/2023/03/19/creating-axios-interceptor-in-react-and-nextjs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.