Last active
          February 29, 2024 07:37 
        
      - 
      
 - 
        
Save wobsoriano/902cce12639a1faa0764542e3732fce5 to your computer and use it in GitHub Desktop.  
    nuxtServerInit like implementation for Pinia
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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 | |
| }) | |
| } | |
| } | |
| }) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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'] } } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
@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/......