How to log out a user in Vue
Implementing secure user logout in Vue applications requires complete session cleanup to prevent unauthorized access and security vulnerabilities. As the creator of CoreUI with extensive Vue development experience since 2014, I’ve implemented logout functionality in numerous production applications with enterprise security requirements. The most secure approach clears all authentication data, invalidates server sessions, and redirects users to appropriate pages. This pattern ensures complete session termination while providing clear feedback to users about their authentication state.
Use Pinia store to clear authentication data, notify the server, and redirect users for complete logout functionality.
// stores/auth.js
import { defineStore } from 'pinia'
import { router } from '@/router'
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false
}),
actions: {
async logout() {
try {
// Notify server to invalidate tokens
if (this.refreshToken) {
await fetch('/api/auth/logout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.accessToken}`
},
body: JSON.stringify({ refreshToken: this.refreshToken })
})
}
} catch (error) {
console.error('Logout error:', error)
// Continue with client-side cleanup even if server request fails
} finally {
this.clearAuthData()
this.redirectToLogin()
}
},
clearAuthData() {
// Clear store state
this.user = null
this.accessToken = null
this.refreshToken = null
this.isAuthenticated = false
// Clear local storage
localStorage.removeItem('refreshToken')
localStorage.removeItem('user')
// Clear session storage
sessionStorage.clear()
// Clear cookies if using cookie-based auth
document.cookie = 'auth=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
},
redirectToLogin() {
// Redirect to login page
router.push('/login')
}
}
})
// In component
<template>
<div>
<button @click="handleLogout" class="logout-btn">
Logout
</button>
</div>
</template>
<script setup>
import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore()
const handleLogout = async () => {
try {
await authStore.logout()
} catch (error) {
console.error('Logout failed:', error)
}
}
</script>
This code implements comprehensive logout functionality that clears both client-side and server-side authentication data. The logout action notifies the server to invalidate tokens, clears all local authentication data including localStorage and sessionStorage, and redirects users to the login page. Error handling ensures cleanup continues even if server communication fails.
Best Practice Note:
This is the secure logout implementation we use in CoreUI Vue applications for complete session termination. Always clear all authentication data sources and consider implementing logout confirmation dialogs for better user experience in enterprise applications.



