Skip to content

Instantly share code, notes, and snippets.

@wanmigs
Created March 2, 2020 06:15
Show Gist options
  • Save wanmigs/2d707a8ee1221429b7278785c63dca66 to your computer and use it in GitHub Desktop.
Save wanmigs/2d707a8ee1221429b7278785c63dca66 to your computer and use it in GitHub Desktop.
Axios Inteceptors
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
@wanmigs
Copy link
Author

wanmigs commented Mar 2, 2020

auth.js

import Cookie from 'js-cookie'
import axios from 'axios'

export const setToken = (token) => Cookie.set('token', token)
export const isLoggedIn = () => Cookie.get('token')
export const logout = async (callback) => {
  setToken('')
  await axios.post('/logout')
  window.location = '/login'
  callback()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment