The relay is a Cloudflare Worker that a client's `www` host points at. Every request for the client's site passes through it on the way to the real server. For most requests it should do nothing at all. For product and company pages it adds structured data. The design problem is the asymmetry: the benefit is small and per page, and the possible damage is the client's whole shop.

A request through the Worker

A row of five boxes: request, counted first without delaying the response; site config, read from KV, where a missing or broken config gives safe defaults; classify, into bypass, llms.txt, robots.txt or proxy; origin fetch, exactly once, where a dead origin is a 502 and not a retry; and guard, only a 2xx response whose type is text/html. From classify an arrow leads down to special paths: llms.txt and robots.txt served from KV. From origin fetch a dashed arrow leads down to passed through: bypass path, kill switch off, error page, not HTML. From guard an arrow leads down to merge: the page payload from KV, merged as the HTML streams. Two notes. Fail open: the whole handler runs inside one try; once the origin has answered, a later failure returns that same response with no second fetch, and a failure before that falls back to fetching the request as it arrived. No branching on who asks: the user agent is read for counting only, and a crawler and a person get identical bytes.
Figure 1. One request. The Worker changes a response on a single path, after the site config, the route, the origin's status and the content type have all passed. Everything else is returned as the origin sent it.

Classify

The first decision is whether this request is any of the Worker’s business. The function is shown whole, with two comments added for this page.

const ALWAYS_BYPASS = ['/.well-known/'];

export function classify(url: URL, config: SiteConfig): RouteKind {
  for (const prefix of ALWAYS_BYPASS) {
    if (url.pathname.startsWith(prefix)) return 'bypass';
  }
  if (!config.enabled) return 'bypass';                 // the kill switch
  for (const prefix of config.bypassPaths) {
    if (url.pathname.startsWith(prefix)) return 'bypass';
  }
  const special = SPECIAL_PATHS[url.pathname];          // /llms.txt, /robots.txt
  if (special !== undefined) return special;
  return 'proxy';
}

The order of the checks is the design.

  • /.well-known/ comes before the site’s own config. Certificate authorities validate a domain through that path. When the Worker first sat on a wildcard route it intercepted the validation request, and the certificate for the first connected host stayed pending. The path cannot be left to per-site configuration, because the certificate has to exist before there is a configuration.
  • The kill switch comes next. A site with injection disabled is still proxied, and every path is a bypass.
  • Bypass paths are per-site data. Checkout, login, account and admin paths differ by platform, so they are stored with the site and not hard-coded. Setting a site’s proxy options never silently empties the list.

Fetch once

The origin is fetched exactly once. If that fetch throws, the Worker answers 502 and does not try again. A second fetch would fail on a request body that has already been consumed, would submit an order form twice, and would double the load on a server that is already failing.

Guard, then merge

const response = await fetchOrigin(originRequest);
// From here on we hold the origin's response. Any failure returns it, with no second request.
try {
  if (!response.ok) return response;
  const contentType = response.headers.get('content-type') ?? '';
  if (!contentType.toLowerCase().includes('text/html')) return response;
  const withGa4 =
    config.ga4 === undefined ? response : injectGa4(response, config.ga4);
  const key = pageKey(url.hostname, url, config.pageKeyParams);
  const payload = await loadPagePayload(env.GEO_RULES, key);
  if (payload === null) return withGa4;
  return injectPayload(withGa4, payload);
} catch {
  return response;
}

Comments are translated and condensed, and the lines for bypass paths are left out. withGa4 is the response itself unless the site has an analytics tag configured.

The response.ok check was added after an incident. A commerce platform answered an AI crawler’s user agent with a 403, and its 403 page was HTML, so it passed the content-type check. The Worker added product structured data to a document that said “403 Forbidden”. Nothing looked wrong: the injection was counted as a success. What the crawler read was an error page asserting that a product lived at that address. A test now loops over 403, 404 and 500 and asserts that none of them is touched.

Fail open, in code

The outer handler is five lines.

try {
  return await handle(request, env);
} catch {
  // Any exception falls back to the origin.
  // Our outage must not become the client site's outage.
  return fetch(request);
}

There are two levels of fallback, and they differ in what they can return.

  • After the origin has answered, any failure in the guard, the KV read or the rewrite returns the response already in hand. There is no second request.
  • Before the origin has answered, the outer catch sends the request on as it arrived.

A design rule sits behind the second case. Reading the site config must never throw, because the config is what tells the Worker where the origin is and how to recognise a request that would loop back to itself. The config loader therefore catches every failure from both the KV read and the JSON parse and returns a default config, and the default is the cautious one: origin unknown, nothing enabled.

A malformed config is worse than a missing one. If the bypass list or the page-key parameters are present and have the wrong shape, the loader disables the whole site. Falling back to an empty bypass list would mean injecting into checkout pages. The safe failure is to do nothing.

What is merged

A table with three columns: the page already has, what the Worker does, and what it never does. A Product node: adds the extra additionalProperty entries, and manufacturer when it is absent; never overwrites the name, the price or the rating, because the origin is live and our copy is a snapshot. An Organization node: fills keys that are absent from a fixed allow-list of address, identifier, opening hours, area served, founding date, VAT id and slogan; never replaces a value the site already states. Neither: appends one new script before the end of the body; never appends when a merge already placed the data. Structured data it cannot parse, or larger than 256 × 1024 characters: leaves the original as it is and appends its own block; never rewrites a block it could not read. A note on why merge: the first design appended a second Product block; search engines expect one Product per page, and two can cost the page its rich result; the merge reads every structured-data script the origin sends before deciding, which is why the addition goes at the end of the body and not in the head.
Figure 2. Merge rules for structured data. The Worker fills what the page lacks and leaves what the page states.

The Worker uses HTMLRewriter, which processes the document as a stream. It buffers each structured-data script the origin sends, looks for the node that represents the product or the organisation, and adds only what is missing.

RuleReason
Never overwrite name, price or ratingThe origin is live. Our payload was computed earlier, and a sold-out price would otherwise persist
Add at the end of the bodyThe decision to merge or append needs every script the origin sends, and the head closes before body scripts are seen
Cap each buffered script at 256 × 1024 charactersAbove that the original is put back as it was, and the payload is appended as its own block. Buffering has to be bounded on a Worker
Escape < and the two Unicode line separatorsSo that a value cannot close the script element or break the JSON
Remove content-length after a rewriteThe stream’s length has changed, and a stale header truncates the page

Two other things are served: llms.txt and robots.txt, straight from KV as plain text. If no content is stored for a host, the request goes to the origin.

No branch on the user agent. The Worker reads the user agent to count crawler visits and for nothing else. Serving crawlers something different from what people see is cloaking, and the same content goes to both.

Turning it off

StepEffectNote
Disable injection in the site’s KV configEvery path is a bypass. The Worker still relaysTakes up to a minute, the KV read-cache window
Remove the client’s custom hostnameThat host stops reaching the WorkerOne client
Remove the Worker’s routeNo host reaches the WorkerEvery client
The client restores its DNS recordThe relay is out of the path entirelyBounded by the record’s time to live, which is lowered beforehand where the DNS provider allows it

A new host is always connected with injection disabled. The relay runs as a pass-through first, its plumbing is checked, and injection is switched on as a second step. That splits one risk into two smaller ones.

Tests

The Worker’s tests run inside the Workers runtime with the real bindings, and the origin is a mocked fetch with outside network access disabled.

GroupExamples
End to endStructured data is injected. Nothing is injected on 403, 404 or 500. Two products that differ only by a query parameter get their own payloads. Tracking parameters do not hide a payload. A bypass path is not touched even when a payload exists. The kill switch stops injection. Broken KV data returns the original. A POST with a body does not produce a 500. A dead origin is a 502 with no retry
Routing/.well-known always passes
OriginRequests that would loop back to the Worker are recognised, for each kind of host
ConfigDefaults, key ordering and escaping, a malformed list disables the site, and behaviour when KV throws
MergeNew block against merge into Product and Organization, broken structured data kept, script-closing sequences escaped, including after a merge

Failure modes

What happensWhat the Worker does
The site config cannot be readDefault config: origin unknown, injection off
The site’s config is malformedInjection is disabled for the site
The origin returns an error pageReturned untouched
The response is not HTMLReturned untouched
The rewrite throwsThe origin’s response is returned
The origin is down502, no retry
A request would loop back to the Worker502 with a header naming the reason
A certificate validation request arrivesPassed straight through, whatever the config

Limits

  • Fail-open covers the Worker’s own logic. An exception in the handler falls back to the origin. It does not cover the platform services the Worker itself depends on.
  • www only. Proxying a bare domain needs a plan tier this deployment does not use, so the client has to make www its canonical host. If AI crawlers read the bare domain, the injection is on an address nobody reads.
  • The kill switch is not instant. KV reads are cached for about a minute at each location.
  • No timeout on the origin fetch. The Worker waits as long as the platform lets it.
  • Response headers pass through untouched. A strict content-security policy on the origin is not adjusted.
  • The list of the relay’s own hosts is in code. Recognising a request that would loop depends on it, and moving it to KV is still to do.