Modern Routing in Angular: Functional Route Guards (canActivateFn)
Functional Route Guards: Replace heavy guard classes with single-purpose, composable functions (canActivateFn).
Functional Route Guards: Replace heavy guard classes with single-purpose, composable functions (canActivateFn).
In legacy Angular, protecting a route felt like writing an entire subsystem. You had to generate a class decorated with @Injectable(), implement interfaces like CanActivate or CanDeactivate, write a bulky constructor to inject services, and wire everything through an NgModule or provider array.
Angular phased out class-based guards in favor of Functional Route Guards. A route guard is no longer a rigid class artifact—it is simply a plain TypeScript function typed with signatures like canActivateFn.
Because functional guards execute inside Angular's reactive Injection Context, you can inject dependencies directly with inject() inside the function body, cutting boilerplate while making guards composable and clean.
| Aspect | Legacy Class Guard (CanActivate) | Modern Functional Guard (CanActivateFn) | | --- | --- | --- | | Structure | @Injectable() class implementing an interface | Plain, exportable function | | Dependency Injection | Constructor parameter ladder | Direct inject() calls inside the body | | File Overhead | 20–30 lines of framework ceremony | 5–10 lines of direct logic | | Parameterization | Awkward route data dictionary hacks | Clean higher-order factory functions | | Testing | Requires configuring TestBed with mocked DI | Call it like any standard JavaScript function |
A functional guard receives two parameters:
It can return a synchronous or asynchronous value resolving to:
type CanActivateFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) =>
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree;
Instead of scaffolding a class, define and export an arrow function:
// src/app/core/guards/auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated()) {
return true;
}
// Redirect unauthenticated users and preserve the intended destination
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url }
});
};
Pass the function directly into the route configuration's canActivate array:
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './core/guards/auth.guard';
export const routes: Routes = [
{
path: 'dashboard',
canActivate: [authGuard],
loadComponent: () => import('./features/dashboard/dashboard.component')
.then(m => m.DashboardComponent)
}
];
When authentication status requires an API call, token refresh, or reading an asynchronous stream, return an RxJS Observable.
// src/app/core/guards/async-auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map, take } from 'rxjs';
import { UserService } from '../services/user.service';
export const asyncAuthGuard: CanActivateFn = (route, state) => {
const userService = inject(UserService);
const router = inject(Router);
return userService.currentUser$.pipe(
take(1),
map(user => {
if (user) {
return true;
}
return router.createUrlTree(['/unauthorized']);
})
);
};
In older Angular versions, checking roles (like ADMIN or MANAGER) meant dumping strings into a route's data: { role: 'ADMIN' } object and reading them out of the snapshot.
Functional guards eliminate this via Higher-Order Functions:
// src/app/core/guards/role.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
// Factory function accepting arguments and returning a ready CanActivateFn
export function hasRole(requiredRole: string): CanActivateFn {
return (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
const user = authService.currentUser(); // Signal or state accessor
if (user?.role === requiredRole) {
return true;
}
return router.createUrlTree(['/forbidden']);
};
}
Now call the factory directly inside your route declarations:
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './core/guards/auth.guard';
import { hasRole } from './core/guards/role.guard';
export const routes: Routes = [
{
path: 'admin',
// Evaluated in sequence: must be authenticated, then must have ADMIN role
canActivate: [authGuard, hasRole('ADMIN')],
loadComponent: () => import('./features/admin/admin.component')
.then(m => m.AdminComponent)
},
{
path: 'reports',
canActivate: [authGuard, hasRole('MANAGER')],
loadComponent: () => import('./features/reports/reports.component')
.then(m => m.ReportsComponent)
}
];
canActivateFn is just one member of Angular's functional routing toolkit:
| Guard Type | Signature | Primary Purpose | | --- | --- | --- | | canActivateFn | (route, state) => ... | Verifies whether a user can enter a route. | | canDeactivateFn | (component, currentRoute, currentState, nextState) => ... | Prevents accidental navigation away (e.g., unsaved changes). | | canMatchFn | (route, segments) => ... | Determines whether the route should match at all. | | canActivateChildFn | (childRoute, state) => ... | Secures all nested children under a parent route branch. |
// src/app/core/guards/pending-changes.guard.ts
import { CanDeactivateFn } from '@angular/router';
export interface HasUnsavedChanges {
hasUnsavedChanges: () => boolean;
}
export const pendingChangesGuard: CanDeactivateFn<HasUnsavedChanges> = (component) => {
if (component.hasUnsavedChanges()) {
return confirm('You have unsaved changes. Do you really want to leave?');
}
return true;
};
Example: canMatchFn for Feature Flags & A/B Testing
Unlike canActivate (which halts navigation or forces a redirect), canMatch determines if Angular should even register the route. If it returns false, Angular skips that config entry and keeps searching down the routes table for the next match:
// src/app/core/guards/feature-flag.guard.ts
import { inject } from '@angular/core';
import { CanMatchFn } from '@angular/router';
import { FeatureFlagService } from '../services/feature-flag.service';
export function featureFlagGuard(flagName: string): CanMatchFn {
return () => {
const flags = inject(FeatureFlagService);
return flags.isEnabled(flagName);
};
}
// src/app/app.routes.ts
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [featureFlagGuard('new_dashboard_v2')],
loadComponent: () => import('./dashboard-v2.component').then(m => m.DashboardV2Component)
},
{
path: 'dashboard',
// Fallback: If the flag is disabled, Angular hits this route definition instead
loadComponent: () => import('./dashboard-v1.component').then(m => m.DashboardV1Component)
}
];
Because guards are plain JavaScript functions, you don't always need to string them together as separate items in the router array. You can compose them directly inside higher-level guard definitions:
import { CanActivateFn } from '@angular/router';
import { authGuard } from './auth.guard';
import { hasRole } from './role.guard';
export const superAdminGuard: CanActivateFn = (route, state) => {
// Run base auth check first
const isAuth = authGuard(route, state);
if (isAuth !== true) {
return isAuth;
}
// Chain into role authorization
return hasRole('SUPER_ADMIN')(route, state);
};