Sub topic 6
Redirecting with a UrlTree
This chapter assumes you know TypeScript, Angular services and dependency injection, and the basics of the Angular router (the Routes array, route parameters, routerLink). It also assumes you have written a simple functional guard. Here you will learn how a guard redirects the user instead of only blocking them.
Why return a redirect instead of false
A guard that returns false cancels the navigation. The user stays where they were, and nothing tells them why. On the first page load there is no previous page, so the user sees a blank outlet.
A redirect fixes both problems. The guard tells the router which URL to go to instead. The user lands on a page that explains or fixes the situation, such as a login page.
What a UrlTree is
A UrlTree is an object that represents a parsed URL. It holds the path segments, the query parameters, and the fragment as a data structure, not as a string. You do not build one by hand. You ask the Router for one.
The router offers three ways to get a UrlTree:
| Method | Input | Use it when |
|---|---|---|
| `router.createUrlTree(commands, extras)` | An array of path commands and optional extras | You build a URL from route segments, as with `routerLink` |
| `router.parseUrl(url)` | A URL string | You already have a full URL string such as `/not-found` |
| `router.serializeUrl(tree)` | A `UrlTree` | You need the string form, for example in a test or a log |
createUrlTree and parseUrl return a UrlTree. serializeUrl goes the other way and returns a string.
Returning a UrlTree from a guard
When a guard returns a UrlTree, the router cancels the current navigation and starts a new one to that URL. The cancelled navigation never activates its route. Here is the guard from the topic plan, with the key parts in order.
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 },
});
};The guard does three things:
- It calls
inject()for the services it needs. This works because the router runs guards in an injection context. - It returns
truefor logged-in users, so navigation continues. - It returns a
UrlTreefor everyone else. ThereturnUrlquery parameter remembers where the user wanted to go.
The state argument is a RouterStateSnapshot. Its url property is the full URL the user asked for, including query parameters. That is why the guard reads state.url and not route.url. The route.url value only holds the segments of that one route.
Sending the user back after login
The returnUrl is only useful if the login page reads it. The login component finishes signing in and then navigates to the saved URL.
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
standalone: true,
template: `<button (click)="signIn()">Sign in</button>`,
})
export class LoginComponent {
private auth = inject(AuthService);
private router = inject(Router);
private route = inject(ActivatedRoute);
signIn(): void {
this.auth.logIn();
const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') ?? '/';
this.router.navigateByUrl(returnUrl);
}
}Use navigateByUrl here, not navigate. The returnUrl is a complete URL string that may contain its own query parameters. navigateByUrl parses it correctly. navigate expects an array of commands and would treat the string as a single path segment.
Redirect and the browser history
The redirect replaces the blocked navigation in the history. Suppose the user clicks a link to /admin, and the guard sends them to /login. The history contains /login, not /admin. The Back button therefore goes to the page before the link, not into a redirect loop.
This is the main reason to prefer returning a UrlTree over calling router.navigate() inside the guard and then returning false. The manual approach starts a second navigation while the first one is still running. The two navigations compete, and the history entry can come out wrong. A returned UrlTree lets the router handle the switch as one step.
Controlling how the redirect navigates
You can pass extras to createUrlTree that shape the new URL: queryParams, fragment, and queryParamsHandling. A guard can also set the navigation behavior of the redirect. Since Angular 18, a guard can return a RedirectCommand instead of a bare UrlTree. A RedirectCommand wraps a UrlTree and a NavigationBehaviorOptions object.
import { inject } from '@angular/core';
import { CanActivateFn, RedirectCommand, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuardWithOptions: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn()) {
return true;
}
const loginTree = router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
return new RedirectCommand(loginTree, { skipLocationChange: true });
};With skipLocationChange: true, the router renders the login route but leaves the address bar unchanged. Use that sparingly. A visible URL is usually better, because the user can bookmark it, reload it, and share it.
Redirects from asynchronous guards
A guard may return an Observable or a Promise that produces a UrlTree. The router uses the first value the Observable emits. That makes asynchronous checks straightforward.
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 router = inject(Router);
return inject(AuthService).checkSession().pipe(
map((valid) =>
valid
? true
: router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } }),
),
);
};Here checkSession() is assumed to return an Observable<boolean>. If the Observable completes without emitting, the navigation is cancelled. If it throws an error, the navigation fails with an error event. So handle the failure case inside the guard, with catchError, and return a redirect there as well.
Common errors
- Redirect loops. If a guard on
/loginredirects to/login, the router keeps cancelling and restarting. Never put the redirecting guard on the page it redirects to. The router also stops after too many redirects and reports an error. - Using
route.urlin place ofstate.url. You then lose the parent segments and the query string, and the user returns to the wrong page. - Forgetting
inject()is only valid synchronously. Callinject()at the top of the guard. Calling it inside amapcallback or after anawaitthrows an error because the injection context is gone. - Calling
router.navigate()and returningfalse. This produces two navigations. Return theUrlTreeinstead. - Returning a string. The router does not accept a URL string. Wrap it with
router.parseUrl('/login').
Summary of the flow
The diagram shows what the router does when a guard returns a UrlTree.
Exercise
A guard protects the route /orders/42?tab=history. It redirects anonymous users with router.createUrlTree(['/login'], { queryParams: { returnUrl: route.url.join('/') } }). After login the user lands on /42 and gets an error. What is wrong, and how do you fix it?
Show answer
route.url holds only the URL segments of that one route, so the saved value lacks the parent path and the query string. Use state.url from the second guard argument, which is the full requested URL, here /orders/42?tab=history. After login, call navigateByUrl(returnUrl) so the string is parsed as a full URL.
Exercise
Why is returning a UrlTree better than calling router.navigate(['/login']) and then returning false?
Show answer
The manual approach starts a second navigation while the first is still in progress, so the two compete and the history can end up wrong. Returning a UrlTree lets the router cancel the first navigation and start the second one as a single, ordered step.