useAuthStore is a Pinia store that manages user authentication state, including user data, access tokens, and authentication lifecycle methods.
Source Code
State Properties
The authenticated user object. Contains user data returned from the authentication API.
The JWT access token used for authenticating API requests.
Actions
setUser()
Sets the authenticated user and stores the access token.The user data object returned from the authentication API
The JWT access token
- Updates the
userstate - Updates the
tokenstate - Persists the token to
localStoragewith key'access_token'
logout()
Clears authentication state and removes the stored token.- Sets
usertonull - Sets
tokentonull - Removes
'access_token'fromlocalStorage
initializeAuth()
Restores authentication state from localStorage on application startup.- Reads
'access_token'fromlocalStorage - Updates the
tokenstate if a token is found
This method only restores the token, not the user data. You may need to fetch user data separately after initialization.
Usage Example
Frompages/index.vue:
Integration with useApi
The auth store works seamlessly with theuseApi composable:
setUser(), the token is persisted to localStorage, which useApi automatically picks up for subsequent requests.
Best Practices
Tokens are stored in localStorage, which persists across browser sessions. Consider using sessionStorage for more sensitive applications.