4/12
Technical Architecture & AI Engineering · 7 min read

API Router With Wildcard Path Params and Middleware Chain

Implement a segment-based Prefix Trie API router in TypeScript supporting static routes, named parameters, wildcards, HTTP method isolation, precedence rules, and composable middleware.

Why This Matters at Engineering Leadership Scale

Every API gateway and Backend for Frontend sits behind a router. Once a codebase grows past a few dozen routes, naive linear regex lists trigger subtle outages: registering GET /users/:id above GET /users/me silently hijacks /users/me, or auth middleware gets skipped on a newly mounted wildcard path.

In Atlassian M60/M70 and staff-level coding loops, the API Router drill tests how you pair tree structures (Prefix Trie) with composable async middleware ((req, next) => res). At minute 30, adding HTTP method isolation, strict precedence rules, and per-route auth middleware verifies whether your interfaces absorb new requirements without collapsing into order-dependent if/else chains.

Core Mental Model & Architecture

Routing ArchitectureLookup TimeRegistrationPrecedence BehaviorMain Trade-Off
Segment Prefix TrieO(D) (path segments)O(D)Deterministic: static > :param > *Best scaling; zero registration-order bugs
Linear Regex ListO(R) (total routes)O(1)Fragile: depends on registration orderSlows at 500+ routes; prone to route shadowing
Flat HashMapO(1)O(1)Exact paths onlyCannot match :param or * wildcards

To absorb the Minute-30 Extension cleanly:

  1. Store methods: Map<HttpMethod, RouteEntry> on each terminal trie node so GET /orders/:id and DELETE /orders/:id stay isolated and unmatched methods return 405 Method Not Allowed.
  2. Enforce strict lookup order at every node: staticChildren -> paramChild -> wildcardChild. Static routes always beat :param routes regardless of registration order.
  3. Compose [...globalMiddlewares, ...routeMiddlewares] around the handler with a guard against calling next() twice.

Step-by-Step Implementation Tutorial

1. Implement the Segment Trie, Precedence Matcher, and Middleware Pipeline (Minutes 5 to 28)

typescript
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
export interface HttpRequest {
  method: HttpMethod; path: string; headers: Record<string, string>;
  params: Record<string, string>; wildcard?: string;
}
export interface HttpResponse { status: number; body: unknown; }
export type RouteHandler = (req: HttpRequest) => Promise<HttpResponse> | HttpResponse;
export type Middleware = (req: HttpRequest, next: () => Promise<HttpResponse>) => Promise<HttpResponse>;

interface RouteEntry { handler: RouteHandler; middlewares: Middleware[]; }

class TrieNode {
  public readonly staticChildren = new Map<string, TrieNode>();
  public paramChild: { name: string; node: TrieNode } | null = null;
  public wildcardChild: TrieNode | null = null;
  public readonly methods = new Map<HttpMethod, RouteEntry>();
}

export class ApiRouter {
  private readonly root = new TrieNode();
  private readonly globalMiddlewares: Middleware[] = [];

  public use(middleware: Middleware): void { this.globalMiddlewares.push(middleware); }

  // Minute-30 Extension: Method-scoped route + per-route middlewares
  public addRoute(method: HttpMethod, path: string, handler: RouteHandler, middlewares: Middleware[] = []): void {
    const segs = this.tokenize(path);
    let cur = this.root;
    for (let i = 0; i < segs.length; i++) {
      const seg = segs[i];
      if (seg === "*") {
        if (i !== segs.length - 1) throw new Error(`Wildcard "*" must be final segment: ${path}`);
        cur = cur.wildcardChild ?? (cur.wildcardChild = new TrieNode());
      } else if (seg.startsWith(":")) {
        const name = seg.slice(1);
        if (!name) throw new Error(`Empty param name: ${path}`);
        if (!cur.paramChild) cur.paramChild = { name, node: new TrieNode() };
        else if (cur.paramChild.name !== name) throw new Error(`Conflicting param :${name} vs :${cur.paramChild.name}`);
        cur = cur.paramChild.node;
      } else {
        let next = cur.staticChildren.get(seg);
        if (!next) { next = new TrieNode(); cur.staticChildren.set(seg, next); }
        cur = next;
      }
    }
    if (cur.methods.has(method)) throw new Error(`Duplicate route: ${method} ${path}`);
    cur.methods.set(method, { handler, middlewares });
  }

  public async handle(method: HttpMethod, path: string, headers: Record<string, string> = {}): Promise<HttpResponse> {
    const segs = this.tokenize(path);
    const hit = this.matchNode(this.root, segs, 0, {});
    if (!hit) return { status: 404, body: { error: "Not Found" } };

    const entry = hit.node.methods.get(method);
    if (!entry) {
      return { status: 405, body: { error: "Method Not Allowed", allow: Array.from(hit.node.methods.keys()) } };
    }

    const req: HttpRequest = { method, path, headers, params: hit.params, wildcard: hit.wildcard };
    return this.executeChain([...this.globalMiddlewares, ...entry.middlewares], entry.handler, req);
  }

  private matchNode(
    node: TrieNode, segs: string[], idx: number, params: Record<string, string>
  ): { node: TrieNode; params: Record<string, string>; wildcard?: string } | null {
    if (idx === segs.length) return node.methods.size > 0 ? { node, params: { ...params } } : null;

    const seg = segs[idx];
    // 1. Static > 2. :param > 3. * wildcard
    const staticChild = node.staticChildren.get(seg);
    if (staticChild) {
      const hit = this.matchNode(staticChild, segs, idx + 1, params);
      if (hit) return hit;
    }
    if (node.paramChild) {
      params[node.paramChild.name] = seg;
      const hit = this.matchNode(node.paramChild.node, segs, idx + 1, params);
      delete params[node.paramChild.name];
      if (hit) return hit;
    }
    if (node.wildcardChild && node.wildcardChild.methods.size > 0) {
      return { node: node.wildcardChild, params: { ...params }, wildcard: segs.slice(idx).join("/") };
    }
    return null;
  }

  private async executeChain(middlewares: Middleware[], handler: RouteHandler, req: HttpRequest): Promise<HttpResponse> {
    let lastIndex = -1;
    const dispatch = async (i: number): Promise<HttpResponse> => {
      if (i <= lastIndex) throw new Error("next() called multiple times in one middleware");
      lastIndex = i;
      return i === middlewares.length ? handler(req) : middlewares[i](req, () => dispatch(i + 1));
    };
    return dispatch(0);
  }

  private tokenize(path: string): string[] {
    const clean = path.split("?")[0].replace(/^\/+|\/+$/g, "");
    return clean === "" ? [] : clean.split("/");
  }
}

2. Write Focused Unit Tests & Verify Minute-30 Extensions (Minutes 30 to 50)

Assert four cases:

  1. Static beats :param: Register GET /users/:id first and GET /users/me second; assert /users/me hits the static handler.
  2. Method isolation & 405: Register GET /invoices only; assert POST /invoices returns 405 with allow: ["GET"].
  3. Per-route auth short-circuit: Attach requireBearerAuth to DELETE /users/:id; missing header returns 401 without invoking the handler.
  4. Wildcard fallback: Register GET /files/*; /files/2026/q1/audit.pdf captures wildcard: "2026/q1/audit.pdf".

Worked Production Scenario: Before vs. After

Context: A fintech API gateway routed 420 endpoints across 8 microservices using a flat regex array loaded from per-squad config files. When a release shifted load order, GET /v1/accounts/:id shadowed GET /v1/accounts/export for 45 minutes (400 Invalid UUID: "export"), and global auth exclusion regexes accidentally exposed an admin route.

After: The Platform team migrated to the Segment Prefix Trie router with structural precedence, startup conflict assertions, and explicit per-route auth middleware arrays.

MetricBeforeAfter
Route lookup latency (420 routes)1.9 ms p99 (linear scan)0.04 ms p99 (O(depth))
Route-shadowing outages / quarter3 incidents0 (enforced structurally)
Auth middleware misconfig findings2 high-severity0 (explicit per-route chains)
Duplicate route conflict detectionNone (silent override)Fails CI on startup

Common Failure Modes & Anti-Patterns

  1. Leaking params during trie backtracking: Failing a :param branch and falling back to * without delete params[name] leaves stale keys on req.params. Fix: Delete the param key after each recursive branch returns and clone { ...params } on hit.
  2. Allowing duplicate next() invocations: A buggy middleware calling next() twice executes the handler twice and risks double-writes. Fix: Guard i <= lastIndex inside executeChain().
  3. Silent conflicting param names: Allowing /orgs/:orgId/a and /orgs/:tenantId/b on the same node breaks deterministic param extraction. Fix: Fail fast during addRoute().

How to Handle Pushback in the Room

Skeptical Principal Engineer: "Why drill router internals when Fastify and Hono already exist?"

Calm Response: "In production, we absolutely use Fastify or Hono rather than rolling our own HTTP router. Understanding trie precedence and middleware dispatch lets our Tech Leads diagnose route shadowing, middleware short-circuits, and gateway latency spikes in minutes."

Pushing Product Manager: "Can we mount a vanity-URL catch-all (/:orgSlug/*) at the top of the gateway this week?"

Calm Response: "Putting a catch-all at the top shadows static health and API routes unless precedence is structural. With trie static-over-param rules, we can mount /:orgSlug/* safely while guaranteeing /health and /api/* always win."

Key Takeaways & This Week's Action Rep

  • Use a Segment Prefix Trie (O(depth)): Lookup cost stays constant whether you have 20 or 2,000 endpoints.
  • Make precedence structural: Static > :param > * eliminates merge-order routing outages.
  • Fail fast at startup: Reject duplicate routes, mid-path wildcards, and conflicting param names in CI.
  • Guard middleware dispatch: Block double-next() execution and compose global + per-route auth cleanly.

This Week's Action Rep: Code ApiRouter in 45 minutes without autocomplete. At minute 30, add 405 handling and a requireAuth per-route middleware test proving unauthenticated requests short-circuit with 401.