Sub topic 5
Protecting a route with canActivate
This chapter assumes you know TypeScript, Angular services and dependency injection, the basics of the Routes array, and how Observables and Promises differ. It builds on the earlier chapters about functional guards and guard return values.
What canActivate decides
canActivate is the guard type that answers one question: may the router activate this route? The router runs it after it has matched a URL to a route and before it creates the component. If the guard says no, the current page stays on screen and the navigation is cancelled or redirected.
Use canActivate when a route is reachable in principle but only some users, in some states, should enter it. Typical cases are a page that requires login, a page that requires a completed profile, or a checkout page that requires a non-empty cart.
A guard attached through canActivate runs every time the router tries to enter that route. It also runs when the router moves between two URLs that use the same route, for example /products/1 to /products/2, if the runGuardsAndResolvers setting says it should. The default setting is paramsChange, so a parameter change re-runs the guard.
The shape of a functional guard
A functional guard is a plain function of type CanActivateFn. It receives two arguments and runs inside an injection context, so inject() works in its body.
routeis anActivatedRouteSnapshot. It holds the route's parameters, query parameters, staticdata, and the route configuration.stateis aRouterStateSnapshot. Itsurlproperty is the full URL the user is trying to reach.
Here is a guard that lets logged-in users through and redirects everyone else to the login page.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};Both inject() calls happen synchronously at the top of the function. That matters. Once the function has awaited something or entered a callback, the injection context is gone, and a later inject() throws. Call inject() first, then do asynchronous work with the values you obtained.
Attaching the guard to a route
You attach guards in the route configuration through the canActivate array. The array can hold several guards.
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { productResolver } from './product.resolver';
export const routes: Routes = [
{ path: 'login', loadComponent: () => import('./login.component').then(m => m.LoginComponent) },
{
path: 'products/:id',
canActivate: [authGuard],
resolve: { product: productResolver },
loadComponent: () => import('./product-detail.component').then(m => m.ProductDetailComponent),
},
];Notice that /login has no guard. If you put authGuard on the login route too, an anonymous user would be redirected to /login, which would trigger the guard again, and the router would loop until it gives up.
The resolve entry in the same configuration is covered in a later chapter. For now, the relevant point is that guards run before resolvers, so a blocked user never triggers the data request.
What the return value means
The router accepts several return types and treats each one differently.
| Return value | Effect |
|---|---|
| `true` | Navigation continues. |
| `false` | Navigation is cancelled. The user stays where they were. |
| `UrlTree` | The current navigation is cancelled and a new navigation to that URL starts. |
| `RedirectCommand` | Like a `UrlTree`, with extra navigation options (Angular 18 and later). |
| `Observable` or `Promise` of any of the above | The router waits for the value. For an Observable, it uses the first emitted value. |
Returning false leaves the user with no feedback, so it suits cases where staying put is a sufficient answer. For access control, a redirect is usually friendlier, because the user learns why nothing happened.
Asynchronous guards
Real authentication state often comes from a server call or a token refresh. A guard can return an Observable, and the router subscribes to it.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
export const asyncAuthGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.checkSession().pipe(
map(valid =>
valid
? true
: router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }),
),
);
};Two details cause most of the bugs here.
- The router takes the first value of the Observable and then unsubscribes. An Observable that never emits leaves the navigation hanging forever. An HTTP call completes on its own, but a long-lived stream such as a
BehaviorSubjectemits immediately and then keeps going, which is fine because only the first value is read. A stream that waits for a value which never arrives is not fine. - An error in the Observable cancels the navigation and surfaces as a navigation error. Decide what a failure should mean, usually "not authenticated", and handle it with
catchError.
import { catchError, map, of } from 'rxjs';
// Inside the guard, treat a failed session check as "not logged in":
// auth.checkSession().pipe(
// map(valid => valid || router.createUrlTree(['/login'])),
// catchError(() => of(router.createUrlTree(['/login']))),
// );Using route data to make one guard reusable
A guard that hardcodes a role cannot be shared. Instead, put the requirement in the route's static data and read it from the snapshot.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const roleGuard: CanActivateFn = (route) => {
const auth = inject(AuthService);
const router = inject(Router);
const required = route.data['role'] as string | undefined;
if (!required || auth.hasRole(required)) {
return true;
}
return router.createUrlTree(['/forbidden']);
};
// In the routes array:
// { path: 'reports', canActivate: [authGuard, roleGuard], data: { role: 'analyst' }, component: ReportsComponent }When several guards are listed, the router runs them and requires all of them to pass. If any returns a UrlTree, the router follows it. If more than one returns a UrlTree, the router uses the first one in array order, so list the broader check (login) before the narrower one (role).
Common mistakes
- Guarding the redirect target. This produces a redirect loop, as described above.
- Calling
inject()after anawaitor inside a callback. Capture services at the top. - Returning
falsewhen you meant to redirect. The user sees nothing happen. - Navigating with
router.navigate()inside the guard and then returningfalse. It works, but returning aUrlTreeis cleaner. The router can coordinate it with the current navigation, which avoids races between two navigations. - Treating the guard as the only protection. The guard only controls what the browser shows. The data itself must be protected on the server, a topic a later chapter covers in detail.
How the flow looks
Exercises
Exercise
A guard on the route login redirects anonymous users to /login. What happens when an anonymous user opens the app, and how do you fix it?
Show answer
The router enters /login, the guard runs and sends the user to /login again, so the navigation loops until the router stops it with an error. Remove the guard from the login route. Only routes that need protection should have the guard.
Exercise
Write a CanActivateFn named cartGuard that allows navigation only when inject(CartService).itemCount() is greater than zero, and otherwise redirects to /cart.
Show answer
import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { CartService } from './cart.service'; export const cartGuard: CanActivateFn = () => { const cart = inject(CartService); const router = inject(Router); return cart.itemCount() > 0 ? true : router.createUrlTree(['/cart']); };