Skip to content
This repository has been archived by the owner on Apr 23, 2024. It is now read-only.

Commit

Permalink
implement refresh token in fetcher
Browse files Browse the repository at this point in the history
  • Loading branch information
mgilangjanuar committed Sep 16, 2021
1 parent f77d00d commit 37ff9b9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions web/src/pages/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const Navbar: React.FC<Props> = ({ user }) => {
const logout = async () => {
await req.post('/auth/logout')
JSCookie.remove('authorization')
localStorage.removeItem('refreshToken')
location.replace('/')
}

Expand Down
15 changes: 14 additions & 1 deletion web/src/utils/Fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,25 @@ export const req = axios.create({
})

export const fetcher = async (url: string, authorization?: string): Promise<any> => {
try {
const fetch = async () => {
const { data } = await req.get(url, {
...authorization ? { headers: { authorization: `Bearer ${authorization}` } } : {},
withCredentials: true })
return data
}

try {
return await fetch()
} catch ({ response }) {
if ((response as any)?.status === 401 && localStorage.getItem('refreshToken')) {
try {
const { data } = await req.post('/auth/refreshToken', { refreshToken: localStorage.getItem('refreshToken') })
localStorage.setItem('refreshToken', data.refreshToken)
return await fetch()
} catch (error) {
throw response
}
}
throw response
}
}

0 comments on commit 37ff9b9

Please sign in to comment.