10LOC

#routing

Chrome APIsintermediate

URLPattern for route matching without a regex library

// TypeScript hasn't bundled URLPattern into its DOM types yet, so this repo's tsconfig
// doesn't know about it either. One cast at the constructor keeps everything below fully
// typed instead of leaking `any` through the rest of the file.
type UrlMatch = { pathname: { groups: Record<string, string | undefined> } };
type UrlPatternLike = { exec: (input: { pathname: string }) => UrlMatch | null };

URLPattern standardizes the :param/wildcard matching every router library reinvents — built into the browser and, increasingly, server runtimes too.

Bunintermediate

A static file router that falls back to Bun.file

import { serve, file } from "bun";

const PUBLIC_DIR = `${import.meta.dir}/public`;

const server = serve({

A fetch handler can serve API routes first and fall back to Bun.file for anything else, building a static file server without a separate static-file middleware.

Chrome APIsadvanced

The Navigation API for SPA routing without a router library

// TypeScript's DOM lib has neither URLPattern nor the Navigation API yet --
// narrow casts for just the shapes this snippet actually uses.
type UrlMatch = { pathname: { groups: Record<string, string | undefined> } };
type UrlPatternLike = { test: (i: { pathname: string }) => boolean; exec: (i: { pathname: string }) => UrlMatch | null };
const URLPattern = (globalThis as any).URLPattern as new (init: { pathname: string }) => UrlPatternLike;

navigation.addEventListener('navigate', ...) intercepts every link click and history change from one place — the primitive most routers wrap.

TypeScriptadvanced

Template literal types for typed route strings

type ParamNames<Path extends string> = Path extends `${string}:${infer Param}/${infer Rest}`
  ? Param | ParamNames<Rest>
  : Path extends `${string}:${infer Param}`
    ? Param
    : never;

Extract :param names out of a route string at the type level, so a route's caller must supply exactly the params that route needs.

Bunintermediate

Bun.serve() with a routes object: a zero-dependency HTTP server

export const app = Bun.serve({
  routes: {
    "/api/health": new Response("ok"),
    "/api/users/:id": (req) => Response.json({ id: req.params.id }),
    "/api/users": {

Bun.serve()'s routes option matches paths, HTTP methods, and :params natively, replacing a router dependency for most REST APIs.