-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
69 lines (58 loc) · 2.22 KB
/
api.ts
File metadata and controls
69 lines (58 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import axios from 'axios'
import { getCookie, setCookie } from 'cookies-next'
import { NAVIGATION } from '@/config'
const api = axios.create()
api.interceptors.request.use(
(config) => {
const token = getCookie('access')
if (token) {
if (!config.headers) {
config.headers = axios.AxiosHeaders.from({})
}
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => Promise.reject(error),
)
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config
// Handle 401 Unauthorized - try to refresh token
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true
try {
const response = await axios.post(NAVIGATION.AUTH_REFRESH)
const { access } = response.data
setCookie('access', access, { path: '/', sameSite: 'lax' })
// Dispatch a custom event to notify the app about token refresh
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('tokenRefreshed'))
}
if (!originalRequest.headers) {
originalRequest.headers = axios.AxiosHeaders.from({})
}
originalRequest.headers.Authorization = `Bearer ${access}`
console.log('Token refreshed!')
return api(originalRequest)
} catch (refreshError) {
console.error('Refresh token failed', refreshError)
// Redirect to login if refresh fails
if (typeof window !== 'undefined') {
window.location.href = '/'
}
return Promise.reject(refreshError)
}
}
// Handle 403 Forbidden - redirect to login
if (error.response?.status === 403) {
console.error('Access forbidden - redirecting to login')
if (typeof window !== 'undefined') {
window.location.href = '/'
}
}
return Promise.reject(error)
},
)
export default api