I'm trying to access the Vuex store from the axios plugin but I'm getting a window is not defined
error.
/plugins/axios.js
import * as axios from 'axios';
const options = {};
// The server-side needs a full url to works
if (process.server) {
// options.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}`;
options.baseURL = 'https://baseurl.com';
}
axios.interceptors.request.use((request) => {
if (window.$nuxt.$store.state.userToken) {
request.headers.Authorization = `Bearer ${window.$nuxt.$store.state.userToken.token}`;
}
return request;
}, (error) => {
Promise.reject(error);
});
axios.interceptors.response.use(response => response, (error) => {
// ERROR OCCURS HERE
const authInstance = axios.create();
// Do something with response error
const request = error.config;
if (window.$nuxt.$store.state.userToken && error.response && error.response.status === 401 && !request.retry) {
request.retry = true;
return axios.get(`https://baseurl.com/umbraco/api/auth/refreshtoken?token=${window.$nuxt.$store.state.userToken.token}`).then((response) => {
window.$nuxt.$store.state.userToken = response.data;
return authInstance(request);
}).catch(() => {
window.$nuxt.$store.dispatch('logout');
window.location.replace('/');
});
}
return Promise.reject(error);
});
export default axios.create(options);
/store/index.js
// eslint-disable-next-line
import Vue from 'vue';
import Vuex from 'vuex';
import axios from '~/plugins/axios';
Vue.use(Vuex);
const store = () => {
const returnValue = new Vuex.Store({
state: {
userToken: null,
},
mutations: {
SET_USER: function SET_USER(state, user) {
// eslint-disable-next-line
state.userToken = user;
},
},
actions: {
nuxtServerInit({ commit }, { req }) {
if (req.session && req.session.userToken) {
commit('SET_USER', req.session.userToken);
}
},
login({ commit }, { username, password }) {
return axios.post('/api/login', {
username,
password,
}).then((res) => {
if (res.status === 401) {
throw new Error('Bad credentials');
} else {
return res;
}
}).then((userToken) => {
commit('SET_USER', userToken);
});
},
async logout({ commit }) {
await axios.get('/api/logout').then(() => {
commit('SET_USER', null);
});
},
},
});
return returnValue;
};
export default store;
There error is occurring in the /plugins/axios.js
on the response interceptor: axios.interceptors.response.use(response => response, (error) => {
. It comes back as ReferenceError: window is not defined
.