Sub topic 11
Protecting Routes with Functional Guards
Some routes should not open for every user in every situation. An admin panel needs an admin. A dashboard needs a signed-in user. A form with unsaved edits should not vanish because someone clicked the wrong link. The Angular Router handles these cases with guards. A guard is a function that the router calls during navigation, and its return value decides whether the navigation continues, stops, or goes somewhere else.
This chapter assumes you know TypeScript, standalone components, inject(), Angular services, and basic RxJS. It also assumes you have read the earlier chapters on route configuration, child routes, lazy loading, and programmatic navigation.
The guard types and when each runs
Modern Angular writes guards as plain functions. The older class-based CanActivate interfaces are deprecated, and CanLoad has been replaced by CanMatch. Each guard type has a typed function signature:
| Guard type | Route property | Question it answers | Receives |
|---|---|---|---|
| `CanMatchFn` | `canMatch` | Should this route definition be considered at all? | `Route`, `UrlSegment[]` |
| `CanActivateFn` | `canActivate` | May the user enter this route? | `ActivatedRouteSnapshot`, `RouterStateSnapshot` |
| `CanActivateChildFn` | `canActivateChild` | May the user enter any child of this route? | child `ActivatedRouteSnapshot`, `RouterStateSnapshot` |
| `CanDeactivateFn<T>` | `canDeactivate` | May the user leave this component? | component instance, current route, current state, next state |
Every guard returns a MaybeAsync<GuardResult>. That means a plain value, a Promise, or an Observable of one of these:
true: continue navigating.false: cancel navigation. The URL stays where it was.- A
UrlTree: cancel this navigation and start a new one to that URL. - A
RedirectCommand(Angular 18 and later): like aUrlTree, with extra navigation options such asskipLocationChange.
The order matters. canMatch runs while the router is still choosing a route, before any lazy code loads. The router checks canDeactivate before any activation guard, so leaving the current page is settled first. Resolvers run only after every guard has passed.
A canActivate guard with a return URL
Here is a guard that lets signed-in users through. Other users go to the login page, and the guard records where they were heading.
// auth.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthService {
private user: { name: string; roles: string[] } | null = null;
isLoggedIn(): boolean {
return this.user !== null;
}
hasRole(role: string): boolean {
return this.user?.roles.includes(role) ?? false;
}
checkSession(): Observable<boolean> {
// Replace with an HTTP call to your backend.
return of(this.user !== null);
}
login(name: string, roles: string[]): void {
this.user = { name, roles };
}
}// 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 auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url }
});
};state.url holds the full URL the user tried to reach, including query parameters. After login, the login component can call router.navigateByUrl(returnUrl).
The router calls guards inside an injection context. That is why inject() works at the top of the function body. It does not work inside a setTimeout or a subscribe callback, because those run later and outside that context.
Async guards
When the answer depends on a server, return an Observable. The router uses the first value the Observable emits and ignores the rest.
// session.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { catchError, map, of } from 'rxjs';
import { AuthService } from './auth.service';
export const sessionGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.checkSession().pipe(
map(valid => (valid ? true : router.createUrlTree(['/login']))),
catchError(() => of(router.createUrlTree(['/login'])))
);
};The catchError is important. If the Observable errors, the navigation fails with an error instead of redirecting. If it never emits, the navigation hangs and nothing on screen changes.
canMatch: guarding lazy code and choosing between routes
canActivate on a lazy route still lets the router download the chunk before it rejects the user. canMatch runs during matching, so a rejected user never downloads the code. A false result also has a second effect: the router treats the route as if it did not exist and moves on to the next definition with the same path.
A guard factory lets you pass parameters such as a role name:
// role.guard.ts
import { inject } from '@angular/core';
import { CanMatchFn } from '@angular/router';
import { AuthService } from './auth.service';
export function roleGuard(role: string): CanMatchFn {
return () => inject(AuthService).hasRole(role);
}The outer function runs once, when the routes array is built. The inner function runs on each navigation, inside an injection context, so inject() is safe there.
Because a false from canMatch falls through, you can serve different components on the same path:
// app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { roleGuard } from './role.guard';
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [roleGuard('admin')],
loadComponent: () =>
import('./admin-dashboard.component').then(m => m.AdminDashboardComponent)
},
{
path: 'dashboard',
canActivate: [authGuard],
loadComponent: () =>
import('./user-dashboard.component').then(m => m.UserDashboardComponent)
},
{
path: 'admin',
canMatch: [roleGuard('admin')],
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
},
{
path: 'login',
loadComponent: () => import('./login.component').then(m => m.LoginComponent)
},
{ path: '**', loadComponent: () => import('./not-found.component').then(m => m.NotFoundComponent) }
];A non-admin who visits /admin falls through to the wildcard and sees the not-found page. That hides the admin section entirely. If you would rather send them to a "forbidden" page, return a UrlTree from the guard.
canActivateChild: one guard for a whole section
When a parent route has many children, canActivateChild on the parent runs before each child activates. It also runs when the user moves between siblings, which canActivate on the parent does not do, because the parent stays active.
import { Routes } from '@angular/router';
import { CanActivateChildFn } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from '../auth.service';
import { SettingsLayoutComponent } from './settings-layout.component';
import { ProfileComponent } from './profile.component';
import { BillingComponent } from './billing.component';
export const settingsChildGuard: CanActivateChildFn = () =>
inject(AuthService).isLoggedIn();
export const SETTINGS_ROUTES: Routes = [
{
path: '',
component: SettingsLayoutComponent,
canActivateChild: [settingsChildGuard],
children: [
{ path: 'profile', component: ProfileComponent },
{ path: 'billing', component: BillingComponent }
]
}
];canDeactivate: protecting unsaved work
CanDeactivateFn<T> receives the component instance being left. Type it against an interface, not a concrete class, and one guard can then serve every form in the app.
// unsaved-changes.guard.ts
import { CanDeactivateFn } from '@angular/router';
export interface HasUnsavedChanges {
hasUnsavedChanges(): boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = component =>
component.hasUnsavedChanges()
? confirm('You have unsaved changes. Leave anyway?')
: true;// edit-profile.component.ts
import { Component } from '@angular/core';
import { HasUnsavedChanges } from './unsaved-changes.guard';
@Component({
selector: 'app-edit-profile',
standalone: true,
template: `<input (input)="dirty = true" placeholder="Display name" />`
})
export class EditProfileComponent implements HasUnsavedChanges {
dirty = false;
hasUnsavedChanges(): boolean {
return this.dirty;
}
}
// Route: { path: 'edit', component: EditProfileComponent, canDeactivate: [unsavedChangesGuard] }canDeactivate only covers navigation inside the router. Closing the tab, refreshing, or typing a new address in the browser bypasses it. To cover those cases, add a beforeunload listener as well.
Common errors and gotchas
- Guards are not security. All the code runs in the browser, so anyone can edit it or skip it. Guards shape the user experience. The server must still authorize every API request.
- Redirect loops. If
authGuardprotects/logintoo, an unauthenticated user gets redirected forever. Keep redirect targets unguarded, or make sure they pass for the user being redirected. - Guards do not re-run on every change. The default
runGuardsAndResolvers: 'paramsChange're-runs guards when path or matrix parameters change, not when only query parameters change. Set it to'paramsOrQueryParamsChange'or'always'if your logic reads query parameters. - Multiple guards in one array run together. If several return
UrlTrees, the router uses the one from the highest-priority guard, which is the earliest in the array. Don't rely on side effects running in order. - Calling
inject()too late. Call it synchronously at the top of the guard, not insidepipecallbacks that run later.
Exercise
An /reports route uses loadChildren and canActivate: [roleGuard]. Users without the role are blocked, but the network tab shows the reports chunk downloading anyway. Why, and what is the fix?
Show answer
canActivate runs after route matching, and matching a loadChildren route loads its code. Switch to a CanMatchFn on canMatch. It runs during matching, so the chunk never loads for users who fail the check.
Exercise
Write a CanActivateFn named featureFlagGuard that injects a FlagService with a method isEnabled(name: string): Observable<boolean>, allows navigation when the flag 'beta' is enabled, and otherwise redirects to /home. It must also redirect to /home if the service errors.
Show answer
export const featureFlagGuard: CanActivateFn = () => { const flags = inject(FlagService); const router = inject(Router); return flags.isEnabled('beta').pipe(map(on => on ? true : router.createUrlTree(['/home'])), catchError(() => of(router.createUrlTree(['/home'])))); }; Both inject calls happen synchronously at the top, and the UrlTree makes the router perform the redirect.
Exercise
A settings section has canActivate: [authGuard] on its parent route. A user signs out in another tab, then clicks from /settings/profile to /settings/billing, and the billing page still opens. Why?
Show answer
The parent route stays active when the user moves between its children, so its canActivate guard does not run again. Put the check in canActivateChild on the parent. That guard runs every time a child activates.