Chapter 6.5โ˜• 16 min read

Route Guards

Functions that decide if a route can be activated, deactivated, or even matched. Protect your routes.

01What are Route Guards

Route guards are functions that decide if a route can be activated, deactivated, or matched. They run BEFORE the route component loads.

"Guard = security guard at Charminar โ€” ticket hai toh andar, nahi toh bahar."

Common use cases:

  • Authentication โ€” is the user logged in?
  • Authorization โ€” does the user have the right role?
  • Unsaved changes โ€” warn before leaving a form
  • Conditional matching โ€” show different route versions based on role

In modern Angular, guards are plain FUNCTIONS (not classes). This is the functional guard pattern.

02canActivate โ€” Can User Enter

canActivate protects a route from unauthorized access. It runs when the user tries to ENTER the route.

// auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);

  if (authService.isLoggedIn()) {
    return true;  // Allow access
  }

  // Redirect to login page
  return router.createUrlTree(['/login']);
};
// Route config
{ path: 'admin', component: AdminComponent,
  canActivate: [authGuard] }

"canActivate = entry gate โ€” login kiya toh andar, nahi toh login page pe bhejo."

Return true to allow, UrlTree to redirect, or false to block (shows blank). ALWAYS prefer UrlTree over false for better UX.

03canDeactivate โ€” Can User Leave

canDeactivate warns the user before leaving a route โ€” essential for forms with unsaved changes.

// unsaved.guard.ts
import { CanDeactivateFn } from '@angular/router';
import { EditComponent } from './edit.component';

export const unsavedGuard: CanDeactivateFn = (component) => {
  if (component.form.dirty && !component.saved) {
    return confirm('You have unsaved changes! Leave anyway?');
  }
  return true;
};
// Route config
{ path: 'edit/:id', component: EditComponent,
  canDeactivate: [unsavedGuard] }

"canDeactivate = exit gate โ€” form bhara hai le save nahi kiya, pakka jaana hai?"

The guard receives the component instance, so it can check the component's state. It can return boolean or Observable for async checks like auto-save.

04canMatch โ€” Can Route Even Match

canMatch runs BEFORE the route even matches. It decides if this route should be in the list of possible routes at all.

// role.guard.ts
import { CanMatchFn } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';

export const adminMatchGuard: CanMatchFn = () => {
  const authService = inject(AuthService);
  return authService.isAdmin();  // If false, this route doesn't exist
};
// Route config
{ path: 'dashboard', component: DashboardComponent,
  canMatch: [adminMatchGuard] }

"canMatch = bouncer outside club โ€” pehle check, phir andar jaane ka socho."

Key difference from canActivate: canMatch can prevent the route from even being considered. This is useful for lazy loaded routes โ€” if canMatch fails, the lazy chunk is NEVER downloaded. canActivate would download the chunk THEN block access.

05Combining Multiple Guards

You can combine multiple guards on the same route. All must return true for the route to activate.

{ path: 'admin',
  canActivate: [authGuard, adminGuard],   // Both must pass
  canDeactivate: [unsavedGuard],           // Leave protection
  canMatch: [featureFlagGuard]             // Route matching
}

"Multiple guards = multiple checkpoints โ€” har gate pe check."

Execution order: canMatch (first) โ†’ canActivate โ†’ Component loads โ†’ canDeactivate (on leave).

canMatch guards run in order โ€” if any returns false, later canMatch guards don't run and the route is skipped entirely. canActivate guards also run in order โ€” first failure stops the chain.

Key Takeaways

  • โœ… Guards are functions that control route access โ€” canActivate, canDeactivate, canMatch
  • โœ… canActivate runs on entry: return true to allow, UrlTree to redirect
  • โœ… canDeactivate runs on exit: warn about unsaved changes before leaving
  • โœ… canMatch runs before route matching: if false, route is skipped entirely (won't download lazy chunk)
  • โœ… Multiple guards run in order โ€” first failure stops the chain
Course Search
Search across all chapters & stages
๐Ÿ“–

Search the course

Type any topic โ€” branching, stash, rebase, hooks โ€” and jump straight to that chapter.

merge branchesgit stashundo commitrebase