Skip to content

Instantly share code, notes, and snippets.

@tuwukee
Last active August 20, 2019 01:29
Show Gist options
  • Save tuwukee/17ab08d5e69460dcbd4f87e4b145a46f to your computer and use it in GitHub Desktop.
Save tuwukee/17ab08d5e69460dcbd4f87e4b145a46f to your computer and use it in GitHub Desktop.
// todos-vue/src/backend/axios/index.js
import axios from 'axios'
const API_URL = 'http://localhost:3000'
const securedAxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
const plainAxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
securedAxiosInstance.interceptors.request.use(config => {
const method = config.method.toUpperCase()
if (method !== 'OPTIONS' && method !== 'GET') {
config.headers = {
...config.headers,
'X-CSRF-TOKEN': localStorage.csrf
}
}
return config
})
securedAxiosInstance.interceptors.response.use(null, error => {
if (error.response && error.response.config && error.response.status === 401) {
// In case 401 is caused by expired access cookie - we'll do refresh request
return plainAxiosInstance.post('/refresh', {}, { headers: { 'X-CSRF-TOKEN': localStorage.csrf } })
.then(response => {
localStorage.csrf = response.data.csrf
localStorage.signedIn = true
// And after successful refresh - repeat the original request
let retryConfig = error.response.config
retryConfig.headers['X-CSRF-TOKEN'] = localStorage.csrf
return plainAxiosInstance.request(retryConfig)
}).catch(error => {
delete localStorage.csrf
delete localStorage.signedIn
// redirect to signin in case refresh request fails
location.replace('/')
return Promise.reject(error)
})
} else {
return Promise.reject(error)
}
})
export { securedAxiosInstance, plainAxiosInstance }
// todos-vue/src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import VueAxios from 'vue-axios'
import { securedAxiosInstance, plainAxiosInstance } from './backend/axios'
Vue.config.productionTip = false
Vue.use(VueAxios, {
secured: securedAxiosInstance,
plain: plainAxiosInstance
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
securedAxiosInstance,
plainAxiosInstance,
components: { App },
template: '<App/>'
})
@xuanchien
Copy link

Hey, thanks for sharing a useful code. I just want to contribute a bit more. There is a small issue when retrying the request with plainAxiosInstance. If the server responds an error to that request, it will be also be handled in the catch part, which means the user will be logged out automatically.

I think we should do a check to make sure it was indeed a refresh request before clearing the csrf and redirecting users to /

Here is what I am using on my local:

.catch(error => {
        if (error.request.responseURL.includes('/refresh')) {
          delete localStorage.csrf
          delete localStorage.signedIn
          // redirect to home in case refresh request fails
          location.replace('/')
        }

        return Promise.reject(error)
      })

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