@pinia/nuxt module.
Pinia Integration
Pinia is configured innuxt.config.ts as a module:
nuxt.config.ts
With
@pinia/nuxt, all stores are automatically imported and available throughout your application without manual imports.Authentication Store
The auth store manages user authentication state, including the current user and access token.Store Implementation
stores/auth.ts
Store Structure
State
State
The State properties:
state function returns the initial state object:user: Stores user information after successful logintoken: JWT token for API authentication
Actions
Actions
Actions are methods that can modify the state:setUser(userData, token)
- Stores user data and token in state
- Persists token to localStorage
- Called after successful login
- Clears user and token from state
- Removes token from localStorage
- Called when user logs out
- Restores token from localStorage on app load
- Maintains authentication across page refreshes
Using Stores in Components
In Pages
Here’s how the auth store is used in the login page:pages/index.vue
In Middleware
The auth store is used in route middleware to protect authenticated routes:middleware/auth.ts
- Middleware checks if user has a token
- If no token exists, redirects to login page
- On mount, restores token from localStorage
In Layouts
The logout functionality in the default layout uses the auth store:layouts/default.vue
Store Best Practices
Keep State Minimal
Only store data that needs to be shared across multiple components
Use Actions
Always modify state through actions, never directly mutate state
Persist Critical Data
Use localStorage for data that should survive page refreshes (like tokens)
Initialize on Load
Restore persisted state when the app loads using initialization actions
Common Patterns
Accessing Store State
Calling Store Actions
Reactive Store State in Templates
Creating New Stores
To create a new store, follow this pattern:stores/newStore.ts
Store naming convention: Use
useXxxStore for the function name and a descriptive string for the store ID.Next Steps
Composables
Learn about reusable composable functions
API Integration
Understand API calls and authentication