Created
December 22, 2019 18:01
-
-
Save janczizikow/dc8cbf094a057e3c73607772f3817bd7 to your computer and use it in GitHub Desktop.
axios refresh token interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import axios from 'axios'; | |
| import { | |
| getAccessToken, | |
| getRefreshToken, | |
| } from '../auth/auth'; | |
| const api = axios.create({ | |
| baseURL: 'http://localhost:3000', | |
| timeout: 2000, | |
| headers: { | |
| 'Content-type': 'application/json', | |
| Accept: 'application/json', | |
| }, | |
| }); | |
| api.interceptors.response.use( | |
| response => response, | |
| error => { | |
| const originalRequest = error.config; | |
| if (error.response.status === 401) { | |
| const refreshToken = getRefreshToken(); | |
| // Remove authorization header with expired access token | |
| api.defaults.headers.Authorization = null; | |
| // Refresh access and refresh tokens and retry previous request | |
| return refreshTokens(refreshToken).then(() => { | |
| originalRequest.headers.Authorization = 'Bearer ' + getAccessToken(); | |
| return axios(originalRequest); | |
| }); | |
| } else { | |
| return Promise.reject(error); | |
| } | |
| }, | |
| ); | |
| export default api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment