Skip to content

Instantly share code, notes, and snippets.

@alexandersandberg
Last active November 4, 2019 14:28
Show Gist options
  • Save alexandersandberg/3a12857d84517c1c02879a9a0f71deec to your computer and use it in GitHub Desktop.
Save alexandersandberg/3a12857d84517c1c02879a9a0f71deec to your computer and use it in GitHub Desktop.
Vue/Nuxt axios plugin with custom interceptors to retry a failed request due to expired tokens
import axios from 'axios'
export default function({ $axios, store }) {
$axios.onRequest((config) => {
const userAccessToken = store.state.auth.userAccessToken
if (userAccessToken) {
config.headers.common.Authorization = `Bearer ${userAccessToken}`
}
})
$axios.onError((error) => {
const code = parseInt(error.response && error.response.status)
const originalRequest = error.config
if (
code === 401 &&
error.request.responseURL.includes(process.env.apiBaseUrl)
) {
return store.dispatch('auth/getCurrentUser').then(() => {
const updatedUserAccessToken = store.state.auth.userAccessToken
originalRequest.headers.Authorization = `Bearer ${updatedUserAccessToken}`
return axios
.request(originalRequest)
.then((response) => {
return response
})
.catch(() => {
store.dispatch('auth/signOut')
})
})
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment