← Back to Angular, page 8

angular-0149 · Hard senior

How do you write a custom UrlMatcher and a custom UrlSerializer, and when are they needed?

A UrlMatcher decides whether a route matches the URL segments and returns the consumed segments and named params, for patterns like "@username" that a path string cannot express. A UrlSerializer parses and writes whole URLs, so a custom one can normalise case or handle legacy formats. Both are rarely needed, so use them when path patterns are not enough.

Full answer

Path strings such as courses/:id cover most routes. Two extension points handle the rest.

UrlMatcher (per route): a function (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult | null. Return null for no match. Return { consumed: segments, posParams: { name: segments[0] } } to match and expose parameters. Use it for:

  • Profile URLs like /@asha (a path cannot match a prefix of a segment).
  • Matching by rules, such as a numeric id versus a slug.
  • Migrating old URL shapes without redirects.

Register with { matcher: profileMatcher, component: ProfileComponent }. The params are read in the component like any route param. Test matchers as plain functions, since they need no router.

UrlSerializer (global): the service that turns a URL string into a UrlTree (parse) and back (serialize). Replace it by providing { provide: UrlSerializer, useClass: LowerCaseUrlSerializer }. Extend DefaultUrlSerializer, and override parse to normalise the path (lowercase it, remove trailing slashes), so /Courses/42/ and /courses/42 reach the same route. Cases for it: case insensitive URLs, legacy query formats, custom encodings, or stripping tracking parameters.

Cautions:

  • A global serializer affects every URL, including query params and fragments. Only lowercase the path part, because params can be case sensitive (ids, tokens).
  • Redirects (server side) are better than rewriting for SEO. A serializer changes the URL the router uses internally, and the browser address bar follows serialize.
  • Keep parse(serialize(tree)) stable. Round trips must not change the tree, or navigation can loop.
  • Prefer simple solutions first: redirectTo, canMatch, and route data.

Testing: matchers are pure. For the serializer, call parse with sample strings and assert on the resulting tree.

typescript
import { Injectable } from '@angular/core';
import { DefaultUrlSerializer, UrlMatchResult, UrlSegment, UrlSerializer, UrlTree } from '@angular/router';

export function profileMatcher(segments: UrlSegment[]): UrlMatchResult | null {
  if (segments.length === 1 && segments[0].path.startsWith('@') && segments[0].path.length > 1) {
    return {
      consumed: segments,
      posParams: { username: new UrlSegment(segments[0].path.slice(1), {}) },
    };
  }
  return null;
}

@Injectable()
export class LowerCasePathSerializer extends DefaultUrlSerializer {
  override parse(url: string): UrlTree {
    const queryStart = url.search(/[?#]/);
    const path = queryStart === -1 ? url : url.slice(0, queryStart);
    const rest = queryStart === -1 ? '' : url.slice(queryStart);
    const cleanPath = path.length > 1 ? path.replace(/\/+$/, '') : path;
    return super.parse(cleanPath.toLowerCase() + rest);
  }
}

// { matcher: profileMatcher, component: ProfileComponent }
// providers: [{ provide: UrlSerializer, useClass: LowerCasePathSerializer }]

Angular 20.3. A Karma test calls the matcher with segments, and parses `/Courses/42/` with the serializer, checking the lowercase path and untouched query case.

Key points

  • `UrlMatcher` matches segments and returns consumed segments and `posParams`, or `null`.
  • `UrlSerializer` parses and writes URLs globally. Extend `DefaultUrlSerializer`.
  • Normalise only the path. Keep round trips stable.
  • Try `redirectTo` and `canMatch` first.

Common mistakes

  • Lowercasing query parameters or fragments in a global serializer.
  • Returning segments that were not consumed.
  • Writing a serializer whose parse and serialize are not inverses.

Follow-ups

  • How would you match `/@username` URLs?
  • Why can a serializer cause navigation loops?
  • When is a server redirect better?

Tips

  • Show the `@username` matcher. It is a classic.
  • Warn about query parameters.
  • Mention testing the pure functions.

Evaluation rubric

  • Implements matcher and serializer correctly.
  • Understands the global effect and risks.
  • Chooses simpler tools first when they fit.