Skip to content

Routing: site resolution, then descriptors

Routing has two stages. First the worker decides which CMS site answers the request, from the request Host. Then it maps the request path to the single best page descriptor within that site. The path-matching stage replaced the old hardcoded rule list with a small, order-independent matcher driven entirely by the descriptors in the resolved site's settings.

Source: src/site/resolve.ts (site resolution), src/engine/router.ts, src/engine/settings.ts (descriptor matching).

Site resolution: host-default, with an optional pin

resolveSite(host, env, ctx) (src/site/resolve.ts) decides which CMS site a request belongs to. By default the lookup key is the request Host, which is what makes a single worker deployment able to serve many CMS sites:

const override = env.CMS_SITE_ID?.trim();
const lookupKey = override ? override : host;
  • Host resolution (multi-tenant, the default). When env.CMS_SITE_ID is unset or empty, lookupKey is the request host and the worker calls GET /public/v2/sites/{host}/settings. Each distinct Host on the route resolves to its own CMS site, so one deployment can front any number of domains that cms-api knows about.
  • CMS_SITE_ID override (single-tenant pin). When the env var is set and non-empty, it replaces the host as the lookup key (GET /public/v2/sites/{CMS_SITE_ID}/settings) regardless of which domain the request arrived on. This is how a worker env is pinned to one site even though the code path is the same for every deployment -- see Deploy and purge for which envs set it and which don't.

Either way, the resolved settings expose a canonical siteId (ResolveResult.siteId, src/site/resolve.ts) -- the numeric site.id from the payload, falling back to the lookup key -- which becomes PageCtx.siteId (see Architecture). Every downstream data fetch keys off ctx.siteId, not off env.CMS_SITE_ID directly -- src/pages/*.ts, src/pages/_shared.ts, and src/engine/sources.ts all build their /public/v2/sites/<id>/... URLs from ctx.siteId. So on the host-resolution path, both the page content and the branding (favicon, ads.txt, robots.txt, templates, all read from the same resolved SiteSettings) come from whichever site the host resolved to -- there is no separate "branding site" and "content site."

Unknown host: a clean 404, never a stale or wrong site

If cms-api has no site for the lookup key, it returns 404 and resolveSite throws SiteNotFoundError. src/index.ts catches this specifically and returns a static not-found page (siteNotFoundPage, status 404, cache-control: no-store so an unknown host that later gets a route bound to it is never stuck behind a cached 404) instead of falling through to any per-site rendering. A repeat request for the same unknown host within a short window is short-circuited by an in-isolate negative cache before it reaches origin again -- see Caching. A transient resolve failure (not a 404) is different: src/index.ts treats that as a 503, not a 404, since the site might exist but be temporarily unreachable.

The two functions

  • matchPattern(pathname, pattern) matches one path against one pattern such as /{category}/{slug}, returning the captured params and a specificity score, or null on no match.
  • matchDescriptor(pathname, pageTypes) runs every descriptor's patterns and returns the best DescriptorMatch, or null when nothing matches.

Matching a single pattern

matchPattern splits both the path and the pattern into segments (leading and trailing slashes ignored) and compares them position by position:

export function matchPattern(
  pathname: string,
  pattern: string,
): { params: Record<string, string>; specificity: number } | null {
  const patternParts = pattern.split("/").filter(Boolean);
  const pathParts = pathname.split("/").filter(Boolean);
  if (patternParts.length !== pathParts.length) return null;

  const params: Record<string, string> = {};
  let specificity = 0;
  for (let i = 0; i < patternParts.length; i++) {
    const seg = patternParts[i]!;
    const val = pathParts[i]!;
    if (seg.startsWith("{") && seg.endsWith("}")) {
      params[seg.slice(1, -1)] = decodeURIComponent(val);
    } else if (seg === val) {
      specificity++;
    } else {
      return null;
    }
  }
  return { params, specificity };
}

Three rules fall out of this:

  • Segment count must match. /a/b never matches /a/b/c.
  • {param} segments capture. {slug} captures the path segment under the name slug (URL-decoded). They do not add to specificity.
  • Literal segments must match exactly and each one adds 1 to the specificity score. A pattern with more fixed segments is more specific.

Choosing the best descriptor

matchDescriptor evaluates every pattern of every descriptor and keeps the winner under a strict ordering:

if (
  best === null ||
  candidate.specificity > best.specificity ||
  (candidate.specificity === best.specificity && candidate.position < best.position)
) {
  best = candidate;
}

The tie-break chain is:

  1. Higher specificity wins -- more literal segments beats more {param} segments.
  2. On equal specificity, lower position wins. A descriptor with no position sorts after any number (1_000_000 + index), then by descriptor order.

Because specificity comes first, the result is robust to how the descriptors happen to be listed in the settings payload.

Catch-all exclusion

Any pattern containing a * segment (for example the 404 descriptor's /*) is skipped during matching:

if (pattern.includes("*")) continue; // catch-all -> engine fallback only

Catch-alls never win a match. Instead, an unmatched path returns null and the engine falls back to the not-found descriptor explicitly (below). This keeps the 404 from accidentally outranking a real route.

The not-found fallback

src/index.ts turns a null match into the explicit not-found descriptor:

const match: DescriptorMatch =
  matchDescriptor(pathname, pageTypes) ??
  { descriptor: notFoundDescriptor(pageTypes), params: {} };

notFoundDescriptor (src/engine/settings.ts) finds the descriptor whose builder is notfound or whose type is 404, falling back to a built-in 404 descriptor if the settings carry none:

export function notFoundDescriptor(pageTypes: PageDescriptor[]): PageDescriptor {
  return (
    pageTypes.find((d) => d.builder === "notfound" || d.type === "404") ?? {
      type: "404",
      routes: ["/*"],
      layout: ["404"],
      ttl: 300,
      builder: "notfound",
    }
  );
}

So the engine always has a descriptor to render, even for a path that matches nothing.

Where descriptors come from

getPageTypes (src/engine/settings.ts) prefers the API-served descriptors and falls back to a built-in set only when the settings carry none:

export function getPageTypes(settings: SiteSettings): PageDescriptor[] {
  const fromApi = settings.site_settings.page_types;
  if (Array.isArray(fromApi) && fromApi.length > 0) return fromApi;
  return DEFAULT_PAGE_TYPES;
}

DEFAULT_PAGE_TYPES mirrors the seed descriptors and is used only when the CMS has not yet served any (an old worker, or a stale KV fallback snapshot). Once the API serves page_types, the API copy wins -- so a site's routing can evolve without a worker redeploy.

Worked example: /category/foo resolves to category, not article

Two DEFAULT_PAGE_TYPES descriptors both have a pattern that matches a two-segment path:

{ type: "article",  routes: ["/{category}/{slug}"], ... position: 40 },
{ type: "category", routes: ["/category/{slug}", "/{slug}"], ... position: 50 },

For the path /category/foo:

Descriptor Pattern Match Specificity
article /{category}/{slug} yes (category=category, slug=foo) 0 literals
category /category/{slug} yes (slug=foo) 1 literal (category)

Both match with two segments, but category's pattern has one literal segment (category) versus the article pattern's zero. Higher specificity wins, so /category/foo resolves to the category descriptor -- even though category has the higher (less preferred) position, because specificity is compared first. The position tie-break only matters when two patterns have the same specificity.

A single-segment path like /foo matches category's second pattern /{slug} (0 literals) and, since no other descriptor matches one segment with higher specificity, resolves to category as the site's catch-all content listing.

Category URL keys and hidden categories

Nav and list URLs use slugified category keys (Exclusive Interviews → /exclusive-interviews). The worker matches settings categories[].slug and list queries with the same rule (strip + lower + spaces→hyphens).

Some categories are never shown in nav, grids, or sitemaps, and their listing pages return 404: trending, yachts-and-jets, uncategorized (see isExcludedCategory in src/pages/_shared.ts).

Note that this excludes listing pages only. isExcludedCategory is called from category.ts, sitemap.ts, homepage.ts and the sidebar -- never from article.ts -- so an article in an excluded category still renders. That is deliberate: trending is a curated bucket whose articles also live under their primary category.

Robots: noindex

Two independent signals decide the <meta name="robots"> a page emits, and the effective value is their OR (AISD-248):

signal scope where it lives
page_types.seo.noindex the route the descriptor, via layoutFlags(ctx)
content.noindex the row the v2 page payload's seo object, via payloadIsNoindex(data)

The two cannot be collapsed into one: content.noindex is a per-ROW column, so a route that must be noindex while the same content stays indexable on its canonical URL can only be expressed on the descriptor. Any descriptor can set seo.noindex and the matched route's value reaches the builders through ctx.descriptor; no descriptor sets it today.

Preview mode also forces noindex (renderLayout ORs input.preview in), which is unchanged.

An article descriptor with variant = "trending", routes = ["/trending/{slug}"] and seo.noindex used to serve /trending/{slug} (AISD-248). The CMS database is left exactly as it is -- those page_types rows stay, and so does every trending row and flag -- because the route is now refused in the worker, so the descriptor can never match.

The trending worker (separate team) owns /trending/* and /s/*: it is bound to those paths at the Cloudflare route level and reads the article straight from cms-api. It cannot override an origin response for a path the CMS worker already serves, which is why the route had to move rather than be shared.

Deleting the descriptor is not sufficient by itself, so isForeignRoute (src/engine/router.ts) short-circuits those prefixes to not-found before matching:

/trending/foo   -> 404 (not matched at all)
/s/foo          -> 404
/sneakers/foo   -> normal article route

Without it, /trending/foo would still match the generic /{category}/{slug} article descriptor -- the payload is fetched by slug and the category segment is never validated -- serving the same article at a second, indexable URL now that the route-scoped noindex is gone.

The trending data is untouched: the trending content type, the is_trending feed flag behind /lists?kind=trending, and the sidebar/nav category exclusions all behave exactly as before.