I want to use window.localStorage in Vuex in Nuxt.js
Solution 1
Using vuex-persisted state would be the best use case for your scenario.
I will walk you through the process of using vuex-persisted state.
- Open command line,
cd
to your project directory, then enternpm install --save vuex-persistedstate
. This will install vuex-persistedstate into your project dependencoes. - Now in your store.js file or wherever your defined your vuex store, add the vuex-persistedstate plugin
import createPersistedState from "vuex-persistedstate";
import * as Cookie from "js-cookie";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
user: {
name: "john doe",
age: " 16",
},
loggedIn: false,
hobbies: ["eating", "partying"],
},
plugins: [
createPersistedState({
paths: ["user", "loggedIn"],
getState: (key) => Cookie.getJSON(key),
setState: (key, state) =>
Cookie.set(key, state, { expires: 1, secure: false }),
}),
],
});
- You also need js-cookie package which makes handling cookies easier. Use
npm install --save js-cookie
. - The paths property says which parts of the state to persist, in our case save as cookies.If no path property is given, then the whole state is persisted
- From the above example we have mentioned the paths
paths: ['user', 'loggedIn']
, so only user and loggedIn properties of the state are saved in cookies not hobbies. - In case you are using modules in your store, the way of defining the pats to persist would be as follows:
import createPersistedState from "vuex-persistedstate";
import * as Cookie from "js-cookie";
import myModule from "./myModule";
import myAnotherModule from "./myAnotherModule";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
user: {
name: "john doe",
age: " 16",
},
loggedIn: false,
hobbies: ["eating", "partying"],
},
modules: {
myModule,
myAnotherModule,
},
plugins: [
createPersistedState({
paths: ["user", "loggedIn", "myModule.<nameOfThePropretyInState>"],
getState: (key) => Cookie.getJSON(key),
setState: (key, state) =>
Cookie.set(key, state, { expires: 1, secure: false }),
}),
],
});
-
In your paths you will refer to the module's property in the state you want to persist. In the above example, the property of the state that you mention of myModule is persisted. myAnotherModule state is not saved since it is not mentioned in the paths.
-
That's it . If you want to customize the way you use vuex-persisted state and js-cookie, have a look at their documentation.
-
If you want to check whether your desired state is saved in cookies then you can console log your cookies like this:
console.log(document.cookie
in your App.vue created() lifecycle hook
Solution 2
I have used vuex-persist package instead, very easy to get it up and running. This works for SSR too.
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'
Vue.use(Vuex)
let vuexLocalStorage = null;
if (process.browser) {
vuexLocalStorage = new VuexPersist({
key: 'vuex', // The key to store the state on in the storage provider.
storage: window.localStorage, // or window.sessionStorage or localForage
})
}
export function createStore() {
return new Vuex.Store({
state: {
},
actions,
mutations,
getters,
plugins: process.browser ? [vuexLocalStorage.plugin] : []
})
}
Just make sure to condition everything to just run in the browser
Solution 3
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)
}
}
hyeokluv
Updated on June 04, 2022Comments
-
hyeokluv almost 2 years
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.
-
hyeokluv almost 7 yearsoh... thanks. but, I am still not enough. I started the project with nuxt / koa. What is the best way to develop a login system here?
-
hyeokluv almost 7 yearsIn your response, I start the project with nuxt / koa. Create an index.js file in the store folder. I have applied your code. How can I check the contents stored in cookies afterwards? Document.cookie is invalid.
-
Michael Giovanni Pumo over 6 yearsDo you know of any way to get this working with Nuxt specifically? I get a "window is not defined error" because of SSR.
-
Jonas Lomholdt over 6 yearsI have the same issue @MichaelGiovanniPumo. Did you ever solve this?
-
Jimmar over 2 years@JonasLomholdt according to the docs of the library, if you call your plugin as
/plugins/persistedState.client.js
it would only be called on the client side. I'm using localstorage so that makes sense, if you are using cookies then check the docs, they have an example for cookies and nuxt too