Sub topic 9
Keeping unauthorized users from downloading a chunk with canMatch
This chapter assumes you can write standalone components, define routes with provideRouter, and read ng build output. It also assumes you know how loadChildren creates a lazy chunk, which earlier chapters covered. Here you will use the canMatch guard to decide whether a lazy route applies before the browser fetches its code.
Why the choice of guard matters for lazy routes
A guard answers one question: may this navigation continue? For lazy routes it also decides whether the bundle for the guarded area gets downloaded. Two guards can give the same user-facing result but have different network behavior.
canActivateruns after the router has matched the route and loaded its configuration. For a route withloadChildren, the lazy chunk has already been downloaded when the guard runs. The user is turned away, but the code has already arrived in the browser.canMatchruns while the router is deciding which route matches the URL. If the guard returnsfalse, the route does not match and the router never calls itsloadChildrenfunction. The chunk is not requested.
canMatch replaced the older canLoad guard, which is deprecated. canMatch does everything canLoad did. It also works on routes that are not lazy, and it can fall through to a different route with the same path.
The guard on a lazy route
A functional guard is a function that receives the Route and the URL segments being matched. It can call inject() to get services, because the router runs it in an injection context.
import { inject } from '@angular/core';
import { CanMatchFn, Router, Routes } from '@angular/router';
import { AuthService } from './auth.service';
export const authMatch: CanMatchFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.parseUrl('/login');
};
export const routes: Routes = [
{
path: 'admin',
canMatch: [authMatch],
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];AuthService is an application service you write yourself. Any object with a synchronous or asynchronous login check will do.
A guard can return three kinds of result:
| Return value | Effect |
|---|---|
| `true` | The route matches. The router continues and loads the chunk if it is not already loaded. |
| `false` | The route does not match. The router tries the remaining routes in the array. |
| `UrlTree` | The current navigation is cancelled and the router navigates to the tree instead. |
A guard can also return a Promise or an Observable of these values, which is useful when the answer comes from the server.
What happens during a navigation
The diagram shows the order of events for an unauthorized user who navigates to /admin.
When the user is logged in, the guard returns true. The router then runs the loadChildren function, the browser requests the chunk, and navigation continues.
Comparing canMatch with canActivate
Consider the same route protected by canActivate instead.
import { Routes } from '@angular/router';
import { authActivate } from './auth.guards';
export const routes: Routes = [
{
path: 'admin',
canActivate: [authActivate],
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];The router matches admin, calls loadChildren to learn the child routes, and only then runs canActivate. An anonymous visitor who types /admin downloads the admin chunk and is then redirected. You can confirm this in the browser's network panel. With canMatch, the request for the admin chunk does not appear.
Use canActivate when the decision depends on the matched route's parameters or data, or when the guard should run for every child. Use canMatch when the question is "should this part of the application be reachable at all for this user?"
Falling through to another route
Because a failed canMatch means "this route does not match", the router goes on to the next route in the array. You can use this to serve different content at the same path.
import { inject } from '@angular/core';
import { CanMatchFn, Routes } from '@angular/router';
import { AuthService } from './auth.service';
const isAdmin: CanMatchFn = () => inject(AuthService).hasRole('admin');
export const routes: Routes = [
{
path: 'dashboard',
canMatch: [isAdmin],
loadComponent: () =>
import('./dashboard/admin-dashboard.component').then(
m => m.AdminDashboardComponent
),
},
{
path: 'dashboard',
loadComponent: () =>
import('./dashboard/user-dashboard.component').then(
m => m.UserDashboardComponent
),
},
];Admins get the first route and download the admin dashboard chunk. Everyone else fails the guard on the first route and matches the second, so they download only the user dashboard. Each variant is a separate chunk, and a user fetches only the one they can see.
This is a pattern canActivate cannot give you. A failed canActivate stops the navigation. It never tries a second route.
Two details matter here:
- Order is significant. The router tries routes top to bottom, so put the guarded route first.
- If every route with that path fails to match and there is no wildcard route, the navigation fails with an error such as "Cannot match any routes". Either end with a
**route, or return aUrlTreefrom the guard so the user lands somewhere sensible.
Guards that need the segments or the route
A CanMatchFn receives two arguments: the Route being tested and an array of UrlSegment objects for the part of the URL being matched. You rarely need them, but they let one guard serve several routes.
import { inject } from '@angular/core';
import { CanMatchFn, Route, Router, UrlSegment } from '@angular/router';
import { AuthService } from './auth.service';
export const roleMatch: CanMatchFn = (route: Route, segments: UrlSegment[]) => {
const auth = inject(AuthService);
const router = inject(Router);
const required = route.data?.['role'] as string | undefined;
if (!required || auth.hasRole(required)) {
return true;
}
const attempted = segments.map(s => s.path).join('/');
return router.createUrlTree(['/forbidden'], {
queryParams: { from: attempted },
});
};The route then declares which role it needs.
import { Routes } from '@angular/router';
import { roleMatch } from './role.guard';
export const routes: Routes = [
{
path: 'reports',
canMatch: [roleMatch],
data: { role: 'analyst' },
loadChildren: () =>
import('./reports/reports.routes').then(m => m.REPORT_ROUTES),
},
];Reading route.data inside a guard keeps the rule in the route configuration, next to the path it protects. Note that route.data here is the static data from the route definition. Resolved data is not available yet, because resolvers run after matching.
Asynchronous checks
If the login state must be fetched from the server, return an Observable or a Promise. The router waits for the first emitted value.
import { inject } from '@angular/core';
import { CanMatchFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
export const sessionMatch: CanMatchFn = () => {
const router = inject(Router);
return inject(AuthService).checkSession().pipe(
map(valid => (valid ? true : router.parseUrl('/login')))
);
};Make sure the observable completes or emits promptly. If it never emits, the navigation hangs, because the router is waiting for an answer before it can pick a route.
Pitfalls
The guard is not a security boundary
A canMatch guard runs in the user's browser, so a determined user can bypass it. The chunk is still a static file at a public URL, so anyone who knows the file name can request it directly. Treat the guard as a way to save bandwidth and show the right screen. Real protection belongs on the server: authenticate API calls, and keep secrets out of client code.
Preloading can bypass the guard
A preloading strategy fetches lazy chunks in the background, outside a user navigation. The router's preloader does not run canMatch guards before it calls load(). If you use PreloadAllModules, a chunk behind canMatch can therefore be downloaded for a user who would be turned away. This is the opposite of what you wanted.
Two ways to avoid it:
- Do not preload guarded routes. With the selective strategy from the preloading chapter, leave
data: { preload: true }off them. - Write the strategy so it checks the same condition before calling
load().
Behavior around preloading has changed between Angular versions, so confirm it in your own build by opening the network panel as an anonymous user and watching for the chunk.
The chunk stays after logout
canMatch is evaluated on each navigation, even when the chunk is already loaded. A user who logs out will be blocked from re-entering the route. The JavaScript they already downloaded remains in memory until the page reloads. If that matters, redirect to a full page load on logout.
Guards that depend on state that is not ready
On a full page refresh, the guard may run before the app has restored the session from storage or from a cookie. If isLoggedIn() returns false only because initialization has not finished, the user is sent to /login although they are signed in. Initialize the session in an app initializer, or make the guard asynchronous and wait for it.
Redirecting to a route that is also guarded
If a guard returns a UrlTree pointing at a route that fails the same guard, the router redirects in a loop and eventually reports an error. Send users to a route that is outside the guarded area, such as /login.
Checking that it works
Verify the behavior rather than trusting the configuration.
- Run
ng serveor serve a production build. - Open the browser's network panel, filter by JavaScript, and clear the log.
- Sign out and navigate to
/admin. You should land on the login page, and no admin chunk request should appear. - Sign in, navigate to
/admin, and confirm that the chunk is requested once. - Navigate away and back. The chunk is not requested a second time, because the router keeps the loaded configuration.
If the chunk appears in step 3, look for a preloading strategy that includes the route, a static import of the admin code from somewhere in the main bundle, or a canActivate guard being used where you meant canMatch.
Exercise
A route has path: 'billing', canActivate: [authActivate], and a loadChildren function. Anonymous users are redirected to /login, but the network panel shows the billing chunk being downloaded first. What change keeps the chunk from loading, and what must you check if the chunk still appears afterwards?
Show answer
Replace canActivate with canMatch (using a CanMatchFn that returns true or a UrlTree for /login). The router then evaluates the guard before it calls loadChildren, so no request is made. If the chunk still appears, check whether a preloading strategy such as PreloadAllModules includes the route, because the preloader does not run canMatch. Also check whether the billing code is imported statically elsewhere in the main bundle.
Exercise
You want admins to see AdminDashboardComponent and everyone else to see UserDashboardComponent at the same path /dashboard, and each group should download only its own code. How do you configure the routes?
Show answer
Define two routes with path: 'dashboard', each using loadComponent with a dynamic import(). Put the admin route first and add canMatch: [isAdmin]. The second route has no guard. A non-admin fails the first route's guard, so the router falls through to the second route. Order matters, because the router tries routes from top to bottom.