Sub topic 6
Redirecting with a UrlTree
This chapter assumes you can write a functional guard with inject() and know the basic return types of a guard (boolean, UrlTree, or an Observable or Promise of either). Here we focus on the redirect case: how to block a navigation and send the user somewhere else.
Why return a UrlTree instead of navigating
A guard that returns false cancels the navigation. The user stays where they were, or sees a blank page on first load. That is rarely what you want for a login check.
A guard could call router.navigate(['/login']) and then return false. This works, but it starts a second navigation while the first is still running. The router has to cancel the first one, and you can see odd behavior in events and history.
Returning a UrlTree is cleaner. The router treats it as "cancel this navigation and start a new one to this URL" as one step. The guard only describes where to go, and the router does the navigating.
Building a UrlTree
A UrlTree is a parsed, structured URL. You get one from the Router in two ways:
router.createUrlTree(commands, extras)builds one from route commands, the same wayrouterLinkdoes.router.parseUrl(urlString)parses a full URL string.
The guard below sends anonymous users to the login page and keeps the requested URL in a query parameter.
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 },
});
};state.url is the URL the user tried to reach. Passing it as returnUrl lets the login page send the user back after sign-in.
Using the returnUrl after login
The login page reads the query parameter and navigates there on success. Validate it before use, because a query parameter is user input. Accept only paths that start with a single /, so an attacker cannot craft a link that redirects to another site.
import { inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
export function redirectAfterLogin(): void {
const route = inject(ActivatedRoute);
const router = inject(Router);
const target = route.snapshot.queryParamMap.get('returnUrl') ?? '/';
const safe = target.startsWith('/') && !target.startsWith('//') ? target : '/';
router.navigateByUrl(safe);
}Call this helper from an injection context, such as a component constructor or field initializer, and invoke the returned behavior after a successful login. Use navigateByUrl because returnUrl is a full URL string, which navigate would treat as one path segment.
Common errors
- Returning
router.navigate(...). It returns aPromise<boolean>, not aUrlTree. UsecreateUrlTreeorparseUrl. - Calling
inject()late. Callinject()at the top of the guard, before anyawaitor callback. It only works in an injection context. - Redirect loops. If the guard also protects
/login, the redirect triggers the guard again and never ends. Keep the login route unguarded, or guard it with a separate "already logged in" check. - Dropping the target. Without
returnUrl, users land on the home page after login and lose their place.
Exercise
Why is returning a UrlTree from a guard preferable to calling router.navigate() inside the guard and returning false?
Show answer
Returning a UrlTree lets the router cancel the current navigation and start the redirect as one coordinated step. Calling navigate() inside the guard starts a second navigation while the first is still running, which can cause cancelled-navigation events and confusing history entries.
Exercise
A guard protects every route, including /login, and redirects anonymous users to /login. What happens, and how do you fix it?
Show answer
The redirect to /login triggers the guard again, which redirects again, producing an endless loop. Remove the guard from the /login route, or give it a separate guard that only checks whether the user is already logged in.