Skip to content

Commit

Permalink
fix(core): prevent multiple refresh token requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Xairoo committed Sep 20, 2022
1 parent 2acbccb commit ad8bfd7
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/next-static-site-auth/src/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,15 @@ export function useRefreshHelper() {
}, [hasWindow]);
}

// Prevent multiple refresh token requests
let isRefreshing = false;

/**
* Get the current session
*
* @returns {object} Auth `status`, (user) `data`, JWT `token`
*/
export function useSession(options?: object): {
export function useSession(): {
status: undefined | undefined | string;
data: any;
token: undefined | null | undefined | null | string;
Expand Down Expand Up @@ -107,13 +110,15 @@ export function useSession(options?: object): {
// Refresh expired token?
else if (authToken.isExpired) {
const fetchData = async () => {
console.log("fetchData");
try {
// Token is expired, request a new one
const res = await fetch(NEXT_PUBLIC_AUTH_API_REFRESH, {
headers: {
"Content-Type": "application/json",
},
credentials: "include",
mode: "cors",
method: "GET",
});

Expand Down Expand Up @@ -170,9 +175,14 @@ export function useSession(options?: object): {
token: null,
});
}
isRefreshing = false;
};

// Request a new token
if (isRefreshing) {
return;
}
isRefreshing = true;

fetchData();
}
}
Expand Down Expand Up @@ -349,6 +359,7 @@ export function useLogout() {
try {
await fetch(NEXT_PUBLIC_AUTH_API_LOGOUT, {
credentials: "include",
mode: "cors",
});
} catch (err: any) {
// Request failed
Expand Down

0 comments on commit ad8bfd7

Please sign in to comment.