Skip to content

Instantly share code, notes, and snippets.

@mucahitgurbuz
Created August 18, 2021 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mucahitgurbuz/2645e4acc18e3b59d69d465821000efd to your computer and use it in GitHub Desktop.
Save mucahitgurbuz/2645e4acc18e3b59d69d465821000efd to your computer and use it in GitHub Desktop.
Axios interceptors to check authorization and append a valid token
// 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