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.
I have used vuex-persist package instead, very easy to get it up and running. This works for SSR too.
Just make sure to condition everything to just run in the browser
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.
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.
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
You also need js-cookie package which makes handling cookies easier. Use
npm install --save js-cookie
.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:
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