Nuxt Integration
To persist state using cookies in a Nuxt application, we recommend using cookie-universal for its robust cookie synchronization capabilities. This ensures that cookie changes on the server propagate to the client and vice versa.
Example Setup
ts
// @filename: pinia-persistence.ts
import type { Pinia } from 'pinia'
import cookies from 'cookie-universal'
import { createStatePersistence } from 'pinia-plugin-state-persistence'
export default defineNuxtPlugin((nuxtApp) => {
const event = nuxtApp.ssrContext?.event // Access server-side request/response
const Cookies = cookies(event?.node.req, event?.node.res) // Initialize cookie-universal with SSR context
;(nuxtApp.$pinia as Pinia).use(
createStatePersistence({
storage: {
getItem: Cookies.get, // Get item from cookies
setItem: Cookies.set, // Set item in cookies
removeItem: Cookies.remove, // Remove item from cookies
},
}),
)
})Notes:
- Default Storage: The default storage mechanism is
localStorage. This example demonstrates using cookies for storage instead. - SSR Context: Ensure
cookie-universalis properly initialized with the server-side context (reqandres) for seamless SSR integration. - Custom Storage: Replace
localStoragewith cookies or any other storage mechanism using thestorageoption. - Debug Mode: Enable debugging during development with the
debugoption.
Add this file as a Nuxt plugin (e.g., plugins/pinia-persistence.ts) and ensure it is loaded in your Nuxt application.
Troubleshooting:
- Ensure the
pinia-plugin-state-persistenceandcookie-universalpackages are installed. - Verify that
piniaandcookie-universalare properly configured in your Nuxt project. - Check browser and server behavior for cookie synchronization and state persistence.