Skip to content

Commit 010277e

Browse files
committed
axios instance setup for logout and new access token
1 parent 18effbc commit 010277e

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import axios from "axios";
2+
3+
const axiosInstance = axios.create({
4+
baseURL: process.env.NEXT_PUBLIC_SERVER_URI,
5+
withCredentials: true,
6+
});
7+
8+
let isRefreshing = false;
9+
let refreshSubscribers: (() => void)[] = [];
10+
11+
//Handle logout and prevent infinite loops
12+
13+
const handleLogout = () => {
14+
if (window.location.pathname !== "/login") {
15+
window.location.href = "/login";
16+
}
17+
};
18+
19+
//handle adding a new access token to queued requests
20+
21+
const subscribeTokenRefresh = (callback: () => void) => {
22+
refreshSubscribers.push(callback);
23+
};
24+
25+
//execute queued request after refresh
26+
const onRefreshSuccess = () => {
27+
refreshSubscribers.forEach((callback) => callback());
28+
refreshSubscribers = [];
29+
};
30+
31+
//Handle Api requests
32+
axiosInstance.interceptors.request.use(
33+
(config) => config,
34+
(error) => Promise.reject(error)
35+
);
36+
37+
// Handle expired Tokens and refresah logic
38+
axiosInstance.interceptors.response.use(
39+
(response) => response,
40+
async (error) => {
41+
const originalRequest = error.config;
42+
43+
//prevent infinite loop
44+
if (error.response?.status === 401 && !originalRequest._retry) {
45+
if (isRefreshing) {
46+
return new Promise((resolve) => {
47+
subscribeTokenRefresh(() => resolve(axiosInstance(originalRequest)));
48+
});
49+
}
50+
51+
originalRequest._retry = true;
52+
isRefreshing = true;
53+
try {
54+
await axios.post(
55+
`${process.env.NEXT_PUBLIC_SERVER_URI}/auth/api/refresh-token-user`,
56+
{},
57+
{ withCredentials: true }
58+
);
59+
60+
isRefreshing = false;
61+
onRefreshSuccess();
62+
63+
return axiosInstance(originalRequest);
64+
} catch (error) {
65+
isRefreshing = false;
66+
refreshSubscribers = [];
67+
handleLogout();
68+
return Promise.reject(error);
69+
}
70+
}
71+
return Promise.reject(error);
72+
}
73+
);

0 commit comments

Comments
 (0)