Sub topic 5
Default Routes, Redirects, and Not-Found Pages
This chapter assumes you can define a Routes array, register it with provideRouter, and render it with RouterOutlet and RouterLink, as covered in the earlier chapters. You should also know TypeScript and standalone components.
A real application has to answer three questions that a list of feature routes doesn't cover:
- What should the user see at the bare root URL,
/? - What happens to old or alternate URLs that should point somewhere else?
- What should the user see when the URL matches nothing?
The Router handles these with empty-path routes, the redirectTo property, and the wildcard path **. All three depend on how the Router matches URLs, so that comes first.
How the Router Picks a Route
The Router splits the URL path into segments. For example, /products/42 becomes products and 42. It then walks your Routes array from top to bottom and uses the first route whose path matches. It does not look for the best or most specific match. Order is part of your configuration.
When no route matches and there is no wildcard, navigation fails with the error Cannot match any routes. URL Segment: '...'. The view stays where it was, and an error appears in the console. A wildcard route stops this from happening.
Default Routes with an Empty Path
A route with path: '' matches the empty path. You can use it in two ways.
You can render a component directly at the root:
{ path: '', component: HomeComponent, title: 'Home' }Or you can redirect the root to a named path:
{ path: '', redirectTo: 'home', pathMatch: 'full' }A redirect gives you one canonical URL. Users see /home in the address bar, and bookmarks, analytics, and routerLinkActive all work with a single path. Rendering at '' gives you a shorter URL. Either is fine. Choose one, and don't serve the same page at both URLs.
`pathMatch`: `prefix` vs `full`
Each route has a pathMatch setting that controls how its path is compared with the URL.
| Value | Matches when | Default? |
|---|---|---|
| `'prefix'` | The route's path matches the start of the remaining URL | Yes |
| `'full'` | The route's path matches the entire remaining URL | No |
Every URL starts with the empty string. With prefix, { path: '', redirectTo: 'home' } would therefore match /products/42, /admin, and every other URL, and send them all to home. Angular catches this. In development mode it throws:
Invalid configuration of route '{path: "", redirectTo: "home"}': please provide 'pathMatch'.
The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.prefix is the right choice for routes that have children. With { path: 'admin', children: [...] }, admin matches the start of /admin/users and passes the rest of the URL (users) to the child routes. full is rarely needed except for empty-path redirects.
"Remaining URL" matters inside child configurations. A child route with path: '' and pathMatch: 'full' matches when nothing is left after the parent's segments. This is how you set a default child view:
{
path: 'admin',
children: [
{ path: '', redirectTo: 'users', pathMatch: 'full' },
{ path: 'users', component: AdminUsersComponent },
{ path: 'settings', component: AdminSettingsComponent }
]
}Here /admin redirects to /admin/users. Nested routes are covered in their own chapter.
Redirects in Detail
Relative and Absolute Targets
A redirectTo string without a leading slash is relative. It replaces only the segments that this route matched. Inside the admin children above, redirectTo: 'users' produces /admin/users.
A string that starts with / is absolute. It replaces the whole URL, whatever level the route is defined at:
{ path: 'old-dashboard', redirectTo: '/admin/users', pathMatch: 'full' }Carrying Parameters Across
A redirect string can reuse parameters from the matched path by naming them:
{ path: 'item/:id', redirectTo: 'products/:id' }/item/42 becomes /products/42. Query parameters and the fragment from the original URL are kept by default. /item/42?ref=email#reviews becomes /products/42?ref=email#reviews.
Redirect Functions
From Angular 18, redirectTo also accepts a function. The function receives the matched route's params, queryParams, fragment, data, and url, and it returns either a string or a UrlTree. It runs in an injection context, so inject() is available inside it.
import { inject } from '@angular/core';
import { Router, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { ProductDetailComponent } from './product-detail.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, title: 'Home' },
{ path: 'products/:id', component: ProductDetailComponent },
// Legacy SKU URLs: /sku/ab-42 -> /products/42?legacy=ab-42
{
path: 'sku/:sku',
redirectTo: ({ params }) => {
const router = inject(Router);
const sku = String(params['sku']);
const id = sku.split('-').pop() ?? '';
return router.createUrlTree(['/products', id], {
queryParams: { legacy: sku }
});
}
},
{ path: '**', component: NotFoundComponent, title: 'Page not found' }
];When the function returns a UrlTree, you control the query parameters and fragment yourself. The original ones are not merged in automatically.
Not-Found Pages with the Wildcard Route
The path ** matches any URL. Because matching is first-match-wins, a wildcard placed early hides every route after it. Put it last.
{ path: '**', component: NotFoundComponent, title: 'Page not found' }A useful not-found component tells users what went wrong and gives them a way to continue:
import { Component, inject } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
@Component({
selector: 'app-not-found',
standalone: true,
imports: [RouterLink],
template: `
<h2>Page not found</h2>
<p>No page exists at <code>{{ url }}</code>.</p>
<a routerLink="/home">Go to the home page</a>
`
})
export class NotFoundComponent {
readonly url = inject(Router).url;
}Render or Redirect?
You could write { path: '**', redirectTo: 'home' } instead. Rendering a component is usually the better choice:
| Approach | URL after navigation | User experience | Debugging |
|---|---|---|---|
| Render `NotFoundComponent` | Unchanged, e.g. `/prodcts/42` | User sees the typo and can fix it | Bad links are visible in logs |
| `redirectTo: 'home'` | `/home` | User is moved without explanation | Broken links are hidden |
Wildcards in Lazy and Child Configurations
A wildcard catches whatever is left at its own level of the tree. If /admin loads a child route array, /admin/unknown matches the parent admin prefix and is then checked against the children. If no child matches, the Router backtracks and tries the remaining top-level routes, so the top-level wildcard can still catch it. To show an admin-specific not-found page inside the admin layout, add a ** route at the end of the admin child routes.
Common Mistakes
- Missing
pathMatch: 'full'on an empty-path redirect. Angular throws a configuration error at startup. - Wildcard not last. Every route after it is unreachable, and no error is reported.
- Redirect loops.
aredirects tobandbredirects toa. Keep redirects one step long, pointing at a route that renders a component. - Expecting a real 404. In a client-side app the server has already returned
index.htmlwith status 200. YourNotFoundComponentis only a visual 404. Search engines need a real status code, which only server-side rendering or server rules can provide. - Deep links failing on refresh. If refreshing
/products/42gives a server 404, the web server isn't configured to fall back toindex.html. That is a server setting, covered in the location strategies chapter.
Exercises
Exercise
Given the routes [{ path: '**', component: NotFoundComponent }, { path: 'home', component: HomeComponent }], what does the user see at /home, and why?
Show answer
The NotFoundComponent. The Router uses the first route that matches, and '**' matches every URL, so the 'home' route is never reached. Move the wildcard to the end of the array.
Exercise
Write a route that sends /catalog/:category/:id to /products/:id and keeps the original query string.
Show answer
{ path: 'catalog/:category/:id', redirectTo: 'products/:id' }. A redirect string keeps query parameters and the fragment by default, and :id is filled in from the matched segment. The :category segment is dropped because the target string doesn't use it.
Exercise
Inside an 'account' route's children, you add { path: '', redirectTo: 'profile' } without pathMatch. What goes wrong, and what is the fix?
Show answer
With the default pathMatch 'prefix', the empty path matches any remaining URL under /account, so this redirect conflicts with every sibling such as /account/billing. Angular rejects the configuration. Add pathMatch: 'full' so the redirect applies only to /account itself.