JAVASCRIPT
Vue 3 Pinia Store for Global User Authentication State
Implement a Pinia store in Vue 3 to manage global user authentication state, including login status, user details, and actions, providing a centralized and efficient state management solution.
// stores/auth.js
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
isLoggedIn: false,
user: null, // { id: 1, name: 'John Doe', email: '[email protected]' }
token: null,
}),
getters: {
isAuthenticated: (state) => state.isLoggedIn && state.user !== null,
getUserName: (state) => state.user ? state.user.name : 'Guest',
},
actions: {
async login(credentials) {
// Simulate API call
return new Promise(resolve => {
setTimeout(() => {
if (credentials.username === 'test' && credentials.password === 'password') {
this.isLoggedIn = true;
this.user = { id: 1, name: 'Test User', email: '[email protected]' };
this.token = 'mock_jwt_token';
resolve(true);
} else {
resolve(false);
}
}, 500);
});
},
logout() {
this.isLoggedIn = false;
this.user = null;
this.token = null;
localStorage.removeItem('authToken'); // Clear persisted token
localStorage.removeItem('authUser'); // Clear persisted user
},
initializeAuth() {
// Check localStorage or sessionStorage for persisted token/user data
const storedToken = localStorage.getItem('authToken');
const storedUser = localStorage.getItem('authUser');
if (storedToken && storedUser) {
try {
this.token = storedToken;
this.user = JSON.parse(storedUser);
this.isLoggedIn = true;
} catch (e) {
console.error('Failed to parse stored user data:', e);
this.logout(); // Clear corrupted data
}
}
}
},
});
// How to use in a component:
// <template>
// <div>
// <p v-if="authStore.isAuthenticated">Welcome, {{ authStore.getUserName }}!</p>
// <button v-if="!authStore.isLoggedIn" @click="handleLogin">Login</button>
// <button v-else @click="authStore.logout">Logout</button>
// </div>
// </template>
// <script setup>
// import { useAuthStore } from './stores/auth';
// import { onMounted } from 'vue';
// const authStore = useAuthStore();
// onMounted(() => {
// authStore.initializeAuth(); // Attempt to restore auth state on app load
// });
// const handleLogin = async () => {
// const success = await authStore.login({ username: 'test', password: 'password' });
// if (success) {
// alert('Logged in!');
// // Persist to local storage after successful login
// localStorage.setItem('authToken', authStore.token);
// localStorage.setItem('authUser', JSON.stringify(authStore.user));
// } else {
// alert('Login failed!');
// }
// };
// </script>
How it works: This Pinia store defines a central place to manage user authentication status. It includes `state` for `isLoggedIn`, `user` details, and `token`. `getters` provide derived state like `isAuthenticated`, and `actions` handle asynchronous operations like `login` and `logout`, updating the state accordingly. This pattern ensures consistent access and modification of authentication data across your entire Vue 3 application.