Route Guards - Create Secure Routes in Angular

Route guards in an Angular application facilitates to block a particular route based on user authentication or on some extra permissions. In this blog, we will implement route guards in Angular.
Let's suppose that dashboard page in Angular application can not be accessed until a valid user is logged in. If someone is trying to access dashboard page directly without providing valid user credentials, in this condition we can use route guard to block that url and then redirect that user to some other page.
Route Guard in Angular offers 2 methods canActivate() and canDecativate().
Most of the time canActivate() method is used to block a route in an application.

Creating Route Guards in Angular application

1. In this demo, I have created 2 components with name- dashboard and unauthorize

2. Next, I have created a route guard with below command -

ng g g /guard/userguard
It will create 2 files

CREATE src/app/guard/userguard.guard.spec.ts
CREATE src/app/guard/userguard.guard.ts

3. Then, import guard name in app.module.ts file

import {UserguardGuard} from './guard/userguard.guard';

and add it to provider -

providers: [UserguardGuard],

4. Next, import this guard in app-routing.module.ts file

5. Now, define the route with route guard in app-routing.module.ts file-


Above route says, DashboardComponent can only be displayed if canActivate method of Userguard returns true.

6. In our final step we will modify the Userguard.ts file

I have assigned a value to user i.e. user's email id. That can be fetched from an API.
Then check the value for user, if it is matches the record then return true else navigate to access denied page and return false.
First create a property of type Router in constructor, then write logic in canActivate() method.

export class UserguardGuard implements CanActivate {
constructor(private _router:Router){}
user = "";
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(this.user == "")
return true;
return false;

Hope you like this blog.
Please share this blog on social media and give your feedback in comment box below.

You may like other blogs -

Interview Questions and Answers Series -

MVC Interview Questions and Answers
Web API interview questions and answers

Keep following - SharePointCafe.Net



What is Web API? When should we use in our projects?