How to logout a user in Angular
Proper user logout requires clearing authentication tokens, resetting application state, and redirecting to the login page. As the creator of CoreUI with 12 years of Angular development experience, I’ve implemented logout functionality for enterprise applications with strict security requirements.
The most secure approach combines token removal, state cleanup, and navigation in a single logout service method.
Create Logout Method
Update src/app/services/auth.service.ts:
import { Injectable } from '@angular/core'
import { Router } from '@angular/router'
import { BehaviorSubject, Observable } from 'rxjs'
interface User {
id: string
name: string
email: string
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
private currentUserSubject = new BehaviorSubject<User | null>(null)
public currentUser: Observable<User | null>
constructor(private router: Router) {
this.currentUser = this.currentUserSubject.asObservable()
this.loadUser()
}
logout(): void {
localStorage.removeItem('auth_token')
localStorage.removeItem('refresh_token')
localStorage.removeItem('user')
this.currentUserSubject.next(null)
this.router.navigate(['/login'])
}
private loadUser(): void {
const user = localStorage.getItem('user')
if (user) {
this.currentUserSubject.next(JSON.parse(user))
}
}
}
Logout Component
Create a logout button component:
import { Component } from '@angular/core'
import { AuthService } from '../../services/auth.service'
@Component({
selector: 'app-logout-button',
template: `
<button (click)="onLogout()" class="btn btn-danger">
Logout
</button>
`
})
export class LogoutButtonComponent {
constructor(private authService: AuthService) {}
onLogout(): void {
if (confirm('Are you sure you want to logout?')) {
this.authService.logout()
}
}
}
Logout with API Call
For server-side session invalidation:
import { HttpClient } from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private http: HttpClient,
private router: Router
) {}
logout(): void {
this.http.post('/api/auth/logout', {}).subscribe({
next: () => {
this.clearAuthData()
this.router.navigate(['/login'])
},
error: (error) => {
console.error('Logout failed:', error)
this.clearAuthData()
this.router.navigate(['/login'])
}
})
}
private clearAuthData(): void {
localStorage.removeItem('auth_token')
localStorage.removeItem('refresh_token')
localStorage.removeItem('user')
this.currentUserSubject.next(null)
}
}
Clear All Application State
Reset application-wide state on logout:
import { Injectable } from '@angular/core'
import { AuthService } from './auth.service'
import { CartService } from './cart.service'
import { NotificationService } from './notification.service'
@Injectable({
providedIn: 'root'
})
export class LogoutService {
constructor(
private authService: AuthService,
private cartService: CartService,
private notificationService: NotificationService,
private router: Router
) {}
async logout(): Promise<void> {
try {
await this.authService.logout()
this.cartService.clear()
this.notificationService.clear()
sessionStorage.clear()
localStorage.removeItem('preferences')
this.router.navigate(['/login'], {
queryParams: { loggedOut: true }
})
} catch (error) {
console.error('Logout error:', error)
}
}
}
Automatic Logout on Token Expiry
Add automatic logout when token expires:
import { Injectable } from '@angular/core'
import { Router } from '@angular/router'
@Injectable({
providedIn: 'root'
})
export class AuthService {
private logoutTimer?: any
constructor(private router: Router) {}
login(token: string, expiresIn: number): void {
localStorage.setItem('auth_token', token)
this.scheduleLogout(expiresIn)
}
logout(): void {
this.clearLogoutTimer()
localStorage.removeItem('auth_token')
localStorage.removeItem('user')
this.router.navigate(['/login'], {
queryParams: { reason: 'session-expired' }
})
}
private scheduleLogout(expiresIn: number): void {
this.clearLogoutTimer()
this.logoutTimer = setTimeout(() => {
this.logout()
}, expiresIn * 1000)
}
private clearLogoutTimer(): void {
if (this.logoutTimer) {
clearTimeout(this.logoutTimer)
this.logoutTimer = null
}
}
}
Logout Confirmation Dialog
Create a reusable logout dialog:
import { Component } from '@angular/core'
import { MatDialogRef } from '@angular/material/dialog'
@Component({
selector: 'app-logout-dialog',
template: `
<h2 mat-dialog-title>Confirm Logout</h2>
<mat-dialog-content>
Are you sure you want to logout?
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button (click)="onCancel()">Cancel</button>
<button mat-raised-button color="warn" (click)="onConfirm()">
Logout
</button>
</mat-dialog-actions>
`
})
export class LogoutDialogComponent {
constructor(private dialogRef: MatDialogRef<LogoutDialogComponent>) {}
onConfirm(): void {
this.dialogRef.close(true)
}
onCancel(): void {
this.dialogRef.close(false)
}
}
Use the dialog:
import { MatDialog } from '@angular/material/dialog'
@Component({
selector: 'app-header'
})
export class HeaderComponent {
constructor(
private dialog: MatDialog,
private authService: AuthService
) {}
openLogoutDialog(): void {
const dialogRef = this.dialog.open(LogoutDialogComponent)
dialogRef.afterClosed().subscribe(confirmed => {
if (confirmed) {
this.authService.logout()
}
})
}
}
Best Practice Note
This is the same logout pattern we use in CoreUI’s Angular admin templates. Always clear all authentication data, reset application state, and navigate to the login page. For added security, call a server endpoint to invalidate the session before clearing client-side tokens.
For production applications, consider using CoreUI’s Angular Admin Template which includes pre-built logout functionality with confirmation dialogs and automatic session timeout.
Related Articles
If you’re implementing authentication, you might also want to learn how to store tokens securely in Angular and how to refresh JWT tokens in Angular.



