Auth Guard Protect routes with guards.

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access


*Enrollment provides full access to this course (and updates) for life.

Use a router guard to protect routes from unauthorized users and show a snackbar error message.


Step 1 - Generate the Guard

command line
ng g guard user/auth

file_type_ng_component_ts auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { SnackService } from '../services/snack.service';

  providedIn: 'root'
export class AuthGuard implements CanActivate {
    private afAuth: AngularFireAuth,
    private snack: SnackService
  ) {}

  async canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {

    const user = await this.afAuth.currentUser;
    const isLoggedIn = !!user;
    if (!isLoggedIn) {
    return isLoggedIn;

Step 2 - Show a SnackBar

Generate a global service that can be used to show snack bar message from any component.

command line
ng g service services/snack

file_type_ng_component_ts snack.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
import { tap } from 'rxjs/operators';

  providedIn: 'root'
export class SnackService {
  constructor(private snackBar: MatSnackBar, private router: Router) {}

  authError() {'You must be logged in!', 'OK', {
      duration: 5000

    return this.snackBar._openedSnackBarRef
        tap(_ =>


Ask questions via GitHub below OR chat on Slack #questions