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 for async authentication checks and implement multiple guard types for comprehensive route security.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What is JavaScript Array.pop() Method?
What is JavaScript Array.pop() Method?

How to set focus on an input field after rendering in React
How to set focus on an input field after rendering in React

CSS Selector for Parent Element
CSS Selector for Parent Element

The Wacky World of JavaScript: Unraveling the Oddities
The Wacky World of JavaScript: Unraveling the Oddities

Answers by CoreUI Core Team