Composables
useAuthStore
Access authentication state
useAuthStore is a composable that provides access to the authentication state, including the current user and authentication status.
Usage
const authStore = useAuthStore();
Return Value
Returns a reactive state object with the following properties:
| Property | Type | Description |
|---|---|---|
user | User | null | The authenticated user object or null |
loggedIn | boolean | Whether the user is currently authenticated |
strategy | string | The name of the active authentication strategy |
Examples
Check Authentication Status
const authStore = useAuthStore();
if (authStore.loggedIn) {
console.log('User is authenticated');
} else {
console.log('User is not authenticated');
}
Access Current User
const authStore = useAuthStore();
if (authStore.user) {
console.log('User name:', authStore.user.name);
console.log('User email:', authStore.user.email);
}
Get Active Strategy
const authStore = useAuthStore();
console.log('Active strategy:', authStore.strategy);
Reactive Usage in Components
<script setup>
const authStore = useAuthStore();
const userName = computed(() => authStore.user?.name || 'Guest');
const isAuthenticated = computed(() => authStore.loggedIn);
</script>
<template>
<div>
<p v-if="isAuthenticated">Welcome, {{ userName }}!</p>
<p v-else>Please log in</p>
</div>
</template>
Watch for Authentication Changes
const authStore = useAuthStore();
watch(() => authStore.loggedIn, (isLoggedIn) => {
if (isLoggedIn) {
console.log('User just logged in');
} else {
console.log('User just logged out');
}
});
Complete Example
<script setup>
const authStore = useAuthStore();
const user = computed(() => authStore.user);
const isLoggedIn = computed(() => authStore.loggedIn);
const strategy = computed(() => authStore.strategy);
const handleLogout = async () => {
const { $auth } = useNuxtApp();
await $auth.logout(strategy.value);
};
</script>
<template>
<div v-if="isLoggedIn">
<h1>Welcome, {{ user?.name }}</h1>
<p>Email: {{ user?.email }}</p>
<p>Strategy: {{ strategy }}</p>
<button @click="handleLogout">Logout</button>
</div>
<div v-else>
<p>Please log in to continue</p>
</div>
</template>
Notes
useAuthStoreuses Vue'suseStateunder the hood, making it reactive and SSR-friendly- The state is reactive and shared only within the current app/request
- Persistence across page reloads or SSR requests is handled by the configured cookies/tokens
- The
userobject structure depends on your API's user endpoint response - This composable is the primary way to access authentication state in your components