Created
August 18, 2021 17:05
-
-
Save mucahitgurbuz/2645e4acc18e3b59d69d465821000efd to your computer and use it in GitHub Desktop.
Axios interceptors to check authorization and append a valid token
This file contains 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
// Request interceptor for API calls | |
axios.interceptors.request.use( | |
async config => { | |
const token = await getTokenSilently(); | |
config.headers.authorization = `Bearer ${token}`; | |
return config; | |
}, | |
error => { | |
Promise.reject(error); | |
} | |
); | |
// Response interceptor for API calls | |
axios.interceptors.response.use( | |
response => { | |
return response.data; | |
}, | |
async function(error) { | |
if (error.response?.status === 401 || error?.error === 'login_required') { | |
history.push(urls.authentication); | |
} | |
return Promise.reject(error); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment