How to handle authentication in Vue

Handling authentication in Vue applications requires managing user state, protecting routes, and maintaining login sessions across page reloads. As the creator of CoreUI with extensive Vue development experience since 2014, I’ve implemented authentication systems in numerous production applications using modern Vue patterns. The most effective approach combines Pinia store for state management with Vue Router navigation guards for route protection. This pattern provides centralized authentication logic while ensuring secure access control throughout your application.

Create an authentication store with Pinia and combine it with router guards for complete authentication handling.

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

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token'),
    isAuthenticated: false
  }),

  actions: {
    async login(credentials) {
      try {
        const response = await fetch('/api/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(credentials)
        })
        const data = await response.json()

        this.token = data.token
        this.user = data.user
        this.isAuthenticated = true
        localStorage.setItem('token', data.token)

        router.push('/dashboard')
      } catch (error) {
        throw new Error('Login failed')
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      localStorage.removeItem('token')
      router.push('/login')
    },

    async checkAuth() {
      if (this.token) {
        // Verify token with server
        this.isAuthenticated = true
      }
    }
  }
})

// router/index.js
import { useAuthStore } from '@/stores/auth'

router.beforeEach((to, from) => {
  const authStore = useAuthStore()

  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return '/login'
  }
})

This code creates a Pinia authentication store that manages user state, tokens, and authentication status. The store provides login and logout actions that handle API communication and state updates. The router guard checks authentication status before accessing protected routes, automatically redirecting unauthenticated users to the login page.

Best Practice Note:

This is the authentication architecture we use in CoreUI Vue dashboard templates for secure user management. Consider implementing token refresh logic and secure HTTP-only cookies for enhanced security in production environments.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author