pinia/references/advanced-ssr.md
Version e53a142a2420.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.
← Return to resource and package checksum
name: server-side-rendering description: SSR setup, state hydration, and avoiding cross-request state pollution
Server Side Rendering (SSR)
Pinia works with SSR when stores are called at the top of setup, getters, or actions.
Using Nuxt? See the Nuxt integration instead.
Basic Usage
<script setup>
// ✅ Works - pinia knows the app context in setup
const main = useMainStore()
</script>
Using Store Outside setup()
Pass the pinia instance explicitly:
const pinia = createPinia()
const app = createApp(App)
app.use(router)
app.use(pinia)
router.beforeEach((to) => {
// ✅ Pass pinia for correct SSR context
const main = useMainStore(pinia)
if (to.meta.requiresAuth && !main.isLoggedIn) {
return '/login'
}
})
serverPrefetch()
Access pinia via this.$pinia:
export default {
serverPrefetch() {
const store = useStore(this.$pinia)
return store.fetchData()
},
}
onServerPrefetch()
Works normally:
<script setup>
const store = useStore()
onServerPrefetch(async () => {
await store.fetchData()
})
</script>
State Hydration
Serialize state on server and hydrate on client.
Server Side
Use devalue for XSS-safe serialization:
import { stringify } from 'devalue'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(router)
app.use(pinia)
// After rendering, state is available
const serializedState = stringify(pinia.state.value)
// Inject into HTML as global variable
Client Side
Hydrate before any useStore() call:
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
import { parse } from 'devalue'
// window.__pinia is the serialized string produced by stringify above.
// Transfer it through an application-owned, safely escaped HTML/data channel.
if (typeof window !== 'undefined') {
pinia.state.value = parse(window.__pinia)
}
SSR Examples
Key Points
- Call stores inside functions, not at module scope
- Pass
piniainstance when using stores outside components in SSR - Hydrate state before calling any
useStore() - Use
devalueor similar for safe serialization - Avoid cross-request state pollution by creating fresh pinia per request
BB Skills serialization note
This example pairs the current named stringify and parse APIs from devalue. Do not mix a JavaScript expression from uneval with JSON.parse, and do not inject unescaped state into inline HTML. The state transfer channel must preserve the serialized string and follow the application's CSP and escaping rules. Create a fresh Pinia instance per request; hydrate before using stores. This is a code example, not a tested SSR application.