Usage with Nuxt3
Persisting pinia stores in Nuxt is easier thanks to the dedicated module.
Installation
- Install the dependency with your favorite package manager:
pnpm i -D @pinia-plugin-persistedstate/nuxt
npm i -D @pinia-plugin-persistedstate/nuxt
yarn add -D @pinia-plugin-persistedstate/nuxt
- Add the module to the Nuxt config (
nuxt.config.ts
):
export default defineNuxtConfig({
modules: [
'@pinia/nuxt',
'@pinia-plugin-persistedstate/nuxt',
],
})
Usage
When declaring your store, set the new persist
option to true
.
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: true,
})
Choosing a storage
By default, your stores will be persisted in cookies (using Nuxt's useCookie
under the hood). You can configure what storage you want to use by using the storages available under the auto-imported persistedState
variable.
INFO
Using other storages than the ones exposed by persistedState
may have unexpected behaviors.
localStorage
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: {
storage: persistedState.localStorage,
},
})
WARNING
localStorage
is client side only.
sessionStorage
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: {
storage: persistedState.sessionStorage,
},
})
WARNING
sessionStorage
is client side only.
cookiesWithOptions
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: {
storage: persistedState.cookiesWithOptions({
sameSite: 'strict',
}),
},
})
TIP
Using cookiesWithOptions()
allows you to configure cookies. Passing no options is the same as using cookies
, which is the default behavior.
Global options
The module accepts some options defined in nuxt.config.ts
under the piniaPersistedstate
key:
export default defineNuxtConfig({
modules: [
'@pinia/nuxt',
'@pinia-plugin-persistedstate/nuxt'
],
piniaPersistedstate: {
cookieOptions: {
sameSite: 'strict',
},
storage: 'localStorage'
},
})
storage
: sets the storage used to persist by default ('localStorage'
,'sessionStorage'
or'cookies'
).cookieOptions
: default cookie options (only used when persisting in cookies).debug
: seedebug
.