Home > other >  Nuxt - Store not keeping logged in state on refresh but info still in local storage & cookie
Nuxt - Store not keeping logged in state on refresh but info still in local storage & cookie

Time:06-23

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,
            },
        },
    },
},

CodePudding user response:

By default when you hard refresh, you get a new instance of the app, so the store will be re-initialized to its initial state.

As Nuxt is a server-side framework for Vue, One solution is using Cookies to maintain the state with your store.

UPDATE

By using cookie-universal-nuxt module ( you have access to cookies on the client and server-side )

To reinitialize your store on each refresh with cookies value on the server-side.

In your store actions, add this method. ( this method will executes on server-side on initial state of the app )

export default {
  nuxtServerInit({ commit }, { req, app }) {
    const token = app.$cookies.get('token')
    const userId = app.$cookies.get('userId')
    const payload = {
        token,
        userId
    }
    commit('setUser', payload)
  },
};
  • Related