Sub topic 9
Choosing routes at match time with canMatch
This chapter assumes you can write a functional guard with inject() and know the Routes array, lazy loading with loadChildren and loadComponent, and the return types a guard may use (boolean, UrlTree, Observable, Promise). Here you will learn what makes canMatch different from canActivate, when to use it, and where it goes wrong.
What canMatch decides
canActivate answers the question "may this navigation enter a route that has already been matched?" canMatch answers an earlier question: "should this route configuration take part in matching at all?"
While the router turns a URL into a router state, it walks the Routes array in order and tests each entry against the URL segments. If an entry has canMatch guards, they run during that test. A guard that returns false does not cancel the navigation. The router treats the entry as if its path had not matched and tries the next entry.
This has two consequences:
- Several entries can share one
path. The first whosecanMatchguards pass wins. - A route that fails
canMatchnever loads. For aloadChildrenorloadComponententry, the JavaScript chunk is not downloaded.
The guard type is CanMatchFn. It receives the Route being tested and the UrlSegment[] the router is trying to consume:
import { inject } from '@angular/core';
import { CanMatchFn } from '@angular/router';
import { AuthService } from './auth.service';
export const adminMatchGuard: CanMatchFn = (route, segments) => {
return inject(AuthService).isAdmin();
};Unlike canActivate, it gets no ActivatedRouteSnapshot, because the route is not active yet. Route parameters are not available through a snapshot, but you can inspect segments if you need them.
Serving different content on one path
The most useful pattern is two entries with the same path, where the first is guarded:
import { Routes } from '@angular/router';
import { adminMatchGuard } from './admin-match.guard';
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [adminMatchGuard],
loadComponent: () =>
import('./admin-dashboard.component').then(m => m.AdminDashboardComponent),
},
{
path: 'dashboard',
loadComponent: () =>
import('./user-dashboard.component').then(m => m.UserDashboardComponent),
},
];An admin who visits /dashboard gets the admin component. Everyone else falls through to the second entry. The URL stays the same, and non-admins never download the admin chunk. With canActivate, you would have to redirect non-admins to a different URL.
Feature flags work the same way:
import { inject } from '@angular/core';
import { CanMatchFn } from '@angular/router';
import { FeatureFlagService } from './feature-flag.service';
export const featureFlag = (flag: string): CanMatchFn => () =>
inject(FeatureFlagService).isEnabled(flag);The factory is a plain function that returns a guard. Use it as canMatch: [featureFlag('new-checkout')]. Put the old checkout after it with the same path, and the router uses it whenever the flag is off.
canMatch and lazy loading
For lazy routes, canMatch is the right guard for access control. canActivate runs after matching. By then the router has already fetched the loadChildren code, so the user's browser has downloaded a bundle they may never see. canMatch runs before that fetch.
| Aspect | `canActivate` | `canMatch` |
|---|---|---|
| Runs | After the route is matched | While matching |
| `false` means | Navigation is cancelled | Entry is skipped, next entry is tried |
| Lazy code | Already downloaded | Not downloaded |
| Arguments | `ActivatedRouteSnapshot`, `RouterStateSnapshot` | `Route`, `UrlSegment[]` |
| Same path twice | Not meaningful | Supported |
You can combine them. A common setup is canMatch to hide the route from the wrong audience and canActivate for checks that depend on route parameters or the full target URL.
Returning a UrlTree
canMatch can return a UrlTree as well as a boolean. The router then abandons the current navigation and starts a new one to that URL:
import { inject } from '@angular/core';
import { CanMatchFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const loggedInMatch: CanMatchFn = () => {
const auth = inject(AuthService);
return auth.isLoggedIn() ? true : inject(Router).createUrlTree(['/login']);
};A redirect stops the search immediately. Entries later in the array are never tried. Return false when you want fall-through, and return a UrlTree when you want to send the user elsewhere.
Failure modes and gotchas
No fallback entry. If every entry for a URL fails canMatch, the router rejects the navigation with a "Cannot match any routes" error (NG04002). Users see a blank screen or a console error instead of a page. Add a wildcard entry ({ path: '**', ... }) at the end, or make sure the last entry for each path has no canMatch guard.
Entry order matters. The router tries entries top to bottom. If you put the unguarded entry first, it always wins and the guarded one is never reached.
Guards that only ask a question once. A guard that reads a signal or a plain value reflects the state at the moment of matching. If the user logs in later, the router does not re-match on its own. The next navigation sees the new state, but the page the user is already on does not change.
Slow async guards. A guard that returns an Observable or Promise holds up the navigation until it completes. An Observable must emit and complete, or the navigation hangs. Use take(1) or first() on streams that never complete.
Guards run on each matching attempt. The router tests canMatch whenever it matches the URL, and it may test a guard for a nested entry while it works out a state that is later discarded. Keep guards free of side effects such as analytics calls or writes.
Segments are for matching only. The segments argument holds only the segments the entry is trying to consume at that level. Do not rely on it for the whole URL. Use canActivate with state.url for that.
Putting it together
This configuration gives anonymous users the login page at /account, gives logged-in users the real account area, and falls back to a not-found page for anything else:
import { Routes } from '@angular/router';
import { loggedInMatch } from './logged-in-match.guard';
export const routes: Routes = [
{
path: 'account',
canMatch: [loggedInMatch],
loadChildren: () => import('./account/account.routes').then(m => m.ACCOUNT_ROUTES),
},
{
path: 'not-found',
loadComponent: () => import('./not-found.component').then(m => m.NotFoundComponent),
},
{ path: '**', redirectTo: 'not-found' },
];Note that loggedInMatch here redirects to /login, so that route must exist in your real application. If you prefer fall-through, return a boolean instead and add a second account entry that shows a sign-in prompt.
Exercise
You have two entries with path 'reports'. The first has canMatch: [managerMatch] and lazy-loads ManagerReports. The second has no guard and lazy-loads BasicReports. A non-manager navigates to /reports. Which component renders, is the ManagerReports chunk downloaded, and what changes if managerMatch returns a UrlTree to '/login' instead of false?
Show answer
BasicReports renders, because the false result makes the router skip the first entry and match the second. The ManagerReports chunk is not downloaded, because canMatch runs before lazy loading. If managerMatch returns a UrlTree to '/login', the router abandons this navigation and starts a new one to /login, so the second entry is never tried and BasicReports does not render.
Exercise
Why can a route with only canActivate still cause a lazy chunk to download for a user who is then denied, and how does canMatch avoid this?
Show answer
canActivate runs after the router has matched the entry, and for loadChildren the router loads the code as part of matching and activation. So the chunk may already be fetched when the guard denies access. canMatch runs during matching, before the loader runs, so a false result skips the entry and the chunk is never requested.