Sub topic 9
Keeping unauthorized users from downloading a chunk with canMatch
This chapter assumes you can define routes with the Angular Router, write standalone components, and use loadChildren to lazy load a route group. It also assumes you have run ng build before.
The problem: guards that run too late
A lazy route splits your code into a separate chunk. The router downloads that chunk the first time the route is activated. If you protect the route with the wrong guard, an unauthorized user can still trigger the download.
Two guards look similar here:
canActivateruns after the router has matched the route. For a lazy route, the router has usually already fetched the chunk by then.canMatchruns while the router is deciding whether a route matches the URL. If it returnsfalse, the route is skipped and the chunk is never requested.
For an admin area, this difference matters. With canActivate, a visitor who is not logged in may still download your admin code and read it in the browser's developer tools. With canMatch, they do not receive it.
Writing a canMatch guard
A canMatch guard is a function of type CanMatchFn. You can call inject() inside it to reach services. It may return a boolean, a UrlTree, or an observable or promise of either.
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 that you provide yourself. Its isLoggedIn() method returns a boolean.
Returning a UrlTree from router.parseUrl('/login') tells the router to redirect. Returning false instead makes the router try the next route that could match the URL. If none matches, navigation fails with a "Cannot match any routes" error. A redirect gives users a better result.
Using canMatch to choose between routes
Because false means "try the next route", you can declare two routes with the same path. The guard picks which one applies.
import { Routes } from '@angular/router';
import { authMatch } from './guards';
export const routes: Routes = [
{
path: 'account',
canMatch: [authMatch],
loadChildren: () =>
import('./account/account.routes').then(m => m.ACCOUNT_ROUTES),
},
{
path: 'account',
loadComponent: () =>
import('./marketing/sign-up.component').then(m => m.SignUpComponent),
},
];Here, logged-in users get the account area. Everyone else gets a sign-up page. Each branch is its own chunk, and only the matching one is downloaded.
Preloading and guards
Preloading downloads lazy chunks in the background. If you use PreloadAllModules, you might expect it to fetch the admin chunk anyway. For routes that have a canMatch guard, the router does not preload them until the guard passes. This keeps the protection intact, because the chunk is not fetched for users who fail the check.
A guard is not real security
canMatch controls what the browser downloads. It does not secure your data. Anyone can request a JavaScript file directly if they know its URL, and all client-side checks can be bypassed. Keep these rules in mind:
- Enforce permissions on the server for every API call.
- Do not put secrets, API keys, or private business rules in client code, lazy or not.
- Treat
canMatchas a way to avoid wasted downloads and to shape the user experience.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Using only `canActivate` on a lazy route | The chunk downloads before the check runs | Add or switch to `canMatch` |
| Returning `false` with no fallback route | "Cannot match any routes" error | Return a `UrlTree`, or add a fallback route |
| Making `isLoggedIn()` return a promise that is never awaited | The guard returns a truthy object and always passes | Return the resolved value, or return the promise itself |
| Trusting the guard as the only protection | Data is exposed through the API | Check permissions on the server |
You can verify the behavior in your browser. Open the Network tab, log out, and visit /admin. You should see a redirect to /login and no admin chunk request. After you log in, the same visit should show the chunk request.
Exercise
A route has canActivate: [authGuard] and a loadChildren for an admin area. A logged-out user visits /admin and is redirected to /login, but the admin chunk still appears in the Network tab. What change stops the download, and why does it work?
Show answer
Move the check to canMatch: [authMatch]. A canMatch guard runs while the router is matching the route, before the lazy chunk is requested. A canActivate guard runs after matching, so the router has already started loading the chunk. Return a UrlTree such as router.parseUrl('/login') so that denied users are redirected instead of hitting a "Cannot match any routes" error.
Exercise
Why should you still check permissions on the server when canMatch already blocks the admin chunk?
Show answer
canMatch runs in the browser, so a user can bypass it, for example by requesting the chunk file's URL directly or by calling your API without the app. Only server-side checks protect data.