AIAPIDate & TimeImageJSONMathNext.jsSecuritySEOTextDesignDatabase
All ToolsWorkspacesWorkflowsLearnError EncyclopediaAboutPrivacyTermsContactEmail

© 2026 Web Util Slyce. All tools run client-side — your data stays private.

How to Add Authentication in Vue.js

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.

Try JWT Generator

Overview

Authentication in Vue.js follows a pattern: user logs in, receives a JWT or session token, stores it (localStorage or cookies), attaches it to API requests via interceptors, and protects routes with navigation guards. Firebase Auth handles email/password, Google, GitHub, and other providers out of the box.

Prerequisites

  • A Vue.js project with Vue Router installed
  • A backend API with authentication endpoints (or Firebase project)
  • Understanding of JWT tokens and HTTP headers

Step-by-Step Instructions

1

Set up JWT authentication store

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') }, } })

2

Add axios interceptor for tokens

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

3

Protect routes with navigation guards

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() } })

4

Implement Firebase Auth

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)

Common Mistakes to Avoid

  • Storing JWT in localStorage without XSS protection — sanitize all user input to prevent XSS attacks
  • Not handling token expiration — check token expiry and redirect to login when expired
  • Storing plain text passwords — never handle passwords client-side, use the backend for hashing
  • Not using route guards on every protected route — leads to unauthorized access

Related Tools

JWT Generator JWT Decoder Password Generator URL Encode/Decode

Frequently Asked Questions

Should I store JWT in localStorage or cookies?

Cookies with httpOnly flag are more secure (prevents XSS access). localStorage is simpler but vulnerable to XSS. For production, use httpOnly cookies.

How do I refresh expired JWT tokens?

Implement a refresh token flow. Store a long-lived refresh token (httpOnly cookie) and use it to get new access tokens when the current one expires.