Full answer
Guards let the router allow or block a navigation. The main types:
canActivate: can this route be entered?canActivateChild: same, for child routes.canMatch: should this route even be considered? This also decides whether lazy code is loaded.canDeactivate: can the user leave this route (for example unsaved changes)?
Since Angular 15 guards are plain functions: const authGuard: CanActivateFn = (route, state) => { ... }. Inside you call inject(AuthService) and inject(Router), because a guard runs in an injection context. Class-based guards (implements CanActivate) were deprecated in Angular 15.2 and the interfaces are marked deprecated, although they still run.
Return values: true allows, false cancels, and a UrlTree redirects. Prefer returning router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }) to calling router.navigate() inside the guard. A returned UrlTree cancels the current navigation and starts the new one in a clean way, which avoids race conditions. Guards can also return an Observable or a Promise; the router uses the first emitted value.
Security point: anything running in the browser can be bypassed, so guards improve user experience by hiding pages. The server must still check permissions on every API call.
canDeactivate receives the component, so you can ask it whether the form is dirty. Reuse one guard function across routes, with route.data for options such as required roles.
// file: auth.service.ts
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthService {
readonly user = signal<{ name: string; role: 'student' | 'admin' } | null>(null);
}
// file: guards.ts
import { inject } from '@angular/core';
import { CanActivateFn, CanDeactivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
const user = auth.user();
const needed = route.data['role'] as string | undefined;
if (!user) {
return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
}
if (needed && user.role !== needed) {
return router.createUrlTree(['/forbidden']);
}
return true;
};
export interface HasUnsavedChanges {
isDirty(): boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) =>
!component.isDirty() || confirm('You have unsaved changes. Leave this page?');
// file: app.routes.ts
import { Component } from '@angular/core';
import { Routes } from '@angular/router';
import { authGuard, unsavedChangesGuard } from './guards';
import type { HasUnsavedChanges } from './guards';
@Component({ selector: 'app-admin', template: `<p>Admin</p>` })
export class AdminComponent {}
@Component({ selector: 'app-profile', template: `<p>Profile</p>` })
export class ProfileComponent implements HasUnsavedChanges {
isDirty(): boolean {
return false;
}
}
export const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [authGuard], data: { role: 'admin' } },
{ path: 'profile', component: ProfileComponent, canActivate: [authGuard], canDeactivate: [unsavedChangesGuard] },
];Angular 20.3. `AuthService` here uses a plain signal. In a real app it would check a token or call an API.
Key points
- Guards are functions with `inject()`. Class guards are deprecated.
- Return `true`, `false`, or a `UrlTree` (or an Observable or Promise of these).
- Redirect with `createUrlTree`, not `navigate`, inside the guard.
- Browser guards are not security. The API must enforce access.
Common mistakes
- Calling `router.navigate()` inside a guard and returning `true`, which can cause double navigation.
- Treating a guard as the only protection for sensitive data.
- Forgetting the guard runs on every navigation to that route, so slow synchronous checks hurt.
Follow-ups
- What is the difference between `canActivate` and `canMatch`?
- How would you pass the required role to a reusable guard?
- How do you wait for an async auth check inside a guard?
Tips
- Say "guards are UX, the server is security" without being asked. It is what a senior reviewer wants to hear.
- Mention UrlTree redirects. It is a detail many candidates miss.
- If asked about legacy, say class guards still work but are deprecated.
Evaluation rubric
- Writes a functional guard with inject.
- Redirects with UrlTree.
- States the security limit.