Skip to main content
The useAuthStore is a Pinia store that manages user authentication state, including user data, access tokens, and authentication lifecycle methods.

Source Code

import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        token: null as string | null
    }),

    actions: {
        setUser(userData: any, token: string) {
            this.user = userData
            this.token = token
            localStorage.setItem('access_token', token)
        },
        logout() {
            this.user = null
            this.token = null
            localStorage.removeItem('access_token')
        },
        initializeAuth() {
            const storedToken = localStorage.getItem('access_token')
            if (storedToken) {
                this.token = storedToken
            }
        }
    }
})

State Properties

user
any | null
default:"null"
The authenticated user object. Contains user data returned from the authentication API.
token
string | null
default:"null"
The JWT access token used for authenticating API requests.

Actions

setUser()

Sets the authenticated user and stores the access token.
setUser(userData: any, token: string): void
userData
any
required
The user data object returned from the authentication API
token
string
required
The JWT access token
Side Effects:
  • Updates the user state
  • Updates the token state
  • Persists the token to localStorage with key 'access_token'

logout()

Clears authentication state and removes the stored token.
logout(): void
Side Effects:
  • Sets user to null
  • Sets token to null
  • Removes 'access_token' from localStorage

initializeAuth()

Restores authentication state from localStorage on application startup.
initializeAuth(): void
Side Effects:
  • Reads 'access_token' from localStorage
  • Updates the token state 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

From pages/index.vue:
<script setup>
import { useAuthStore } from '~/stores/auth'

const authStore = useAuthStore()
</script>

Integration with useApi

The auth store works seamlessly with the useApi composable:
// useApi reads the token from localStorage
const token = import.meta.client ? localStorage.getItem('access_token') : null

const api = axios.create({
  baseURL: apiBaseUrl as string,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {})
  }
})
When you call setUser(), the token is persisted to localStorage, which useApi automatically picks up for subsequent requests.

Best Practices

Call initializeAuth() in your app’s main entry point or layout to restore authentication state when the page reloads.
The current implementation stores user data as any type. Consider defining a proper User interface for better type safety.
Tokens are stored in localStorage, which persists across browser sessions. Consider using sessionStorage for more sensitive applications.

Build docs developers (and LLMs) love