How to process the request in the React js after the access token gets expire

Viewed 20

Let us suppose that I have 2 tokens in the react website

  1. access token ( life span = 5min)
  2. refresh token (life span = 1 day)

Now to us assume that the user send the request to the backend API but during that time period his access token got expired now how I can handle that request after getting the new access token from the refresh token?

I am using Django rest framework next js

code of axioxinstance

import axios from "axios";
import Cookies from "js-cookie";
import jwt_decode from "jwt-decode";
import dayjs from "dayjs";
export const baseURL = "http://127.0.0.1:8000/";
const axiosInstance = axios.create({
    baseURL,
    headers: { "Content-Type": "application/json" },
});

axiosInstance.interceptors.request.use(
    function (config) {
        let tokens = Cookies.get("token");
        if (tokens) {
            tokens = JSON.parse(tokens);
            const tokenExpt = jwt_decode(tokens.access);
            const isExpired = dayjs.unix(tokenExpt.exp).diff(dayjs()) < 1;
            if (isExpired) {
                axios
                    .post(`${baseURL}api/token/refresh/`, {
                        refresh: tokens.refresh,
                    })
                    .then((response) => {
                        Cookies.set("token", JSON.stringify(response.data));
                        config.headers.Authorization = `Bearer ${response.data.access}`;
                        // console.log("object");
                        return config;
                    });

                return config;
            } else {
                config.headers.Authorization = `Bearer ${tokens.access}`;
                return config;
            }
        } else {
            return config;
        }
    },
    function (error) {
        return Promise.reject(error);
    }
);

export default axiosInstance;
0 Answers
Related