Integrating Axios in a React Project

Axios is a popular JavaScript library used for making HTTP requests from web browsers and Node.js applications. It provides a simple and intuitive API to facilitate communication with RESTful APIs. In this post, I will cover how to integrate Axios in a React project.

The client side

Create the React App

npm create vite@latest . -- --template react-ts
npm install
npm install axios
npm install js-cookie @types/js-cookie

Setting environment variables for API calls

.env

VITE_API_BASE_URL=http://localhost:3000/  
VITE_TOKEN_KEY=authToken

Create an Axios instance

src/utils/axios.ts

import axios from "axios";  

const baseURL = import.meta.env.VITE_API_BASE_URL;
const tokenKey = import.meta.env.VITE_TOKEN_KEY;

console.log('baseURL:', baseURL);

const instance = axios.create({
baseURL: baseURL,
timeout: 3000,
headers: {
'Content-Type': 'application/json',
}
});

export default instance;

Add a request interceptor

Add content to axios.ts

import Cookies from 'js-cookie';

instance.interceptors.request.use(function (config) {
if (config.url === '/login') {
return config;
}
// Do something before request is sent
config.headers["Authorization"] = 'Bearer ' + Cookies.get(tokenKey);
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

Add a response interceptor

Add content to axios.ts

instance.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data...
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
console.log('error:', error);
if (error.response.status === 401) {
Cookies.remove(tokenKey);
// redirect to login page
window.location.href = '/login';
return Promise.reject(error);
} else {
alert(error.response.data.message)
}
});

The complete example of axios.ts

src/utils/axios.ts

import axios from "axios";  
import Cookies from 'js-cookie';

const baseURL = import.meta.env.VITE_API_BASE_URL;
const tokenKey = import.meta.env.VITE_TOKEN_KEY;

console.log('baseURL:', baseURL);

const instance = axios.create({
baseURL: baseURL,
timeout: 3000,
headers: {
'Content-Type': 'application/json',
}
});

instance.interceptors.request.use(function (config) {
if (config.url === '/login') {
return config;
}
// Do something before request is sent
config.headers["Authorization"] = 'Bearer ' + Cookies.get(tokenKey);
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

instance.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data... return response;
}, function (error) {
// Any status codes that fall outside the range of 2xx cause this function to trigger
// Do something with response error console.log('error:', error);
if (error.response.status === 401) {
Cookies.remove(tokenKey);
// redirect to login page
window.location.href = '/login';
return Promise.reject(error);
} else {
alert(error.response.data.message)
}
});

export default instance;

Write the App.tsx

src/App.tsx

import './App.css'  
import instance from "./utils/axios.ts";
import {useEffect, useState} from "react";

function App() {
const [message, setMessage] = useState()
useEffect(() => {
instance.get('/api/demo').then(response => {
console.log('response:', response.data);
setMessage(response.data.message);
});
}, []);
return (
<>
API Response: {message}
</>
)
}

export default App

The server side

Setting up the API server

1. Create a Next.js project

# create the Next.js (Would you like to use xxx: just uses the default option)
npx create-next-app next-app

2. Create an API

src/pages/api/demo.js

export default function handler(req, res) {  
res.status(200).json({ message: 'Hello, this is your custom API!' });
}

Next.js automatically recognizes the api folder as a special folder for API routes. The API is /api/demo.

3. Enable CORS

next.config.ts

const nextConfig: NextConfig = {
/* config options here */
headers: async () => {
// enable CORS
return [
{
source: '/api/(.*)',
headers: [
{key: 'Access-Control-Allow-Origin', value: '*'},
{key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT'},
{key: 'Access-Control-Allow-Headers', value: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization'},
],
},
];
}
};

4. Start API server

npm run dev

Visiting http://localhost:3000/api/demo to verify your API.

Running the React App

npm run dev

Visit http://localhost:5173/ to see API response.