Created
March 2, 2020 06:15
-
-
Save wanmigs/2d707a8ee1221429b7278785c63dca66 to your computer and use it in GitHub Desktop.
Axios Inteceptors
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
import getConfig from 'next/config' | |
import axios from 'axios'; | |
import { isLoggedIn, logout } from './auth' | |
const { | |
publicRuntimeConfig: {API_URL}, // Available both client and server side | |
} = getConfig() | |
let axiosIntance = { ...axios} | |
axiosIntance.defaults.baseURL = API_URL | |
let token = isLoggedIn() | |
if (token) { | |
axiosIntance.interceptors.request.use((config) => { | |
config.headers.common['Authorization'] = `Bearer ${token}` | |
return config; | |
}, (error) => { | |
return Promise.reject(error); | |
}); | |
axiosIntance.interceptors.response.use(function (response) { | |
return response; | |
}, function (error) { | |
if (401 === error.response.status) { | |
logout() | |
} else { | |
return Promise.reject(error); | |
} | |
}); | |
} | |
export default axiosIntance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
auth.js