@@ -14,38 +14,50 @@ const getAccessToken = (): string | null => {
1414 return '' ;
1515} ;
1616
17+ const redirectToLogin = ( ) => {
18+ const { pathname } = window . location ;
19+ const redirectPages = [ '/desktop/login' , '/mobile/sign-in' ] ;
20+
21+ if ( ! redirectPages . includes ( pathname ) ) {
22+ window . location . replace (
23+ pathname . startsWith ( '/desktop' ) ? '/desktop/login' : '/mobile/sign-in' ,
24+ ) ;
25+ }
26+ } ;
27+
1728const PrivateAxiosInstance = axios . create ( {
1829 baseURL : process . env . NEXT_PUBLIC_API_BASE_URI ,
1930 headers : {
2031 'Content-Type' : 'application/json' ,
2132 } ,
2233} ) ;
2334
35+ // 요청 인터셉터
2436PrivateAxiosInstance . interceptors . request . use (
2537 ( config : InternalAxiosRequestConfig ) => {
2638 const token = getAccessToken ( ) ;
27- if ( ! token ) {
28- const redirectPages = [ '/desktop/login' , '/mobile/sign-in' ] ;
29- const { pathname } = window . location ;
30-
31- if ( ! redirectPages . includes ( pathname ) ) {
32- window . location . replace (
33- pathname . startsWith ( '/desktop' )
34- ? '/desktop/login'
35- : '/mobile/sign-in' ,
36- ) ;
37- }
3839
40+ if ( ! token ) {
41+ redirectToLogin ( ) ;
3942 return Promise . reject ( new AxiosError ( 'No authentication token found' ) ) ;
4043 }
4144
4245 const newConfig = { ...config , withCredentials : false } ;
43- if ( token ) {
44- newConfig . headers . set ( 'Authorization' , `Bearer ${ token } ` ) ;
45- }
46+ newConfig . headers . set ( 'Authorization' , `Bearer ${ token } ` ) ;
4647 return newConfig ;
4748 } ,
4849 ( error ) => Promise . reject ( error ) ,
4950) ;
5051
52+ PrivateAxiosInstance . interceptors . response . use (
53+ ( response ) => response ,
54+ ( error : AxiosError ) => {
55+ if ( error . response ?. status === 401 ) {
56+ localStorage . clear ( ) ;
57+ redirectToLogin ( ) ;
58+ }
59+ return Promise . reject ( error ) ;
60+ } ,
61+ ) ;
62+
5163export default PrivateAxiosInstance ;
0 commit comments