mirror of
https://github.com/ershisan99/todolist_next.git
synced 2026-02-02 12:35:49 +00:00
switch to bun + biomejs
fix infinite load on failed token refresh
This commit is contained in:
@@ -9,14 +9,14 @@ import { useMeQuery } from "@/services";
|
||||
|
||||
export const AuthRedirect: FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const router = useRouter();
|
||||
const { data: user, isLoading, isError } = useMeQuery();
|
||||
const { data: user, isLoading } = useMeQuery();
|
||||
const isAuthPage = router.pathname === "/login";
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !user && !isAuthPage) {
|
||||
router.push("/login");
|
||||
}
|
||||
}, [user, isError, isLoading, isAuthPage, router]);
|
||||
}, [user, isLoading, isAuthPage, router]);
|
||||
|
||||
if (isLoading || (!user && !isAuthPage)) {
|
||||
return (
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Mutex } from "async-mutex";
|
||||
import axios from "axios";
|
||||
import router from "next/router";
|
||||
|
||||
const mutex = new Mutex();
|
||||
|
||||
let refreshedAt: number | null = null;
|
||||
|
||||
export const todolistApiInstance = axios.create({
|
||||
baseURL: "http://localhost:3000",
|
||||
baseURL: "http://localhost:3000"
|
||||
});
|
||||
|
||||
async function refreshAccessToken(): Promise<string> {
|
||||
@@ -17,8 +19,8 @@ async function refreshAccessToken(): Promise<string> {
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${localStorage.getItem("refreshToken")}`,
|
||||
},
|
||||
Authorization: `Bearer ${localStorage.getItem("refreshToken")}`
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -46,9 +48,10 @@ todolistApiInstance.interceptors.request.use(
|
||||
todolistApiInstance.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if(error?.response?.request?.responseURL?.includes("refresh-token")){
|
||||
return }
|
||||
await mutex.waitForUnlock();
|
||||
const originalRequest = error.config;
|
||||
|
||||
// Check for a 401 response and if this request hasn't been retried yet
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
if (!mutex.isLocked()) {
|
||||
@@ -60,7 +63,7 @@ todolistApiInstance.interceptors.response.use(
|
||||
// If the token has been refreshed within the last minute, use the refreshed token
|
||||
originalRequest.headers[
|
||||
"Authorization"
|
||||
] = `Bearer ${localStorage.getItem("accessToken")}`;
|
||||
] = `Bearer ${localStorage.getItem("accessToken")}`;
|
||||
release();
|
||||
|
||||
return todolistApiInstance(originalRequest);
|
||||
@@ -72,6 +75,8 @@ todolistApiInstance.interceptors.response.use(
|
||||
originalRequest.headers["Authorization"] = `Bearer ${newAccessToken}`;
|
||||
|
||||
return todolistApiInstance(originalRequest); // Retry the original request with the new token
|
||||
} catch (error) {
|
||||
router.push("/login");
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user