JAVASCRIPT

Vue 3 Pinia Store for Global User Authentication

Learn to implement global state management in Vue 3 using Pinia for user authentication, tracking login status, and user data efficiently across components.

// src/stores/auth.js
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoggedIn: false,
    user: null,
    authToken: null,
  }),
  getters: {
    isAuthenticated: (state) => state.isLoggedIn,
    getUser: (state) => state.user,
  },
  actions: {
    login(userData, token) {
      this.isLoggedIn = true;
      this.user = userData;
      this.authToken = token;
      // Optionally, persist token to localStorage
      localStorage.setItem('authToken', token);
    },
    logout() {
      this.isLoggedIn = false;
      this.user = null;
      this.authToken = null;
      localStorage.removeItem('authToken');
    },
    initializeAuth() {
      const token = localStorage.getItem('authToken');
      if (token) {
        // In a real app, validate token with backend
        this.authToken = token;
        this.isLoggedIn = true;
        // Potentially fetch user data based on token
        this.user = { name: 'Guest User', id: '123' }; // Placeholder
      }
    }
  },
});

// src/App.vue (or any component)
<script setup>
import { onMounted } from 'vue';
import { useAuthStore } from './stores/auth';

const authStore = useAuthStore();

onMounted(() => {
  authStore.initializeAuth();
});

const handleLogin = () => {
  // Simulate a login API call
  const userData = { id: 1, name: 'John Doe', email: '[email protected]' };
  const token = 'xyz.abc.123';
  authStore.login(userData, token);
};
</script>

<template>
  <div>
    <h1>Authentication Status</h1>
    <p>Logged In: {{ authStore.isAuthenticated }}</p>
    <p v-if="authStore.user">Welcome, {{ authStore.user.name }}</p>
    <button v-if="!authStore.isAuthenticated" @click="handleLogin">Log In</button>
    <button v-else @click="authStore.logout">Log Out</button>
  </div>
</template>
How it works: This snippet demonstrates how to set up a global authentication store using Pinia in Vue 3. It defines a store with state for login status, user data, and an auth token. Getters provide computed state, while actions handle login, logout, and initial authentication from local storage. The component then uses `useAuthStore()` to interact with the global state, allowing for easy access and modification of authentication details across the entire application.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs