JavaScript
The @mettr/browser package loads the browser script from your bundle and sends your product's events, safely during server rendering.
The same browser script as the one-line tag, loaded from your code: for apps built with a bundler (Vite, webpack, Next.js, Nuxt, SvelteKit, Remix). The source is on GitHub, MIT licensed.
Install
npm install @mettr/browser
Use
Load the script once, as early as you can, with the site's public key (the site's settings, Tracking):
import { load, track } from '@mettr/browser'; load('pk_your_site_key');
Page views, navigation in single-page apps, outbound clicks and who is on the page right now are then sent on their own. Send the product's own events with track:
track('signup', { plan: 'pro' });
Props are flat: up to 30, each a string, number, boolean or null. Calls made before the script has loaded are kept and sent once it has.
The package is safe to import during server rendering: without a window it does nothing.
Through your own domain
To load the script and send events through routes on your own domain:
load('pk_your_site_key', { src: 'https://example.com/_live/script.js', api: 'https://example.com/_live/events', });
The events route has to forward with a secret key and the visitor's address: see Through your own domain.
From a server
The package runs in the browser only. From Node or any other backend, send events to the Events API with a secret key, which must never reach a page:
await fetch('https://mettr.app/api/v1/events', { method: 'POST', headers: { Authorization: `Bearer ${process.env.METTR_SECRET_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ type: 'event', name: 'signup', user_id: String(user.id), props: { plan: 'pro' } }), });
Leaving yourself out
Run localStorage.mettr_ignore = "true" in the browser's console: that browser sends nothing from then on.
Updated · This page as Markdown · Something unclear? [email protected]