> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom edge contract

> Reference for running a Foil first-party integration on your own CDN or proxy: routes, forwarded headers, the X-Foil-Proxy headers, the Origin fallback, signed agents, caching, and credential rotation.

A **Custom proxy** integration runs on an edge you operate: a CDN function, a load balancer rule, or a reverse proxy. This page describes what that edge must do. Foil's own Cloudflare and CloudFront adapters, and the Worker module it generates for a Cloudflare integration that runs in your Worker, implement the same contract, at edge adapter version `1.3.0`.

## Configuration values

In step 2 of the integration page, select **Reveal proxy config**. The dashboard asks you to verify your identity, then shows these values:

| Field | Example | Use |
| - | - | - |
| **Integration ID** | `int_0123456789abcdef0123456789abcdef` | Send as `X-Foil-Proxy-Integration`. It's also part of the continuity cookie's name. |
| **Forward to** | `api.usefoil.com` | The upstream host for every forwarded request |
| **Integration URL** | `https://www.example.com/foil` | Its path is the prefix your edge matches and strips. |
| **Site origin** | `https://www.example.com` | The `Origin` value to send when the browser sends none, for an integration that answers only on its own hostname |
| **Credential** | A random 43-character string | Send as `X-Foil-Proxy-Credential`. Store it as a secret. |
| **Edge adapter version** | `1.3.0` | The contract version on this page. Send it as `X-Foil-Proxy-Adapter-Version`. |

**Copy config JSON** copies the same values in the form Foil's adapters read, where `collectionBase` is the integration URL and `pageOrigin` is the site origin:

```json theme={"dark"}
{
  "integrationId": "int_0123456789abcdef0123456789abcdef",
  "collectionBase": "https://www.example.com/foil",
  "pageOrigin": "https://www.example.com",
  "collectionHost": "api.usefoil.com"
}
```

An integration that serves every domain routed to the edge also has `"anyOrigin": true`. Ignore fields you don't use. The JSON never contains the credential.

## Handle a request

For each request your edge receives:

1. Decide whether the request belongs to Foil. See [Match the request](#match-the-request). If it doesn't, pass it to your application unchanged.
2. Build the upstream headers from the [forwarded headers](#forwarded-headers), the [continuity cookie](#continuity-cookie), and the [headers your edge sets](#headers-your-edge-sets).
3. Send the request to `https://api.usefoil.com` followed by the path with the integration prefix removed and the original query string, with the same method and body. See [Send the request upstream](#send-the-request-upstream).
4. Return Foil's response to the browser. See [Return the response](#return-the-response).

## Match the request

A request belongs to Foil when all of these are true:

* Its origin equals the integration URL's origin, for example `https://www.example.com`. An integration that serves every domain routed to the edge skips this check.
* Its path starts with the integration URL's path followed by `/`, for example `/foil/`. An integration without a path matches from `/`.
* After you remove that prefix, the method and remaining path match a row in the following table.

| Method | Path after the prefix | Purpose |
| - | - | - |
| `GET`, `HEAD` | `/t.js` | The SDK |
| `GET`, `HEAD` | `/t.<release>.js` | A specific SDK release, for [pinned pages](https://usefoil.com/docs/pin-a-release.md#pin-through-a-first-party-integration) |
| `POST` | `/v2/collect/sessions` | Create or continue a session |
| `POST` | `/v2/collect/sessions/<session>/documents/<document>/batches` | Observation batches |
| `POST` | `/v2/collect/sessions/<session>/documents/<document>/results` | Session handoff |
| `GET` | `/v2/collect/r` | Continuity |
| `GET` | `/v2/collect/pings/<id>` | Timing ping |
| `OPTIONS` | Any `/v2/collect/...` path above | CORS preflight |

`<release>`, `<session>`, `<document>`, and `<id>` each consist of 1 to 128 letters, digits, `-`, or `_`, and `<release>` has at least 8. A path that contains `%`, `\`, or `//` never matches. Match complete paths only. Don't forward a whole `/v2/` prefix.

For example, `POST https://www.example.com/foil/v2/collect/sessions?x=1` goes upstream as `POST https://api.usefoil.com/v2/collect/sessions?x=1`.

## Forwarded headers

Copy only these request headers from the browser, with their values unchanged. Foil reads several of them during scoring, including `Accept-Encoding` and the client hints, so don't normalize or rewrite them. Drop every other header.

| Group | Headers |
| - | - |
| Content negotiation | `accept`, `accept-language`, `accept-encoding`, `content-type`, `content-encoding` |
| Conditional requests | `if-none-match`, `if-modified-since` |
| Browser identity | `user-agent`, `priority`, `sec-ch-ua`, `sec-ch-ua-mobile`, `sec-ch-ua-platform`, `sec-ch-ua-platform-version`, `sec-ch-ua-arch`, `sec-ch-ua-bitness`, `sec-ch-ua-model`, `sec-ch-ua-full-version-list`, `sec-ch-ua-wow64` |
| Fetch metadata | `sec-fetch-site`, `sec-fetch-mode`, `sec-fetch-dest`, `sec-fetch-user` |
| Privacy | `dnt`, `sec-gpc` |
| CORS | `origin`, `access-control-request-method`, `access-control-request-headers` |
| Foil | `authorization`, `x-session-id`, `x-client-key`, `x-batch-seq`, `x-foil-sdk-version`, `x-foil-bundle-hash`, `x-foil-client-attempt-id`, `x-foil-operation`, `x-foil-document-id` |

On the two script routes, don't forward `authorization`.

Don't forward `Signature`, `Signature-Input`, or `Signature-Agent` under their own names. Your edge sends them as `X-Foil-Proxy-Signature`, `X-Foil-Proxy-Signature-Input`, and `X-Foil-Proxy-Signature-Agent`. See [Signed agents](#signed-agents).

### Continuity cookie

From the browser's `Cookie` header, forward only cookies named `__Secure-foil-cid-<integration ID>`. A browser can hold more than one, so forward each of them, joined with `; `, and let Foil pick the one whose signature verifies. Never forward your application's cookies, and don't send a `Cookie` header on the script routes.

## Headers your edge sets

| Header | Value |
| - | - |
| `X-Foil-Proxy-Credential` | The integration's proxy credential |
| `X-Foil-Proxy-Integration` | The integration ID |
| `X-Foil-Proxy-Viewer-IP` | The IP address of the client that connected to your edge, as your CDN observed it. Send a single IPv4 or IPv6 address, optionally with a port, such as `203.0.113.7` or `[2001:db8::1]:443`. Don't copy it from a header the client controls. |
| `X-Foil-Proxy-Adapter-Version` | The contract version your edge implements, such as `1.3.0`. Foil records it, and the integration page's **Edge adapter** field shows when your edge is behind. Foil ignores a value that isn't three dot-separated numbers. |
| `X-Foil-Proxy-Host` | The hostname the browser requested, such as `www.example.com`, taken from the `Host` or `:authority` of the request your edge received. Send it on HTTPS requests only, without a port or with `:443`. Don't copy it from another header the client controls. See [Signed agents](#signed-agents). |
| `X-Foil-Proxy-Signature`, `X-Foil-Proxy-Signature-Input`, `X-Foil-Proxy-Signature-Agent` | The browser's `Signature`, `Signature-Input`, and `Signature-Agent` headers, with their values unchanged. Send each one the browser sent, on every route except the two script routes. See [Signed agents](#signed-agents). |
| `Origin` | Only when the browser sent no `Origin` header. See [Origin fallback](#origin-fallback). |
| `Host` | `api.usefoil.com`. Some reverse proxies forward the browser's `Host` by default. Foil rejects those requests. |

Any request that carries an `X-Foil-Proxy-*` header must prove it with a valid credential for an installed integration. Foil doesn't fall back to treating it as an ordinary request.

### Origin fallback

When the integration URL is on the page's own origin, browsers omit the `Origin` header on same-origin `GET` requests, including the SDK's continuity request to `/v2/collect/r`. Foil checks every request against the publishable key's [allowed origins](https://usefoil.com/docs/first-party/multiple-domains.md#allowed-origins-are-the-authority), so it needs an origin to compare.

When the browser sent no `Origin`, set it to:

* The integration's **Site origin**, for an integration that answers only on its own hostname.
* The origin of the hostname the request arrived on, such as `https://shop.example.net`, for an integration that serves every domain routed to the edge.

Never replace an `Origin` header the browser sent.

## Signed agents

Some AI agents sign each request with [Web Bot Auth](https://datatracker.ietf.org/doc/draft-meunier-web-bot-auth-architecture/), which uses HTTP Message Signatures ([RFC 9421](https://www.rfc-editor.org/rfc/rfc9421)). When Foil verifies a signature, the session is attributed to the agent that signed it. The signature covers the URL the agent called on your edge, so Foil checks it against that URL rather than the one your edge forwards to:

* **Host.** The value of `X-Foil-Proxy-Host`. It must be the integration URL's host or another host on the same registrable domain, such as `cdn.example.com` for the integration URL `https://www.example.com/foil`. Only when your edge sends no `X-Foil-Proxy-Host`, or a value that isn't a hostname on port 443, does Foil use the integration URL's host instead.
* **Path.** The integration URL's path followed by the path your edge forwarded. For example, a request forwarded to `/v2/collect/sessions` for the integration URL `https://www.example.com/foil` was called as `/foil/v2/collect/sessions`.
* **Query and scheme.** The forwarded query string, and `https`.
* **Headers.** The values your edge forwarded. A signature can cover only the [forwarded headers](#forwarded-headers) and the three signature headers.

Foil reads a signature only from the `X-Foil-Proxy-Signature` headers on a request with a valid credential, and ignores `Signature`, `Signature-Input`, and `Signature-Agent` on any request from an edge. A Foil release that can't verify signatures through an edge drops the `X-Foil-Proxy-*` headers, so it records the signature as absent rather than invalid.

Foil reports a signature as unverifiable (`error`) rather than invalid when it can't rebuild what the agent signed:

* `X-Foil-Proxy-Host` names a host on another registrable domain than the integration URL's. Foil doesn't fall back to the integration URL's host in this case.
* The signature covers a header your edge doesn't forward, such as `Cookie`.
* Your edge sent no `X-Foil-Proxy-Host`, and the signature doesn't verify for the integration URL's host. The agent may have called another hostname your edge serves.

On CloudFront, a function sees only the viewer headers that the behavior's origin request policy includes. `Managed-AllViewer` and `Managed-AllViewerExceptHostHeader` both include the three signature headers, but only `Managed-AllViewer` includes `Host`. With `Managed-AllViewer`, your function must still set `Host` to `api.usefoil.com` before the request goes upstream.

## Send the request upstream

* Use HTTPS to `api.usefoil.com` and pass the request body through unchanged for `POST`.
* Don't follow redirects. If Foil answers with a `3xx` status other than `304`, return `502` to the browser instead.
* Don't cache requests or responses for Foil's routes at your edge.
* Set a timeout. Foil's adapters wait 15 seconds, then return `502` with `Cache-Control: no-store`.

## Return the response

Return Foil's status, headers, and body unchanged, including `Set-Cookie`, the CORS headers, and `Cache-Control`.

* **Caching.** Foil sends `CDN-Cache-Control: no-store` on every response through an integration. `t.js` has a short browser cache lifetime, and the continuity response has a private one, but neither may be stored in a shared cache. The upstream URL `https://api.usefoil.com/t.js` is the same for every integration, so a cache keyed on it can serve one integration's release to another.
* **Compression.** If your edge's HTTP client decompresses the upstream response, remove `Content-Encoding` and `Content-Length` before you return it.
* **Errors.** If the upstream request fails or times out, return `502` with `Cache-Control: no-store`.

## Rejections

Foil rejects a request from an edge with `401` and the error code `auth.invalid_api_key` when any of these is true:

* The credential or integration ID is wrong, or the credential has been retired.
* You haven't selected **Start accepting traffic** yet, or the integration is being removed or has been removed.
* The method and path aren't a route in the [table](#match-the-request).
* The path names an SDK release that Foil doesn't list.
* `Host` isn't `api.usefoil.com`.
* `X-Foil-Proxy-Viewer-IP` is missing or isn't a single IP address.

Foil also answers `401` when the publishable key belongs to the integration's other environment, such as a `pk_test_*` key on a **Live** integration. Otherwise, a `401` for a request that carries a valid publishable key means one of the edge problems above.

## Credential rotation

A rotation gives the integration a second credential while the first stays valid. To start one, select **Rotate** in the **Proxy credential** section of the integration page.

While a rotation is open:

1. Foil accepts both credentials. **Reveal proxy config** shows the new one.
2. You deploy the new credential to your edge whenever you're ready. Foil records which credential each request carries.
3. Foil retires the old credential once all of these are true:
   * At least an hour has passed since the rotation started.
   * The new credential has arrived through your edge.
   * The old credential hasn't arrived for an hour, or a day has passed since the new one first arrived.

Until the new credential arrives, both stay valid with no deadline, so an edge that hasn't been updated keeps working. After the new credential first arrives, every edge that serves the integration has at most a day to switch.

On Cloudflare and CloudFront integrations that Foil deploys, Foil deploys the new credential to the edge itself and retires the old one at least an hour after that deployment. Every edge you run, including your own Worker, follows the rules above.

## Run inside an existing Cloudflare Worker

If your site is served by a Cloudflare Worker you already operate, create a Cloudflare integration and choose **Your Worker** under **Who deploys it**. Step 2 of the integration page then gives you a Worker module that implements this contract with your integration's values filled in. It exports `foilProxy(request, env)`, which returns a response for Foil's routes and `null` for anything else.

1. Save the module as `foil-proxy.js` next to your Worker.

2. Select **Reveal proxy config** and store the credential as a Worker secret:

   ```bash theme={"dark"}
   npx wrangler secret put FOIL_PROXY_CREDENTIAL
   ```

3. Call the module first in your `fetch` handler:

   ```javascript theme={"dark"}
   import { foilProxy } from "./foil-proxy.js";

   export default {
     async fetch(request, env, ctx) {
       const foil = await foilProxy(request, env);
       if (foil) return foil;
       return handleRequest(request, env, ctx); // your existing handler
     },
   };
   ```

4. Deploy your Worker, then select **Start accepting traffic** in step 3.

The module reads the visitor IP from `CF-Connecting-IP` and returns `404` for requests that arrive from another Worker.

## Test your edge

After you select **Start accepting traffic**, request the SDK through the integration URL:

```bash theme={"dark"}
curl -sS -o /dev/null -D - https://www.example.com/foil/t.js
```

The response should have status `200` and no `Set-Cookie` header. Before you select **Start accepting traffic**, the same request returns `401`. Then load a page that runs the install snippet, reload it once, and confirm all three [checks](https://usefoil.com/docs/first-party/checks.md) pass.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.