Angular have a built in feature to protect access to routes and is very simple to use. This can be done by using guard which gives you a lot of flexibility to define your own rules for accessing specific route paths.

 

So, let's say we want to protect access to dashboard for only logged in users, and if they are not logged in they will be redirected to home page.

How to do it?

It can be done in 3 simple steps:

Step 1 - Create guard instance
Type this command to generate guard:

                    ng g g Auth
                  

this command translates to: ng generate guard named Auth

You will be asked which interface to use, please select CanActivate

                     Which interfaces would you like to implement? (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ CanActivate
 ◯ CanActivateChild
 ◯ CanDeactivate
 ◯ CanLoad

                  

 

Step 2 - Define your rule inside of guard

Open newly created auth.guard.ts and inside of  canActivate  method defined your rule:

                    canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    if( this.authService.isLoggedIn){
       return true;
    }else{
       return false;
     }

}
                  

 

Step 3 - use this guard on your route

Open your app-routing.module.ts where you have defined all of your routes, find the route which you want to protect and add your guard as one of the options. In our case we will protect dashboard route:

                    {
    path: 'dashboard',
    canActivate: [AuthGuard],
    loadChildren: () => import('./Components/Dashboard/dashboard-home/dashboard-home.module').then(
      m => m.DashboardHomeModule
    )

  }
                  

 

And your route is protected! You can read more about CanActivate guard on official Angular documentation:

 https://angular.io/api/router/CanActivate

 

Ofcourse you can tweak it a little bit, you have noticed that we are using external authService to get information is the use logged in or not. This can be injected into the guard by using constructor. Here is how your auth.guard should look like

                    import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
import {authService} from './Services/auth.service';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: authService

  ){

  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

      if( this.authService.isLoggedIn){
         return true;
      }else{
         return false;
       }
    

    }
  }
}

                  

 

And now let's add one more feature, we want to redirect user to home page if he is not logged in.

To do that, let's add Router to constructor and use it if user is not logged in:

                    constructor(
    public authService: authService,
    private router: Router,

  ){

                  

redirect to home page:

                    canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      if( this.authService.isLoggedIn){
         return true;
      }else{
          this.router.navigate(['']).then(() => {
            console.log('redirected from the guard');         
          });
       }
    }
}
                  

 

And that's it!

Easy peasy lemon squeezy 🍋