Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active February 29, 2024 07:37
Show Gist options
  • Save wobsoriano/902cce12639a1faa0764542e3732fce5 to your computer and use it in GitHub Desktop.
Save wobsoriano/902cce12639a1faa0764542e3732fce5 to your computer and use it in GitHub Desktop.
nuxtServerInit like implementation for Pinia
import { defineStore } from 'pinia'
export const useAuthStore = defineStore({
id: 'auth',
state: () => ({
isAuthenticated: false,
user: null
}),
actions: {
async nuxtServerInit() {
const user = await this.$axios.get('/api/user')
this.$patch({
isAuthenticated: true,
user
})
}
}
})
import { useAuthStore } from '~/store/auth'
export default async function ({ $pinia }) {
if (process.server) {
const store = useAuthStore($pinia)
await store.nuxtServerInit()
}
}
// Add this file to nuxt.config.js
// { router: { middleware: ['nuxt-server-init'] } }
@trandaison
Copy link

You should use nuxt plugins instead of middleware.
Because this middware will be invoked every time route changes (of course you already check process.server, but a plugin should be more suitable)

@kapaha
Copy link

kapaha commented May 2, 2023

A plugin won't wait for the data to be fetch before loading the page?

@LeonardoRick
Copy link

I don't know if it's just the recent versions of nuxt but I'm not being able to call useStore inside defineNuxtPlugin, neither access a valid $pinia on nuxtApp param

@dhaladitya108
Copy link

@LeonardoRick yes you can.
in the nuxt.config we can import store so that it's available throughout the application
imports: { dirs: ['./stores'] }

then the plugins/......

export default defineNuxtPlugins((nuxtApp) => {
   const exampleStore = useExampleStore()
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment