I want to use window.localStorage in Vuex in Nuxt.js

Viewed 15534

I developing nuxt.js app. And point is login & logout.


We will develop a login to the JWT system.

You must remain logged in at vuex.

However, when I refresh the page, vuex is initialized.

I've read git vuex-persistedstate , but it's hard to understand just how to initialize and set it.

What is the best way to develop a login system in nuxt.js?

Thanks.

5 Answers

Better to use cookies for saving authorization token, look at this nuxt module

https://github.com/microcipcip/cookie-universal/tree/master/packages/cookie-universal-nuxt

Here sample on vuex store module to set cookie

//call async ajax request to get UUID
const uuidReq = await dispatch('getUUID')

if (uuidReq.hasOwnProperty('meta')) {
  commit('setState', {
    uuid: uuidReq.meta.links.me.meta.id,
    isLogin: true
  })

  // calculate expires
  const expDate = new Date()
  expDate.setTime(expDate.getTime() + (state.accExpKey - 0.3) * 1000)
  const expDate2 = new Date()
  expDate2.setTime(expDate.getTime() + 2592000 * 1000)

  const options = {
    path: '/',
    expires: expDate
  }
  const options2 = {
    path: '/',
    expires: expDate2
  }

  const cookieList = [{
      name: 'g_isLogin',
      value: true,
      opts: options2
    },
    {
      name: 'g_accKey',
      value: state.accKey,
      opts: options
    },
    {
      name: 'g_refKey',
      value: state.refKey,
      opts: options2
    },
    {
      name: 'g_userUUID',
      value: uuidReq.meta.links.me.meta.id,
      opts: options
    }
  ]
  this.$cookies.setAll(cookieList)
}

Here sample implementation on custom Nuxt middleware check existing cookie then inject them into vuex state

export default function({ store, route, redirect, app }) {
  const isLogin = app.$cookies.get('g_isLogin') === 'true'
  const accKey = app.$cookies.get('g_accKey') || ''
  const refKey = app.$cookies.get('g_refKey') || ''
  const userUUID = app.$cookies.get('g_userUUID') || ''

  // console.warn('authenticated isLogin:', isLogin)

  // If the user authenticated
  if (isLogin) {
    store.commit('user/setState', {
      isLogin: isLogin,
      accKey: accKey,
      refKey: refKey,
      uuid: userUUID
    })
  } else {
    return redirect('/?prevURL=' + route.path)
  }
}

I would strongly recommend using cookies over localStorage with nuxt and the vuex store. Using a package such as univeral-cookie and the built-in nuxtServerInit action, you can populate both client and server stores by reading the cookies on the initial request from the server. You may be limited in the amount of data you can store with cookies but if you implement a RESTful-like API and store ids in your cookies whenever possible, you can server-side fetch that data to populate the full stack store thereby setting yourself up very well in cases where the user refreshes the page. I found it very handy with auth tokens, too, which expire on their own cookie-related behavior and hence wont exist in the store (or its mutation handled decoded data) in cases where the page refreshes.

for using vuex-persistedstate in nuxt both client and server , follow these steps.

For example consider you have a Vuex Module user and you want to persist it . even if you refresh or route to another page.

const user = {
    namespaced: true,
    state: () => ({
        name: 'geeekfa'
    }),
    mutations: {
        name(state, name) {
            state.name = name;
        },
    },
    getters: {
        name: (state) => {
            return state.name;
        },
    }
}
export default user
  1. install vuex-persistedstate

npm install --save vuex-persistedstate

  1. install cookie & js-cookie

npm install --save cookie js-cookie

after that your package.json is like :

  "dependencies": {
    ...
    "cookie": "^0.3.1",
    "js-cookie": "^2.2.1",
    "vuex-persistedstate": "^4.0.0-beta.3",
    ...
  }
  1. create persistedState.js in ~/plugin/persistedState.js
// persistedState.js
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
import cookie from 'cookie'

export default ({ store, req }) => {
  createPersistedState({
    paths: ['user'], // your vuex module name
    storage: {

      getItem: (key) => {
        if (process.server) {
          const parsedCookies = cookie.parse(req.headers.cookie)
          return parsedCookies[key]
        } else {
          return Cookies.get(key)
        }
      },
   
      setItem: (key, value) =>
        Cookies.set(key, value, { expires: 365, secure: false }),
      removeItem: key => Cookies.remove(key)
    }
  })(store)
}
  1. add this plugin to nuxt.config.js
plugins: [
    ...
    { src: '~/plugins/persistedState.js' }
    ...
  ],

this is enough ! you can persist user module even after refresh in both client and server side . there is no need to change ~/store/index.js file

Related