Vue.js authentication typically uses JWT stored in localStorage with axios interceptors for attaching tokens. Vue Router navigation guards protect routes. Firebase Auth provides a complete auth solution with social login.
Use Pinia to manage auth state. // stores/auth.js import { defineStore } from 'pinia' import axios from 'axios' export const useAuthStore = defineStore('auth', { state: () => ({ user: null, token: localStorage.getItem('token'), }), getters: { isAuthenticated: (state) => !!state.token, }, actions: { async login(email, password) { const { data } = await axios.post('/api/auth/login', { email, password }) this.token = data.token this.user = data.user localStorage.setItem('token', data.token) }, logout() { this.token = null this.user = null localStorage.removeItem('token') }, } })
Automatically attach the JWT to every API request. // utils/axios.js import axios from 'axios' const api = axios.create({ baseURL: import.meta.env.VITE_API_URL }) api.interceptors.request.use((config) => { const token = localStorage.getItem('token') if (token) { config.headers.Authorization = `Bearer ${token}` } return config }) api.interceptors.response.use( (res) => res, (err) => { if (err.response?.status === 401) { localStorage.removeItem('token') window.location.href = '/login' } return Promise.reject(err) } ) export default api
Use Vue Router's beforeEach guard to check authentication. // router/index.js import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/login', component: () => import('../views/Login.vue'), meta: { guest: true } }, { path: '/dashboard', component: () => import('../views/Dashboard.vue'), meta: { requiresAuth: true } }, ] const router = createRouter({ history: createWebHistory(), routes }) router.beforeEach((to, from, next) => { const token = localStorage.getItem('token') if (to.meta.requiresAuth && !token) { next('/login') } else if (to.meta.guest && token) { next('/dashboard') } else { next() } })
For a complete auth solution without a backend, use Firebase. npm install firebase // utils/firebase.js import { initializeApp } from 'firebase/app' import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut } from 'firebase/auth' const firebaseConfig = { /* your config */ } const app = initializeApp(firebaseConfig) export const auth = getAuth(app) // In component: import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth' const provider = new GoogleAuthProvider() await signInWithPopup(auth, provider)