Skip to content

Route Guards

A route guard is a function the router calls to decide whether a navigation may proceed. Guards are the mechanism behind “you must sign in to see this,” “you have unsaved changes,” and “this feature is behind a flag.”

They are functions, not classes. Class-based guards (implements CanActivate) are the legacy form; everything below uses the functional API, which is what ng generate guard produces and what works with inject().

For where guards sit in the navigation pipeline, see Angular Routing in Depth. This page is the reference for writing them.

Guard Signature type Fires Returning false
canMatch CanMatchFn During URL matching Falls through to the next matching route
canActivate CanActivateFn Entering a route Cancels the navigation
canActivateChild CanActivateChildFn Entering any descendant of a route Cancels the navigation
canDeactivate CanDeactivateFn<T> Leaving a route Cancels the navigation

canMatch’s fall-through behaviour is the one genuine difference in semantics, and it is the reason to prefer it for anything gating a lazy route.

Every guard may return:

  • boolean — allow or block.
  • UrlTree or RedirectCommand — redirect instead of blocking.
  • Promise<T> or Observable<T> of either — the router takes the first emitted value and unsubscribes.

That last point matters. A guard returning a long-lived observable (a BehaviorSubject of auth state, say) is used once and dropped. Do not expect later emissions to re-run the guard.

export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isAuthenticated()) {
return true;
}
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};

Never return false and then call router.navigate(). The two operations race, and browser history ends up holding the blocked URL — press Back and the user is bounced again, sometimes into a loop. Returning a UrlTree makes the redirect part of the same navigation, so history stays correct.

RedirectCommand is the richer form when you need navigation options on the redirect:

return new RedirectCommand(router.parseUrl('/login'), { skipLocationChange: true });
export const permissionGuard: CanActivateFn = (route) => {
const permissions = inject(PermissionService);
const router = inject(Router);
const required = route.data['permission'] as string;
return permissions.check(required).pipe(
map((allowed) => allowed || router.createUrlTree(['/forbidden'])),
catchError(() => of(router.createUrlTree(['/error']))),
);
};

Two things this shows:

  • Read configuration from route.data so one guard serves many routes: { path: 'admin', canActivate: [permissionGuard], data: { permission: 'admin:read' } }.
  • Catch errors. An unhandled rejection surfaces as NavigationError, and to the user that looks like a link that does nothing.

Guards block navigation while they run, exactly as resolvers do. A guard making a network call on every navigation is a latency tax on the whole application — cache the answer.

Guards are arrays, evaluated in order:

{
path: 'admin/settings',
component: AdminSettings,
canActivate: [authGuard, adminGuard],
canDeactivate: [unsavedChangesGuard],
}

Order them cheapest-first: a synchronous authentication check before an asynchronous permission lookup means the common rejection never makes a request.

canActivateChild on a parent protects every descendant with one declaration — and note that it fires once per level, so a two-level nesting evaluates it twice per navigation. Keep it cheap.

{
path: 'users', // /users itself is NOT protected
canActivateChild: [authGuard],
children: [
{ path: 'list', component: UserList }, // protected
{ path: ':id', component: UserDetail }, // protected
],
}

Type the guard against a capability interface rather than a concrete component, so one guard covers every editable screen:

export interface HasUnsavedChanges {
hasUnsavedChanges(): boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) => {
if (!component.hasUnsavedChanges()) {
return true;
}
return inject(ConfirmDialog).ask('Discard unsaved changes?');
};

Returning an Observable<boolean> from a dialog service is the realistic form; window.confirm() blocks the main thread and cannot be styled or tested well.

One limitation worth knowing: canDeactivate only covers in-application navigation. Closing the tab or typing a new URL bypasses it entirely — that needs a beforeunload listener, which browsers restrict to a generic, uncustomisable prompt.

Because rejection falls through, the same path can resolve to different components:

const routes: Routes = [
{ path: 'dashboard', component: AdminDashboard, canMatch: [isAdmin] },
{ path: 'dashboard', component: UserDashboard },
];

And for a lazy route, canMatch refuses before the chunk is fetched:

{
path: 'admin',
canMatch: [isAdmin],
loadChildren: () => import('./admin/admin.routes').then((m) => m.adminRoutes),
}

With canActivate instead, the browser downloads the admin bundle and then refuses. Same user-visible outcome, wasted bandwidth.

Angular’s own documentation opens the guards page with this, and it is the most important sentence on it: never rely on client-side guards as the sole source of access control. All JavaScript that runs in a browser can be modified by the person running the browser.

Concretely:

  • A guard can be bypassed by editing the running code in DevTools.
  • A lazy chunk gated by canMatch is still a file on your origin that anyone can request directly.
  • Any data the client already fetched is in memory and readable regardless of what is rendered.

Guards make the application behave sensibly for legitimate users. Authorisation is enforced by the server, on every request, without exception. Treat a guard as a routing concern, and never as the thing standing between an attacker and your data.

Guards are plain functions, so they test without a router, a fixture, or change detection — you only need an injection context:

describe('authGuard', () => {
function run(isAuthenticated: boolean) {
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{ provide: AuthService, useValue: { isAuthenticated: () => isAuthenticated } },
],
});
return TestBed.runInInjectionContext(() =>
authGuard({} as ActivatedRouteSnapshot, { url: '/orders' } as RouterStateSnapshot),
);
}
it('allows authenticated users', () => {
expect(run(true)).toBe(true);
});
it('redirects anonymous users to login with a returnUrl', () => {
const result = run(false) as UrlTree;
expect(result.toString()).toContain('/login');
expect(result.queryParams['returnUrl']).toBe('/orders');
});
});

Cast a minimal object to ActivatedRouteSnapshot rather than constructing a real one — the guard only reads the fields it reads, and a hand-built snapshot is noise.

Mistake Consequence Fix
return false then router.navigate() Corrupted history, redirect loops Return a UrlTree
Guard as the security model The data is not protected at all Enforce authorisation server-side
Network call in canActivateChild Runs per nesting level, per navigation Cache, or move to canActivate on the parent
canActivate on a gated lazy route Chunk downloads, then access is refused Use canMatch
No catchError on an async guard NavigationError; the link appears dead Catch and redirect to an error route
Expecting later observable emissions to re-run the guard Only the first value is used Re-navigate, or use withRouterConfig({ onSameUrlNavigation: 'reload' })
inject() after an await in the guard NG0203 Inject at the top of the function body
Duplicating the same guard on every child Drift as routes are added canActivateChild on the parent