Skip to content

Instantly share code, notes, and snippets.

@janczizikow
Created December 22, 2019 18:01
Show Gist options
  • Select an option

  • Save janczizikow/dc8cbf094a057e3c73607772f3817bd7 to your computer and use it in GitHub Desktop.

Select an option

Save janczizikow/dc8cbf094a057e3c73607772f3817bd7 to your computer and use it in GitHub Desktop.
axios refresh token interceptor
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