Documentation menu

Writing monitors

A Keybeat monitor is one Playwright Test spec file. If you have written a Playwright test before, you already know how to write a monitor. This page covers the rules that are specific to Keybeat.

The rules

RuleDetail
One fileEach monitor is a single spec file, TypeScript (.ts) or JavaScript (.js). It cannot import other local files.
At least one testThe file must contain at least one test().
SizeAt most 100 KB.
Libraries@playwright/test, otpauth and Node.js built-in modules. No npm installs.
BrowserChromium only, headless.
Time limit60 seconds per run.
ConfigKeybeat supplies the Playwright config. You do not upload a playwright.config.ts.

You can check a script without running it with POST /v1/monitors/validate (or the validate_script MCP tool). Validation is static: it checks that the script parses, contains a test, is within the size limit and imports nothing but @playwright/test, otpauth and Node.js built-in modules (any other import is rejected, as is importing a local file). It does not open your site. keybeat deploy runs the same validation and deploys nothing if one script is invalid.

How Keybeat runs your spec

Every run uses the same settings, both in the cloud and in npx keybeat test:

  • Chromium, headless
  • workers: 1 and retries: 0
  • trace: retain-on-failure
  • screenshot: only-on-failure
  • 60 second run timeout

Keybeat does not retry inside the run. Instead, when a scheduled run fails, Keybeat starts a fresh run from a different region at once, and alerts only if that also fails. See Alerts.

Each run records the duration and status of every step, plus stdout and stderr. Failed runs also keep the Playwright trace and a final screenshot. A trace records what the browser did, including values typed into the page, so it can contain secrets: artifact links are only given to members of your organization, and they expire after a few minutes. Runs and artifacts are kept for 30 days on paid plans and 7 days on the free plan.

A good monitor

keybeat/checkout.spec.ts
import { test, expect } from '@playwright/test';

test('checkout reaches payment', async ({ page }) => {
  await test.step('open product page', async () => {
    await page.goto('https://shop.example.com/products/t-shirt');
    await expect(page.getByRole('heading', { name: 'T-shirt' })).toBeVisible();
  });

  await test.step('add to cart', async () => {
    await page.getByRole('button', { name: 'Add to cart' }).click();
    await expect(page.getByTestId('cart-count')).toHaveText('1');
  });

  await test.step('start checkout', async () => {
    await page.getByRole('link', { name: 'Checkout' }).click();
    await expect(page).toHaveURL(/\/checkout/);
    await expect(page.getByRole('heading', { name: 'Payment' })).toBeVisible();
  });
});

Tips:

  • Use test.step(). Steps appear in run results as test title > step title with their own timings, so a failure tells you which stage broke.
  • Assert outcomes, not just clicks. Finish each step with an expect that proves the step worked.
  • Prefer role and label locators (getByRole, getByLabel, getByTestId) over CSS selectors. They survive cosmetic changes.
  • Stay well under 60 seconds. Aim for under 20 seconds. Slow pages are reported by the slowness detection anyway.
  • Do not create real orders or charges. Stop before payment, or use a dedicated test account, a test product or a full discount code that your backend recognises.
  • Use a dedicated monitoring account so its activity is easy to filter out of analytics and easy to revoke.
  • One flow per monitor. Several small monitors give clearer alerts than one long one.

You can use test.use() in the file for per-file options such as viewport, locale or timezone.

The 60 second limit

A run has 60 seconds. Keybeat stops a run that goes past the limit and reports it as failed with a timeout message. Timeouts count as failures, so a scheduled run that times out is retried from another region, and if the retry also times out you are alerted.

The time that counts towards slowness detection is the Playwright test duration, not the time it takes to start the machine.

Environment variables and secrets

Each monitor can have its own environment variables, available to the spec as process.env.NAME.

  • Names must match [A-Z_][A-Z0-9_]*, for example LOGIN_EMAIL or TOTP_SECRET.
  • Values are encrypted at rest and are write only. Neither the API, the CLI nor the dashboard ever shows them again. You can list names only.
  • Every value is replaced with *** in logs, error messages and step titles.

Set them with the CLI:

Shell
npx keybeat env set login [email protected] LOGIN_PASSWORD='s3cret'
npx keybeat env list login
npx keybeat env unset login LOGIN_PASSWORD

Or with the API:

Shell
curl -X PUT https://api.keybeat.dev/v1/monitors/login/env \
  -H "Authorization: Bearer $KEYBEAT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "set": { "LOGIN_PASSWORD": "s3cret" }, "unset": ["OLD_TOKEN"] }'

When you run npx keybeat test locally, the spec reads variables from your own shell environment. Cloud secrets are never downloaded.

Logging in with two factor authentication

Keybeat supports TOTP codes (the six digit codes from authenticator apps) through the preinstalled otpauth library. When you enable 2FA for the monitoring account, save the setup secret (the base32 string behind the QR code) as an environment variable.

keybeat/login-2fa.spec.ts
import { test, expect } from '@playwright/test';
import * as OTPAuth from 'otpauth';

test('login with 2FA', async ({ page }) => {
  await test.step('enter password', async () => {
    await page.goto('https://app.example.com/login');
    await page.getByLabel('Email').fill(process.env.LOGIN_EMAIL!);
    await page.getByLabel('Password').fill(process.env.LOGIN_PASSWORD!);
    await page.getByRole('button', { name: 'Sign in' }).click();
  });

  await test.step('enter TOTP code', async () => {
    const totp = new OTPAuth.TOTP({
      secret: OTPAuth.Secret.fromBase32(process.env.TOTP_SECRET!),
      algorithm: 'SHA1',
      digits: 6,
      period: 30,
    });
    await page.getByLabel('Authentication code').fill(totp.generate());
    await page.getByRole('button', { name: 'Verify' }).click();
  });

  await test.step('see the dashboard', async () => {
    await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
  });
});
Shell
npx keybeat env set login-2fa [email protected] LOGIN_PASSWORD='...' TOTP_SECRET=JBSWY3DPEHPK3PXP

Keybeat does not provide test email inboxes or SMS numbers, so flows that need an emailed code or magic link cannot be monitored end to end in v1.

What the runner blocks

Monitors run on isolated, single use machines. To prevent abuse, the runner drops traffic to:

  • private networks (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and IPv6 private ranges)
  • loopback (127.0.0.0/8, ::1)
  • link-local addresses, including cloud metadata endpoints such as 169.254.169.254
  • carrier-grade NAT (100.64.0.0/10)
  • Keybeat's own private network

Each run is also capped at 2,000 requests and 300 MB transferred.

In practice: monitor public URLs only. You cannot monitor localhost, a staging server on a VPN, or hosts that resolve to private addresses. Test those locally with npx keybeat test.

Identifying and allowlisting Keybeat traffic

Keybeat's browser identifies itself. The user agent is the normal Chromium user agent followed by:

Text
Keybeat/1.0 (+https://keybeat.dev/bot)

Keybeat does not use static IP addresses in v1, so do not allowlist by IP. Instead, every request the monitor's browser makes carries a secret header unique to your organization:

HTTP
X-Keybeat-Token: <your organization's allowlist token>

Use it to let monitors through bot protection, rate limits, CAPTCHAs or maintenance pages. Find the token in the dashboard. You can rotate it at any time with POST /v1/org/allowlist-token/rotate, after which new runs send the new value.

The header is sent on every request the browser makes, including requests to third party hosts your page loads (analytics, fonts, CDNs). Treat it as a way to recognise Keybeat traffic, not as an authentication credential, and rotate it if you think it has leaked.

Example: a Cloudflare WAF custom rule that skips bot checks for Keybeat.

Text
Expression:  (http.request.headers["x-keybeat-token"][0] eq "<your token>")
Action:      Skip (bot fight mode, rate limiting rules)

Example: nginx, exempting Keybeat from a rate limit.

Text
map $http_x_keybeat_token $limit_key {
    "<your token>"  "";
    default         $binary_remote_addr;
}
limit_req_zone $limit_key zone=site:10m rate=10r/s;

If you run a site that receives Keybeat traffic you did not set up, see keybeat.dev/bot.