# Cloudflare Worker

> The @mettr/cloudflare Worker sends crawler visits, 404s and response times of any site behind Cloudflare and adds the script to its pages, with no change to the site.

Source: https://mettr.app/docs/cloudflare

For a static site, a site builder behind Cloudflare, or a CMS you would rather not touch. A Worker on the site's routes passes each request to the origin as it was and sends mettr what only a server sees: crawler visits (search engines and AI crawlers seldom run scripts) with the status the origin answered, people's 404s and response times. It also serves the [browser script](/docs/browser-script) from the site's own domain and adds its tag to every HTML page. The source is on [GitHub](https://github.com/mettrhq/mettr-js), MIT licensed.

The site's domain has to be on Cloudflare, with its DNS records proxied (the orange cloud).

## Set up

```bash
npm create cloudflare@latest mettr-worker -- --type hello-world --ts
cd mettr-worker
npm install @mettr/cloudflare
```

```ts
// src/index.ts
export { default } from '@mettr/cloudflare';
```

Run it on every path of the site:

```jsonc
// wrangler.jsonc
{
    "routes": [{ "pattern": "example.com/*", "zone_name": "example.com" }]
}
```

Then store the keys (the site's settings, **Tracking**) as the Worker's secrets, and deploy:

```bash
npx wrangler secret put METTR_SECRET_KEY
npx wrangler secret put METTR_PUBLIC_KEY
npx wrangler deploy
```

## Settings

| Variable | What |
|---|---|
| `METTR_SECRET_KEY` | the site's secret key, as a Worker secret |
| `METTR_PUBLIC_KEY` | the site's public key, for the tag the Worker adds |
| `METTR_INJECT` | `false` when the pages carry mettr's tag already |
| `METTR_IGNORE` | paths that send nothing, comma separated (`/up` by default; `*` matches anything) |
| `METTR_PROXY_PATH` | the path on your own domain, `_live` by default |

## Your own Worker

To tell mettr who the signed-in user is, or who is staff:

```ts
import { mettrWorker } from '@mettr/cloudflare';

export default {
    fetch: mettrWorker({
        user: (request) => readUserIdFromCookie(request),
        staff: (request) => request.headers.has('x-staff'),
        assets: false, // images, scripts and fonts send nothing (the default)
    }),
};
```

The visitor's address is Cloudflare's `CF-Connecting-IP`: mettr places the visitor and drops the address. Only what a browser may send passes through `/_live/events`.

An MCP client's request (one that names the MCP protocol or a session, or asks for an event stream) passes through and sends nothing, as an assistant's user agent would read as a crawler's. To count the calls to an MCP server, use the SDK of the app behind the Worker, or in a Worker of your own that answers MCP, `withMcp` from [@mettr/node](/docs/node#your-mcp-server). More in [MCP analytics](/docs/mcp-analytics).
