How to create a route guard in Angular
Route guards provide essential security and navigation control in Angular applications by intercepting route changes and enforcing access rules. As the creator of CoreUI with extensive Angular development experience since 2014, I’ve implemented route guards in numerous enterprise applications for authentication and authorization. The most common approach is creating a CanActivate guard that returns a boolean to allow or deny route access. This pattern enables centralized route protection while maintaining clean separation between authentication logic and components.
Create a CanActivate guard service that implements the CanActivate interface to control route access.
import { Injectable } from '@angular/core'
import { CanActivate, Router } from '@angular/router'
import { AuthService } from './auth.service'
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true
} else {
this.router.navigate(['/login'])
return false
}
}
}
This guard checks if the user is authenticated through an AuthService. If logged in, it returns true to allow route access. If not authenticated, it redirects to the login page and returns false to block access. Apply this guard to routes in your routing configuration using the canActivate property to protect specific routes from unauthorized access.
Best Practice Note:
This is the security pattern we implement in CoreUI Pro admin templates for robust route protection.
Consider returning an Observable



