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 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.use(
createStatePersistence({
storage: {
getItem: Cookies.get, // Get item from cookies
setItem: (key, value) => Cookies.set(key, value), // 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-universal
is properly initialized with the server-side context (req
andres
) for seamless SSR integration. - Custom Storage: Replace
localStorage
with cookies or any other storage mechanism using thestorage
option. - Debug Mode: Enable debugging during development with the
debug
option.
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-persistence
andcookie-universal
packages are installed. - Verify that
pinia
andcookie-universal
are properly configured in your Nuxt project. - Check browser and server behavior for cookie synchronization and state persistence.