# Node.js

> The @mettr/node package sends a Node, Bun, Deno or Workers app's events, crawler visits, 404s, errors and response times, with middleware for Express, Fastify and Hono.

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

It runs wherever `fetch` does: Node 20 or later, Bun, Deno, Cloudflare Workers and Vercel's edge. For Next.js, [@mettr/next](/docs/nextjs) does it all in a few lines. The source is on [GitHub](https://github.com/mettrhq/mettr-js), MIT licensed.

## Install

```bash
npm install @mettr/node
```

The client reads the environment; options passed to it win.

| Variable | What |
|---|---|
| `METTR_SECRET_KEY` | the site's secret key (the site's settings, **Tracking**); keep it on the server |
| `METTR_PUBLIC_KEY` | the site's public key, for the script tag and the proxy |
| `METTR_ENABLED` | `true` or `false`; by default on only when `NODE_ENV` is `production` |
| `METTR_PROXY_PATH` | the path on your own domain, `_live` by default; empty loads the script from mettr |
| `METTR_ENDPOINT` | where mettr runs, `https://mettr.app` |

```js
import { Mettr } from '@mettr/node';

export const mettr = new Mettr();
```

## Express

```js
import { mettrErrorHandler, mettrMiddleware } from '@mettr/node/express';

app.use(session(...)); // first, so events carry the user
app.use(
    mettrMiddleware(mettr, {
        user: (req) => req.user?.id?.toString(),
        staff: (req) => req.user?.isAdmin === true,
    }),
);

// ...your routes

app.use(mettrErrorHandler(mettr)); // after the routes
```

Set Express's `trust proxy` when the app runs behind a proxy, so `req.ip` is the visitor's. Behind Cloudflare the visitor's address comes from `CF-Connecting-IP`, and only when the request came from Cloudflare's own ranges.

## Fastify

```js
import { mettrFastify } from '@mettr/node/fastify';

await app.register(mettrFastify(mettr, { user: (request) => request.user?.id }));
```

## Hono

```js
import { mettrHono } from '@mettr/node/hono';

app.use(mettrHono(mettr, { user: (c) => c.get('user')?.id }));
```

On Cloudflare Workers the batch is sent through `waitUntil`, after the response. On Node or Bun, pass the socket's address: `relay: (c) => getConnInfo(c).remote.address`.

## Bun, Deno and Workers

```js
import { Mettr, withMettr } from '@mettr/node';

const mettr = new Mettr({ flushInterval: 0 });

export default {
    fetch: withMettr(mettr, (request, env, ctx) => app.fetch(request, env, ctx)),
};
```

## The script in your pages

```js
res.send(`<head>${mettr.scriptTag()}</head>`);
```

The tag loads the [browser script](/docs/browser-script) from `/_live/script.js` and sends its events to `/_live/events`, which the middleware serves: ad blockers mostly leave first-party requests alone, and the events carry the visitor's address and user as your server saw them. Only what a browser may send passes (page views, events, engagement, [Web Vitals](/docs/browser-script#web-vitals), presence), never a time, a user, an address or revenue.

## What it sends on its own

- **Crawler visits**: a crawler's request, with its page and status. mettr names the crawler and checks it against its owner's network.
- **404s** of people, as errors.
- **Exceptions**, by their class only, never the message. A client's error (a status under 500) is not one.
- **Response times** of one request in twenty, by route.
- Nothing for `/up` (`ignore`), for staff, or while it is off.

Sending never throws into your app: a failed batch answers `false` and is passed to `onError`, without its events.

## Your own events

```js
mettr.event('signup', { plan: 'pro' }, { userId: '42' });
mettr.revenue('order', 49.5, 'EUR', { items: 2 });
mettr.error('PaymentFailed', { provider: 'stripe' });
```

Props are flat: up to 30, each a string, number, boolean or null. Events wait a second to go together (`flushInterval`); a serverless function awaits `mettr.flush()` before it ends.

## Subscriptions

When your billing is your own (anything but Stripe, Paddle or Polar, which mettr [reads itself](/docs/revenue)), send each subscription whenever it changes, and every one once for the history. mettr works out MRR, churn and their movements from them:

```js
mettr.subscription({
    id: 'sub_1',
    status: 'active', // active, past_due, trialing, paused, canceled
    amount: 19, // each cycle, before tax, in the main unit
    currency: 'USD',
    interval: 'month', // day, week, month, year
    userId: '42',
    plan: 'Pro',
});
```

See the [Subscriptions API](/docs/subscriptions-api) for what each field means.

## Your MCP server

If you run an MCP server with `@modelcontextprotocol/sdk`, wrap its transport (Streamable HTTP, SSE or stdio) before connecting it:

```js
import { trackMcp } from '@mettr/node/mcp';

const transport = trackMcp(mettr, new StreamableHTTPServerTransport({ sessionIdGenerator: () => crypto.randomUUID() }), {
    userId: (extra) => extra?.authInfo?.extra?.userId,
});
await server.connect(transport);
```

Each tool, resource, prompt and handshake is sent as an `mcp.*` event with the client, how it ended and how long it took; never the arguments or the answer, and a failed call's message only with `errors: true`. A request your auth refuses before the transport sees it is not counted here.

An MCP server behind a fetch handler (Hono, a Worker, `mcp-handler`, Bun or Deno) is wrapped whole, outside its auth, so a refusal at the door (a 401, 403 or 429) is counted too:

```js
import { withMcp } from '@mettr/node/mcp';

const handler = withMcp(mettr, mcpHandler, { userId: (request) => userFromToken(request) });
app.all('/mcp', (c) => handler(c.req.raw)); // Hono; a Worker passes (request, env, ctx)
```

A streamed answer is counted when its stream ends; a Worker's `ctx.waitUntil` keeps it alive until then. The Express, Fastify and Hono middleware send no crawl, 404 or timing for an MCP client's request. More in [MCP analytics](/docs/mcp-analytics).

## History and deploys

```js
await mettr.import(rows); // each with ts and source_id: a second run adds nothing
await mettr.annotation('Deployed v2.4', { url: 'https://github.com/acme/app/releases/v2.4' });
```

Rows are those of the [Import API](/docs/import-api); notes are those of the [Annotations API](/docs/annotations-api).
