'Refresh the homepage store auth token going to null

How does Nuxt.js token use set constant after done local Storage. I have a Nuxt.js app with nuxtjs axios for authentication. My backend is in Laravel used to handle authentication. When I log first time its coming good and its redirect every page after come back to home page the and when I do refresh the stored initial token value going to null, but page is redirecting well.

my question is, 2. I did local Storage and cookie.

  1. In my Vuex store I did like initially token is null, parallelly in the header showing Login and register nav-item, once user loggedIn header shows logout. after login I going all page but once come back to home page and refresh the page in the store token going to token null in store again its shows login and register item. but its giving access to go for all page.

import Vuex from "Vuex";
import Cookie from "js-cookie";

const createStore = () => {
  return new Vuex.Store({
    state: {
      token: null,
    },

    mutations: {
      setToken(state, token) {
        state.token = token;
      },

      clearToken(state) {
        state.token = null;
      },
    },

    actions: {

      authenticateUser(vuexContext, authData) {
        return this.$axios.$post("/api/login", {
            email: authData.email,
            password: authData.password,
            name: authData.name,
            returnSecureToken: true,
          })
          .then(result => {
            vuexContext.commit("setToken", result.token);
            localStorage.setItem("token", result.token);
            localStorage.setItem("tokenExpiration", new Date().getTime() + Number.parseInt(result.expiresIn) * 1000)

            Cookie.set('jwt', result.token)
            Cookie.set('expirationDate', new Date().getTime() + Number.parseInt(result.expiresIn) * 1000)
            // vuexContext.dispatch("setLogoutTimer", result.expiresIn * 1000);
          })
          .catch(e => console.log(e));
      },

      // setLogoutTimer(vuexContext, duration) {
      //     set Timeout(() => {
      //       vuexContext.commit("clearToken");
      //     }, duration);
      //   },

      initAuth(vuexContext, req) {
        let token;
        let expirationDate;

        if (req) {
          if (!req.headers.cookie) {
            return;
          }
          const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('jwt='));
          if (!jwtCookie) {
            return;
          }
          token = jwtCookie.split('=')[1];
          expirationDate = req.headers.cookie.split(';').find(c => c.trim().startsWith('expirationDate=')).split('=')[1];
        } else {
          token = localStorage.getItem("token");
          expirationDate = localStorage.getItem("tokenExpiration");
        }
        if (new Date().getTime > +expirationDate || !token) {
          console.log('No token or invalid token');
          vuexContext.dispatch('logout');
          return;
        }
        // vuexContext.dispatch('setLogoutTimer', +expirationDate - new Date().getTime());
        vuexContext.commit('setToken', token);
      },

      logout(vuexContext) {
        vuexContext.commit("clearToken");
        Cookie.remove('jwt');
        Cookie.remove('expirationDate');
        if (process.client) {
          localStorage.removeItem("token");
          localStorage.removeItem("tokenExpiration");
        }
      }
    },
    getters: {
      isAuthenticated(state) {
        return state.token != null
      },


    },
  });
};
export default createStore;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source