Skip to content

Commit 4cf3e11

Browse files
committed
fix: Pass the refresh token into a separate function
1 parent 8a4da46 commit 4cf3e11

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

src/utils/auth.ts

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,25 @@ type RefreshedTokens = {
1010

1111
const refreshTokenPromiseCache: { [key: string]: Promise<RefreshedTokens> } = {};
1212

13+
const fetchNewToken = async (refreshToken: string): Promise<RefreshedTokens> => {
14+
const response = await fetch(
15+
`${process.env.NEXT_PUBLIC_API_URL}/auth/token/`,
16+
{
17+
method: 'POST',
18+
headers: { 'Content-Type': 'application/json' },
19+
body: JSON.stringify({ refresh: refreshToken }),
20+
},
21+
);
22+
23+
if (!response.ok) {
24+
throw new Error('Failed to fetch new token');
25+
}
26+
27+
const data = await response.json();
28+
29+
return data;
30+
};
31+
1332
export const authOptions: AuthOptions = {
1433
session: {
1534
strategy: 'jwt',
@@ -48,19 +67,7 @@ export const authOptions: AuthOptions = {
4867

4968
// Obtain new token pair and new profile data
5069
if (!refreshTokenPromiseCache[tokenId]) {
51-
refreshTokenPromiseCache[tokenId] = new Promise<RefreshedTokens>((resolve, reject) => {
52-
fetch(
53-
`${process.env.NEXT_PUBLIC_API_URL}/auth/token/`,
54-
{
55-
method: 'POST',
56-
headers: { 'Content-Type': 'application/json' },
57-
body: JSON.stringify({ refresh: token.refreshToken }),
58-
},
59-
)
60-
.then<RefreshedTokens>((resp) => resp.json())
61-
.then((resp) => resolve(resp))
62-
.catch((err) => reject(err));
63-
});
70+
refreshTokenPromiseCache[tokenId] = fetchNewToken(token.refreshToken);
6471
}
6572
const { access, refresh, profile } = await refreshTokenPromiseCache[tokenId];
6673

0 commit comments

Comments
 (0)