[Vuejs]-Vue resource interceptor to refresh JWT token

0👍

I think the chaining of callbacks is not quite right. The second call to next should happen when the first call returns a promise, and should not depend on the logic applied to resolve the first promise, only on successful resolution of that promise.

Vue.http.interceptors.push(function (request, next) {

  if (!request.headers.has('Authorization') && window.localStorage.access_token) {
    request.headers.set('Authorization', `Bearer ${window.localStorage.access_token}`);
  }

  next(function (response) {
    if (response.status === 401) {
        const refreshToken = localStorage.getItem('refresh_token');

        return Vue.http.post('/api/v4/auth/refresh', null, {
            headers: {'Authorization': `Bearer ${refreshToken}`}
        }).then((response) => {
            localStorage.setItem('access_token', response.data.accessToken);
            localStorage.setItem('refresh_token', response.data.refreshToken);
        })
    }
    return Promise.resolve(response)
  }).then(() => {
     next(); // This is called whenever the first callback returns a promise
  });
})

Leave a comment