Last active
November 4, 2019 14:28
-
-
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
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 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