angular
/

Angular Route Guards – Securing Navigation

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

angular

Angular Route Guards – Securing Navigation

What are Route Guards?

Route guards are interfaces (or functions) that tell the Angular Router whether it should allow navigation to a requested route. As an Architect, you use guards to enforce business rules at the navigation level. For example, your Revochamp 'Admin' panel should only be accessible to users with an 'Admin' role, and the 'Editor' should warn users if they try to leave with unsaved code.

  1. Types of Route Guards

Angular provides several types of guards, each triggered at a different point in the routing lifecycle.

  • CanActivate: Determines if a user can visit a route (e.g., Is the user logged in?).
  • CanActivateChild: Determines if a user can visit the child routes of a protected parent.
  • CanDeactivate: Determines if a user can leave a route (e.g., 'Warning: Unsaved Changes').
  • CanMatch: Determines if a route can be matched at all (useful for choosing between two different components for the same path based on a flag).

  1. Implementing Functional Guards

In modern Angular (v15+), functional guards are the preferred standard over class-based guards. They are easier to write, test, and compose using Dependency Injection.

TypeScriptRead-only
1
// auth.guard.ts
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard = () => {
  const authService = inject(AuthService);
  const router = inject(Router);

  if (authService.isLoggedIn()) {
    return true;
  }

  // Redirect to login if not authenticated
  return router.parseUrl('/login');
};

  1. Registering Guards in Routes

You apply guards directly to your route configuration. You can provide an array of multiple guards; all must return true for navigation to proceed.

TypeScriptRead-only
1
// app.routes.ts
export const routes: Routes = [
  {
    path: 'admin',
    loadComponent: () => import('./admin/admin.component'),
    canActivate: [authGuard] // Guard applied here
  }
];

Guard Execution Flow

The router checks guards in a specific sequence before the component is even instantiated.

Guard TypePrimary Use CaseReturn Value
CanActivateAuthentication / Login checkboolean | UrlTree
CanDeactivatePrevent accidental data lossboolean | Promise<boolean>
CanMatchFeature flagging / Role-based routingboolean
CanActivateChildProtecting sub-menus/dashboardsboolean

Test Your Knowledge

Q1
of 3

Which guard type is used to prevent a user from accidentally navigating away from a form with unsaved changes?

A
CanActivate
B
CanDeactivate
C
CanMatch
D
CanLoad
Q2
of 3

What happens if a route guard returns 'false'?

A
The user is redirected to home
B
The application crashes
C
The navigation is cancelled and the user stays on the current page
D
The route is loaded but hidden
Q3
of 3

What is the benefit of functional guards over class-based guards?

A
They run faster in the browser
B
They require less boilerplate and are easier to use with the 'inject()' function
C
They are the only way to use the Router
D
They don't require TypeScript

Frequently Asked Questions

Can a guard return an Observable?

Yes. Guards can return a boolean, a UrlTree, a Promise, or an Observable. This is perfect for checking auth status against a backend API or a Firebase session.

What is a UrlTree return?

Instead of just returning 'false' (which cancels navigation), you can return a 'UrlTree' created by the router. This tells Angular to cancel the current navigation and immediately redirect the user to a different route (like /login).

Should I use Guards for Authorization?

Guards are great for UI-level security, but as a Lead, remember: Never rely on frontend guards alone. Always verify permissions on your Python/FastAPI backend, as frontend code can be bypassed by a determined user.

Previous

angular routing

Next

angular lazy loading

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.