Home

Awesome

pinia-persistedstate

For vue3. Persist and rehydrate your Pinia state between page reloads. frok from vuex-persistedstate

<hr />

Install

npm install --save pinia-persistedstate

The UMD build is also available on unpkg:

<script src="https://unpkg.com/pinia-persistedstate/dist/pinia-persistedstate.umd.js"></script>

You can find the library on window.createPersistedState.

Usage

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import persistedstate from 'pinia-persistedstate'
import App from './App'

const app = createApp(App)
const store = createPinia()

store.use(
  persistedstate({
    key: 'client'
    // paths: ['dataStore', 'dataStore.count']  // Keep state, use module id, or state
  })
)

app.use(store)

Example with pinia modules

New plugin instances can be created in separate files, but must be imported and added to plugins object in the main pinia file.

/* module.js */
import { defineStore } from 'pinia'

export const dataStore = defineStore({
  id: 'dataStore',
  state: () => {
    return {
      count: 0
    }
  },
  actions: {
    increment(data) {
      this.count = data
    }
  }
})


/* demo.tsx */
import { dataStore } from './module'

...
  setup: () => {
    const store = dataStore()

    store.increment()

    return () => {
      <div>{ store.count }</div>
    }
  }
...

// ~/plugins/persistedState.js

import createPersistedState from 'pinia-persistedstate';
import * as Cookies from 'js-cookie';
import cookie from 'cookie';

export default ({ store, req }) => {
    createPersistedState({
        paths: [...],
        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)
}

API

createPersistedState([options])

Creates a new instance of the plugin with the given options. The following options can be provided to configure the plugin for your specific needs:

Customize Storage

If it's not ideal to have the state of the pinia store inside localstorage. One can easily implement the functionality to use cookies for that (or any other you can think of);

In fact, any object following the Storage protocol (getItem, setItem, removeItem, etc) could be passed:

createPersistedState({ 
  storage: window.sessionStorage 
})

This is especially useful when you are using this plugin in combination with server-side rendering, where one could pass an instance of dom-storage.

🔐Obfuscate Local Storage

If you need to use Local Storage (or you want to) but want to prevent attackers from easily inspecting the stored data, you can obfuscate it.

Important ⚠️ Obfuscating the pinia store means to prevent attackers from easily gaining access to the data. This is not a secure way of storing sensitive data (like passwords, personal information, etc.), and always needs to be used in conjunction with some other authentication method of keeping the data (such as Firebase or your own server).

import { Store } from "pinia";
import createPersistedState from "pinia-persistedstate";
import SecureLS from "secure-ls";
var ls = new SecureLS({ isCompression: false });

// https://github.com/softvar/secure-ls

createPersistedState({
  storage: {
    getItem: (key) => ls.get(key),
    setItem: (key, value) => ls.set(key, value),
    removeItem: (key) => ls.remove(key)
  }
})