Nuxt.js
Using Pinia with Nuxt.js is easier since Nuxt takes care of a lot of things when it comes to server side rendering. For instance, you don't need to care about serialization nor XSS attacks. Pinia supports Nuxt Bridge and Nuxt 3, for bare Nuxt 2 support, See below.
Installation
yarn add @pinia/nuxt
# or with npm
npm install @pinia/nuxt
We supply a module to handle everything for you, you only need to add it to buildModules
in your nuxt.config.js
file:
// nuxt.config.js
export default {
// ... other options
buildModules: [
// ...
'@pinia/nuxt',
],
}
And that's it, use your store as usual!
Using the store outside of setup()
If you want to use a store outside of setup()
, remember to pass the pinia
object to useStore()
. We added it to the context so you have access to it in asyncData()
and fetch()
:
import { useStore } from '~/stores/myStore'
export default {
asyncData({ $pinia }) {
const store = useStore($pinia)
},
}
Auto imports
By default @pinia/nuxt
exposes one single auto import: usePinia()
, which is similar to getActivePinia()
but works better with Nuxt. You can add auto imports to make your life easier:
// nuxt.config.js
export default {
// ... other options
buildModules: [
// ...
[
'@pinia/nuxt',
{
autoImports: [
// automatically imports `usePinia()`
'defineStore',
// automatically imports `usePinia()` as `usePiniaStore()`
['defineStore', 'definePiniaStore'],
],
},
],
],
}
TypeScript
If you are using TypeScript or have a jsconfig.json
, you should also add the types for context.pinia
:
{
"types": [
// ...
"@pinia/nuxt"
]
}
This will also ensure you have autocompletion 😉 .
Nuxt 2 without bridge
Pinia supports Nuxt 2 until @pinia/nuxt
v0.2.1. Make sure to also install @nuxtjs/composition-api
alongside pinia
:
yarn add pinia @pinia/nuxt@0.2.1 @nuxtjs/composition-api
# or with npm
npm install pinia @pinia/nuxt@0.2.1 @nuxtjs/composition-api
We supply a module to handle everything for you, you only need to add it to buildModules
in your nuxt.config.js
file:
// nuxt.config.js
export default {
// ... other options
buildModules: [
// Nuxt 2 only:
// https://composition-api.nuxtjs.org/getting-started/setup#quick-start
'@nuxtjs/composition-api/module',
'@pinia/nuxt',
],
}
Using Pinia alongside Vuex
It is recommended to avoid using both Pinia and Vuex but if you need to use both, you need to tell pinia to not disable it:
// nuxt.config.js
export default {
buildModules: [
'@nuxtjs/composition-api/module',
['@pinia/nuxt', { disableVuex: false }],
],
// ... other options
}