JAVASCRIPT

Centralized Authentication State with Pinia Store

Learn to manage global authentication state in Vue 3 applications using Pinia, Vue's official state management. Ensures reactive, centralized user data.

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

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    isAuthenticated: false,
    token: null,
  }),
  getters: {
    getUser: (state) => state.user,
    isLoggedIn: (state) => state.isAuthenticated,
  },
  actions: {
    login(userData, token) {
      this.user = userData;
      this.isAuthenticated = true;
      this.token = token;
      localStorage.setItem('user_token', token);
      // Potentially fetch user profile here
    },
    logout() {
      this.user = null;
      this.isAuthenticated = false;
      this.token = null;
      localStorage.removeItem('user_token');
    },
    initializeAuth() {
      const token = localStorage.getItem('user_token');
      if (token) {
        this.token = token;
        // In a real app, you'd validate the token and fetch user data
        this.isAuthenticated = true;
        this.user = { id: 1, name: 'Guest' }; 
      }
    }
  },
});

/*
// main.js (or equivalent setup)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
const pinia = createPinia();

app.use(pinia);
app.mount('#app');

// In a Vue Component (e.g., App.vue or a Login component):
<script setup>
import { onMounted } from 'vue';
import { useAuthStore } from './stores/auth';

const authStore = useAuthStore();

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

const handleLogin = () => {
    // Simulate login
    authStore.login({ id: 1, name: 'John Doe' }, 'some-jwt-token');
};

const handleLogout = () => {
    authStore.logout();
};
</script>

<template>
    <div>
        <p v-if="authStore.isLoggedIn">Welcome, {{ authStore.getUser?.name }}!</p>
        <p v-else>Please log in.</p>
        <button v-if="!authStore.isLoggedIn" @click="handleLogin">Login</button>
        <button v-else @click="handleLogout">Logout</button>
    </div>
</template>
*/
How it works: This snippet demonstrates setting up a Pinia store for authentication. It defines a `useAuthStore` with `state` for user data, `getters` to easily access properties, and `actions` for login/logout logic. It also shows how to initialize the store from `localStorage` on application load, ensuring persistent login states. Pinia is Vue 3's recommended state management solution, offering a simple and powerful API.

Need help integrating this into your project?

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

Hire DigitalCodeLabs