Frontend axios middleware

vimal_adithan

Vimal

Posted on June 4, 2024

Frontend axios middleware

import axios from 'axios'
import jwt_decode from "jwt-decode";
import dayjs from 'dayjs'
import { useContext } from 'react'
import AuthContext from '../context/AuthContext'

const baseURL = 'http://127.0.0.1:8000'

const useAxios = () => {
const {authTokens, setUser, setAuthTokens} = useContext(AuthContext)

const axiosInstance = axios.create({
    baseURL,
    headers:{Authorization: `Bearer ${authTokens?.access}`}
});


axiosInstance.interceptors.request.use(async req => {

    const user = jwt_decode(authTokens.access)
    const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1;

    if(!isExpired) return req

    const response = await axios.post(`${baseURL}/api/token/refresh/`, {
        refresh: authTokens.refresh
      });

    localStorage.setItem('authTokens', JSON.stringify(response.data))

    setAuthTokens(response.data)
    setUser(jwt_decode(response.data.access))

    req.headers.Authorization = `Bearer ${response.data.access}`
    return req
})

return axiosInstance
Enter fullscreen mode Exit fullscreen mode

}

export default useAxios;

💖 💪 🙅 🚩
vimal_adithan
Vimal

Posted on June 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Frontend axios middleware
interceptor Frontend axios middleware

June 4, 2024