DEV Community

loading...

vuex-persistedstate is all you need for your Vue and Nuxt project

Mohammad Shahbaz Alam
I’m a Full Stack Developer, Developer Advocate @ Magic, GDG Ranchi Organizer, and Mozilla Representative.
・2 min read

If you have worked with Vue or Nuxt application, I am sure you have had a hard time managing the sessions, storing cookies, and working with localStorage.

Luckily we have a vuex-persistedstate package to help us with all these.

You just need to install the package and configure it for your project. That's it. All your browser refreshes won't affect the application state.

Install

npm install vuex-persistedstate // npm
// OR
yarn add vuex-persistedstate // yarn
Enter fullscreen mode Exit fullscreen mode

Usage

vuex-persistedstate 3.x (for Vuex 3 and Vue 2)

import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()],
});
Enter fullscreen mode Exit fullscreen mode

vuex-persistedstate 4.x (for Vuex 4 and Vue 3)

import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

const store = createStore({
  // ...
  plugins: [createPersistedState()],
});
Enter fullscreen mode Exit fullscreen mode

Example with Nuxt.js

Create a file persistedState.client.js inside the plugins directory.

Note: Naming your plugin 'xxx.client.js' will make it execute only on the client-side. Learn more

// ~/plugins/persistedState.client.js
import createPersistedState from 'vuex-persistedstate'

export default ({ store }) => {
  createPersistedState()(store)
}
Enter fullscreen mode Exit fullscreen mode

Then, update your plugins inside the nuxt.config.js file.

// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [{ src: '~/plugins/persistedState.client.js' }],
Enter fullscreen mode Exit fullscreen mode

That's it, your Nuxt.js application is now state persistent and will be able to handle manual browser refreshes.

That's it for this post.

If you want to see how it works in a Vue.js application, please leave a comment below, I will include that too.

Live Demo using vuex-persistedstate: https://magic-nuxtjs.vercel.app/login

I have used vuex-persistedstate in my How to add Magic Link to a Nuxt.js Application guide. Check out and share your feedback.

Discussion (2)

Collapse
devondahon profile image
gvi

It doesn't seem to be compatible with @nuxt/auth (and @nuxt/auth-next).

Collapse
shahbaz17 profile image
Mohammad Shahbaz Alam Author

Let me confirm this.