I have the browser storing the token, userid, user email and expiration date (it is stored in local storage and cookie through dev tools). But on refresh it clears the state yet the local storage and cookie information is still there in the browser, I am guessing something is wrong in the store or I should do something else to retain the information?
On my login page, this is my logic for sending the info, getting the token and such from the backend and trying to commit it to my mutation:
async submitForm() {
const response = await axios.post(
'http://localhost:3000/api/user/login',
{
email: this.email,
password: this.password,
}
);
const responseData = await response.data;
const expiresIn = +responseData.expiresIn * 5000;
const expirationDate = new Date().getTime() + expiresIn;
localStorage.setItem('token', responseData.token);
localStorage.setItem('userId', responseData.userId);
localStorage.setItem('email', responseData.email);
localStorage.setItem('tokenExpiration', expirationDate);
this.$cookies.set('token', responseData.token);
this.$cookies.set('userId', responseData.userId);
this.$cookies.set('email', responseData.email);
this.$cookies.set('tokenExpiration', expirationDate);
this.$store.commit('setUser', {
token: responseData.token,
userId: responseData.userId,
});
},
},
This is my store information that I have
Index.js
import mutations from './mutations.js';
import getters from './getters.js';
export default {
state() {
return {
userId: null,
token: null,
didAutoLogout: false,
};
},
mutations,
getters,
};
mutations.js
export default {
setUser(state, payload) {
state.token = payload.token;
state.userId = payload.userId;
state.didAutoLogout = false;
},
setAutoLogout(state) {
state.didAutoLogout = true;
},
};
getters.js
export default {
userId(state) {
return state.userId;
},
token(state) {
return state.token;
},
isAuthenticated(state) {
return !!state.token;
},
didAutoLogout(state) {
return state.didAutoLogout;
},
};
And I call isAuthenticated in my default layout like so:
export default {
computed: {
isAuthenticated() {
return this.$store.getters.isAuthenticated;
},
},
};
I tried nuxt auth using cookie:
auth: {
strategies: {
cookie: {
token: {
property: 'token',
global: true,
},
},
},
},
and local:
auth: {
strategies: {
local: {
token: {
property: 'token',
global: true,
},
},
},
},