nuxt-community / universal-storage-module

Universal Storage Utilities for Nuxt 2
MIT License
276 stars 15 forks source link

Nuxt 2 Universal Storage Module

npm (scoped with tag) npm GitHub Actions Codecov Dependencies js-standard-style

Universal Storage Utilities for Nuxt 2 based on @nuxt-community/auth-module

📖 Release Notes

Setup

yarn add @nuxtjs/universal-storage

OR

npm install @nuxtjs/universal-storage --save
{
  modules: [
    '@nuxtjs/universal-storage',
  ],

  storage: {

  }
}

TypeScript

Add the types to your "types" array in tsconfig.json

{
  "compilerOptions": {
    "types": [
      "@nuxt/types",
      "@nuxtjs/universal-storage"
    ]
  }
}

Usage

Options

Options are defined as following:

 storage: {
  vuex, // boolean or {namespace}
  localStorage, // boolean or {prefix}
  cookie, // boolean or {prefix, options}
  initialState,  // Object {}
  ignoreExceptions //
 }

and default to the following values:

 {
  vuex: {
    namespace: 'storage'
  },
  cookie: {
    prefix: '',
    options: {
      path: '/'
    }
  },
  localStorage: {
    prefix: ''
  },
  ignoreExceptions: false,
}

Full synchronise on start with initialState as default

Since version 0.4.0 this module allows full state synchronisation with cookies, localStorage and initialState as a default value. That allows for a very neat usage pattern: For example, if you have an initialState like the following in your nuxt.config.js file:

  storage: {
    initialState: { testParam: false }
  }

then in my component I can simply declare (with decorators)

  @State(s => s.storage.testParam)
  testParam

or (with mapState)

  computed: mapState({
    testParam: s => s.storage.testParam
  })

Afterwards you can get the computed property testParam with whatever value it had in your last session and on change you just have to call this.$storage.setUniversal("testParam", newVal) to get the new value saved.

Hidden settings (private state)

Private state is suitable to keep information not being exposed to the Vuex store. This helps prevent stealing tokens from the SSR response HTML.

If the key name starts with _ then that value is kept separate in the memory storage and not exposed to the Vuex store like the rest of the values.

For example:

  $storage.setState("_password", "alpha1")

Api

Development

Roadmap

License

MIT License