/tools/peepless/reference/Folio 4 of 7ReferenceDaybook of peepless 1.0.0-rc.2Days kept in UTC
4.0

Reference

Two halves, both generated when the site is built. The HTTP half is rendered from openapi.yaml, the contract for everything that crosses the network, and its examples are the ones the tests replay. The functions are read from the package's own TypeScript source, doc comments included.

Jump to POST /api/peepless, GET /api/peepless/stats, start(), createHandler(), readCounts() or testStore().

4.1

POST /api/peepless

Count one page view, engaged visit or event.

Sent by the client with navigator.sendBeacon as a plain-text string, so the browser needs no CORS preflight; the body is JSON either way, and the Content-Type is not checked.

The answer carries nothing a client needs: a bot, a beacon over the rate limit and a counted beacon all get 204, so a bot learns nothing from the reply. Errors have a small JSON body for whoever is debugging with curl.

Nothing in the request is stored. The fields become counter names (docs/counters.md) and are forgotten; the User-Agent is read only to drop bots, the address only keys this minute's in-memory rate limit, and the country comes from the host's geo header.

Any method other than POST and OPTIONS answers 405 with Allow: POST, OPTIONS.

Parameters

NameInRequiredMeaning
OriginheaderYesThe page's origin, set by the browser. It must be one of the project's origins, or the same with www. added or removed. Anything else answers 403.

Body

Everything the browser sends. Nothing here identifies a person: no id, cookie, URL, path or time. The client sends visit, ref and via only on the first page of a visit, and route only when it was given routes.

FieldTypeRequiredMeaning
projectstringYesThe project's slug, a key of the handler's projects. (matches ^[a-z0-9][a-z0-9-]{0,63}$)
eventstringYespageview, human (an engaged visit: the first real input, or 10 seconds on screen, once per visit), or one of the project's own events, which match ^[a-z][a-z0-9_]{0,39}$.
visitboolean (always true)NoOn a page view, the first page of a visit from another site or from none. Absent otherwise.
refstringNoOn a visit, the referring site's hostname (never a path), or "" for none. (at most 253 characters)
routestringNoOn a page view, the page-type pattern the path matched (/blog/*, /posts/[id]), or /_other for none. Never the path itself. One the server doesn't list counts as page:other. (at most 100 characters)
viastringNoOn a visit that arrived with ?ref= (or ?utm_source=), when the client was given campaigns: the tag if it is listed there, else other. The raw value never leaves the browser. The server counts via:<tag> for a tag the project lists and via:other for anything else, and only for projects with campaigns. (at most 40 characters)

Responses

StatusWhen
204Counted, or dropped without saying so (a bot's User-Agent, or over the rate limit).
400The body isn't a JSON object, or its event isn't one this project counts.
403The Origin isn't one of the project's origins.
404The server has no project by that name.
413The body is over 1 KB (by Content-Length, or once read).
500The store failed. The details go to the server's log, never into the answer.

Examples

Each row is sent to the real handler by src/openapi.test.ts on every check, and must answer this status and count exactly these counters.

ExampleBodyAnswerCounted
The first page of a visit, from a search engine{"project":"my-app","event":"pageview","visit":true,"ref":"www.google.com","route":"/blog/*"}
x-vercel-ip-country: DE
204pageview
visit
from:search
country:de
page:/blog/*
A visit with no referrer, on a host that sends no country{"project":"my-app","event":"pageview","visit":true,"ref":""}204pageview
visit
from:direct
country:xx
A later page of the same visit, on a page type the server doesn't list{"project":"my-app","event":"pageview","route":"/_other"}204pageview
page:other
A visit from a link tagged ?ref=newsletter, a tag the project lists{"project":"my-app","event":"pageview","visit":true,"ref":"","via":"newsletter"}204pageview
visit
from:direct
country:xx
via:newsletter
A tag the server doesn't list counts as other, and is never stored{"project":"my-app","event":"pageview","visit":true,"ref":"","via":"spring-sale"}204pageview
visit
from:direct
country:xx
via:other
The visit's first real input, or 10 seconds on screen{"project":"my-app","event":"human"}204human
One of the project's own events{"project":"my-app","event":"exported"}204exported
Fields the server doesn't know are ignored{"project":"my-app","event":"human","added_later":1}204human
A crawler, dropped without saying so{"project":"my-app","event":"pageview"}
user-agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
204nothing
An event the project doesn't list{"project":"my-app","event":"deleted"}400nothing
A body that isn't a JSON objecthello400nothing
A beacon from another site{"project":"my-app","event":"human"}
origin: https://elsewhere.test
403nothing
A project the server doesn't have{"project":"other-app","event":"human"}404nothing
A body over 1 KB, refused by its Content-Length before it is read{"project":"my-app","event":"human"}
content-length: 5000
413nothing
The database refused the write{"project":"my-app","event":"human"}500nothing
4.2

OPTIONS /api/peepless

CORS preflight, for a fetch-based client. sendBeacon never sends one.

Responses

StatusWhen
204Allowed.
4.3

GET /api/peepless/stats

A project's numbers for a range of UTC days.

Reads the project's daily totals through the store's read and answers them as a Summary, the same object summarize returns, with the project and range added.

A wrong token and a missing one get the same 401, checked before anything else, so a caller without the token learns nothing about which projects exist.

Any method other than GET answers 405 with Allow: GET. Serve this on its own path, never the beacon's. It has no CORS headers: it is for a server (yours, a stats page's, a dashboard's), and its token never goes to a browser.

Send Authorization: Bearer <token>. The token given to createStatsHandler. A long random secret, never the database key.

Parameters

NameInRequiredMeaning
projectqueryYes e.g. my-app
sincequeryNoThe first UTC day, inclusive. Default 29 days before until. e.g. 2026-12-01
untilqueryNoThe last UTC day, inclusive. Default today (UTC). At most 366 days after since. e.g. 2026-12-03

Responses

StatusWhen
200The numbers.
400No valid project, or a range that isn't two UTC days in order and at most 366 days long.
401The token is missing or wrong.
500The store failed. The details go to the server's log, never into the answer.
503The server has no token of at least 16 characters, so stats are off.

Examples

Replayed against the real handler by src/openapi.test.ts.

ExampleQueryAnswer
Three days of numbers?project=my-app&since=2026-12-01&until=2026-12-03200
No token?project=my-app401
A wrong token, answered the same way as none?project=my-app401
A range over 366 days?project=my-app&since=2025-01-01&until=2026-12-01400
The database refused the read?project=my-app500
The server was given no token, so stats are off?project=my-app503

A 200, exactly

{
  "project": "my-app",
  "since": "2026-12-01",
  "until": "2026-12-03",
  "pageviews": 12,
  "visits": 5,
  "humans": 3,
  "sources": {
    "direct": 2,
    "search": 3
  },
  "campaigns": {},
  "countries": {
    "de": 4,
    "xx": 1
  },
  "pages": {
    "/blog/*": 6,
    "other": 4
  },
  "events": {
    "exported": 2
  },
  "days": [
    {
      "day": "2026-12-01",
      "pageviews": 10,
      "visits": 4,
      "humans": 3
    },
    {
      "day": "2026-12-02",
      "pageviews": 0,
      "visits": 0,
      "humans": 0
    },
    {
      "day": "2026-12-03",
      "pageviews": 2,
      "visits": 1,
      "humans": 0
    }
  ]
}
FieldTypeRequiredMeaning
pageviewsintegerYes
visitsintegerYes
humansintegerYesEngaged visits: a real input, or 10 seconds on screen.
sourcesCountsYesfrom:*, by source key.
campaignsCountsYesvia:*, by campaign tag. Empty for a project without campaigns.
countriesCountsYescountry:*, by lowercase country code; xx is unknown.
pagesCountsYespage:*, by route pattern, or other.
eventsCountsYesThe project's own events.
daysobject[]YesEvery day in the range, oldest first, zeros included.
4.4

Functions: peepless

From src/index.ts and the modules it re-exports, read at build time.

isOptedOut()

function
const isOptedOut: () => boolean

True when this device asked not to be counted. Kept in this site's local storage, never sent.

optIn()

function
const optIn: () => void

Count this device again after optOut() or ?peepless-ignore.

optOut()

function
const optOut: () => void

Stop counting this device, from now on and on later visits. For a privacy page's toggle.

start()

function
function start<E extends string = string>(opts: PeeplessOptions): Peepless<E>

Starts counting: a page view now (or once a prerendered page is shown) and on every client-side navigation, and one engaged visit per arrival. Call once; later calls return the first one's result. track calls made before it are sent now.

const peepless = start<'signed_up' | 'exported'>({ project: 'my-app', host: 'example.com' })
peepless.track('exported')

track()

function
function track(event: string, key?: string): void

Count a "used it" event through the counter start set up. Calls made before start are held (up to 20) and sent once it runs; off the live site they are dropped.

Peepless

type
interface Peepless<E extends string = string> {
  /** Count a "used it" event (one the counter lists for this project). With `key`, at most once per key per page load. */
  track(event: E, key?: string): void
  /** True while beacons are being sent from this page. */
  readonly counting: boolean
  /** Why nothing is being sent, or null while counting. */
  readonly reason: Reason | null
}

What start returns. E narrows track to the project's own event names.

PeeplessOptions

type
interface PeeplessOptions {
  /** The project's name as the counter knows it, e.g. "inlay": lowercase letters, digits and dashes. */
  project: string
  /**
   * The production hostname, e.g. "inlaytrace.com", or a list of them. "www." is allowed too.
   * Anywhere else (localhost, preview deployments), nothing is sent.
   */
  host: string | readonly string[]
  /**
   * Where the counts go. Default "/api/peepless", same-origin. A full URL (a Supabase
   * Edge Function, say) works too: the beacon is a plain-text POST, so no CORS preflight,
   * but a Content-Security-Policy must allow it in `connect-src`.
   */
  endpoint?: string
  /** The query parameter that opts a device out (`?name`) or back in (`?name=off`). Default "peepless-ignore". */
  ignoreParam?: string
  /**
   * Page-type patterns, the same list as the server's `routes`: "/" exact, "/docs/*" for
   * everything under /docs/, "/figures/[id]" for one dynamic segment. The first
   * match is sent; a path matching none is sent as "/_other". Leave out to send no route.
   */
  routes?: readonly string[]
  /** Count an engaged visit ("human") after this long on screen with no input. Default 10 s. */
  engagedAfterMs?: number
  /**
   * Log each beacon to the console instead of sending it, on any host (localhost too).
   * For seeing that it works before deploying; never leave it on in production.
   */
  debug?: boolean
  /**
   * Campaign tags this site counts, the same list as the server's `campaigns`, lowercase. On a
   * visit whose address has ?ref=<tag> (or ?utm_source=<tag>), a listed tag is sent and any
   * other value is sent as "other", so a referral code or an email never leaves the browser.
   */
  campaigns?: readonly string[]
  /**
   * Send nothing from a browser with Global Privacy Control on. Default false: peepless keeps
   * nothing about a person, so there is nothing for GPC to opt out of, and honoring it undercounts.
   */
  respectGPC?: boolean
  /**
   * The path this app lives under when it shares its host with another, e.g. "/tools/tipjar/"
   * beside a site at "/". A page reached from the same host but outside this path then counts
   * as a visit (with that host as its referrer), as one from another site would. Default "/":
   * only another host's referrer makes a visit. Needs the browser's default Referrer-Policy (or
   * any that sends the path on same-origin links); under `origin` every page would look like an arrival.
   */
  base?: string
}

Reason

type
type Reason = 'no-browser' | 'automated' | 'not-live' | 'no-beacon' | 'opted-out' | 'gpc' | 'debug'

Why nothing is being sent:

  • no-browser: not running in a browser (server rendering, a worker)
  • automated: navigator.webdriver is set (Playwright, Puppeteer, Selenium)
  • not-live: the page isn't on one of the hosts (localhost, a preview deployment)
  • no-beacon: the browser has no navigator.sendBeacon
  • opted-out: this device opted out, with optOut() or ?peepless-ignore
  • gpc: respectGPC: true and the browser sends Global Privacy Control
  • debug: debug: true, so each beacon is logged to the console instead
4.5

Functions: peepless/server

From src/server.ts and the modules it re-exports, read at build time.

SOURCES

value
const SOURCES: readonly Source[]

countryOf()

function
function countryOf(req: Request): string | null

The default country reader: a two-letter code from the host's geo header, lowercased, or null.

createHandler()

function
function createHandler(opts: HandlerOptions): (req: Request) => Promise<Response>

The counter endpoint. POST a beacon from peepless's client; anything else is refused. Successful and silently-dropped beacons (bots, over the limit) both answer 204, so a bot learns nothing from the reply.

createStatsHandler()

function
function createStatsHandler(opts: StatsOptions): (req: Request) => Promise<Response>

The read side over HTTP: GET ?project=my-app&since=2026-11-01&until=2026-11-30 with Authorization: Bearer <token> answers a Summary as JSON (openapi.yaml). since and until default to the last 30 days, today included. Serve it on its own path, never the beacon's: it is for your server or a stats page's server, and its token never goes to a browser.

d1Store()

function
function d1Store(db: D1Like): ReadableStore

isBot()

function
function isBot(ua: string | null | undefined): boolean

True when the User-Agent names a bot, crawler, link previewer or automation tool. Only a positive match drops a count: a missing or unusual User-Agent may be a proxy's doing, and treating it as a bot could silently stop every count.

memoryStore()

function
function memoryStore(): ReadableStore & { totals: Map<string, number> }

Counts in memory, for tests and local development. totals is "day|project|counter" → count.

postgresStore()

function
function postgresStore(query: Query): ReadableStore

readCounts()

function
async function readCounts(store: ReadableStore, query: { project: string; since: string; until: string }): Promise<CountRow[]>

Reads a project's counts for a range of UTC days (YYYY-MM-DD, both inclusive), checking the query first. Pass the rows to summarize for a report.

sourceOf()

function
function sourceOf(ref: unknown, ownHosts: readonly string[], sources: readonly Source[] = SOURCES): string

The source key for a referring hostname: "direct" when there is none or it is the site itself, "other" when no source matches.

summarize()

function
function summarize(rows: readonly CountRow[], range?: { since: string; until: string }): Summary

Turns stored rows into a report: totals, sources, campaigns, countries, pages, events and a per-day series. With range, days covers every day in it; without, the days the rows span.

supabaseStore()

function
function supabaseStore(opts: { url: string; key: string; fetch?: typeof fetch }): ReadableStore

Counts in Supabase, through peepless_add and peepless_counts in starters/supabase/schema.sql. Use the service-role or a secret key, on the server only.

CountRow

type
interface CountRow {
  /** UTC day, YYYY-MM-DD. */
  day: string
  counter: string
  count: number
}

One stored total: a counter's count for one UTC day.

D1Like

type
interface D1Like {
  prepare(sql: string): D1StatementLike
  batch(statements: D1StatementLike[]): Promise<unknown>
}

The parts of a D1 binding peepless uses, so no Cloudflare types are needed to import it.

D1StatementLike

type
interface D1StatementLike {
  bind(...values: unknown[]): D1StatementLike
  all<T = Record<string, unknown>>(): Promise<{ results: T[] }>
}

DayTotals

type
interface DayTotals {
  day: string
  pageviews: number
  visits: number
  humans: number
}

One day's headline numbers.

HandlerOptions

type
interface HandlerOptions {
  /** Projects by name, the name each client passes as `project`. */
  projects: Record<string, ProjectConfig>
  store: Store
  /** Beacons per address per project per minute before the rest are dropped. Default 60. */
  perMinute?: number
  /**
   * The visitor's two-letter country code, or null. Default: the first of
   * x-vercel-ip-country, cf-ipcountry and cloudfront-viewer-country. Pass `() => null`
   * to count no countries.
   */
  country?: (req: Request) => string | null | undefined
  /** Where a visit came from, first match wins. Default: SOURCES. */
  sources?: readonly Source[]
  /**
   * The address the rate limit keys on. Default: the first x-forwarded-for entry, then x-real-ip,
   * then cf-connecting-ip. A client can set x-forwarded-for itself on a host that passes it
   * through untouched, so name the header your host sets: on Cloudflare,
   * `(req) => req.headers.get('cf-connecting-ip')`. Return null to put everyone in one bucket.
   * The address is never stored, and the limit lives in this instance's memory.
   */
  address?: (req: Request) => string | null | undefined
  /**
   * Decides whether a User-Agent is a bot, whose beacons are dropped. Default: the built-in
   * `isBot`. Wrap it to add your own: `(ua) => isBot(ua) || /mymonitor/i.test(ua ?? '')`.
   */
  isBot?: (ua: string | null) => boolean
}

ProjectConfig

type
interface ProjectConfig {
  /** The site's origin(s), e.g. "https://example.com". Beacons from anywhere else are refused. "www." is accepted too. */
  origin: string | readonly string[]
  /** The "used it" events this project may count, e.g. ["signed_up", "exported"]. */
  events?: readonly string[]
  /** The page-type patterns the client sends (the same list as its `routes`). Anything else counts as page:other. */
  routes?: readonly string[]
  /**
   * Campaign tags this project counts as via:<tag>, from ?ref= (or ?utm_source=) on a visit,
   * e.g. ["newsletter", "launch"]. The client's `campaigns` lists the same. Any other tag counts as via:other.
   */
  campaigns?: readonly string[]
}

Query

type
type Query = (text: string, params: unknown[]) => Promise<readonly Record<string, unknown>[]>

Runs one SQL statement with $1-style parameters and resolves to its rows. Adapters:

  • pg: (text, params) => pool.query(text, params).then((r) => r.rows)
  • postgres.js: (text, params) => sql.unsafe(text, params)
  • Neon: (text, params) => neon(process.env.DATABASE_URL).query(text, params)

ReadableStore

type
interface ReadableStore extends Store {
  /** Every count for the project from `since` to `until`, both whole UTC days, inclusive. */
  read(project: string, since: string, until: string): Promise<CountRow[]>
}

A store you can also read back from: what readCounts and createStatsHandler need.

Source

type
interface Source {
  key: string
  /** "example.com" matches it and its subdomains; "google.*" matches google.com, google.co.uk and so on. */
  hosts: readonly string[]
}

StatsOptions

type
interface StatsOptions {
  store: ReadableStore
  /**
   * The bearer token a reader must send: a long random secret (at least 16 characters),
   * not the database key. Until one is set, every request gets 503.
   */
  token: string | undefined
}

Store

type
interface Store {
  /** Add one to each counter's total for this UTC day. */
  add(project: string, counters: readonly string[], day: string): Promise<void>
}

Summary

type
interface Summary {
  pageviews: number
  visits: number
  /** Engaged visits: a real input, or 10 s on screen. */
  humans: number
  /** `from:*`, by source key ("search", "direct"), largest first. */
  sources: Record<string, number>
  /** `via:*`, by campaign tag, largest first. Empty for a project without `campaigns`. */
  campaigns: Record<string, number>
  /** `country:*`, by lowercase country code ("us", "xx" for unknown), largest first. */
  countries: Record<string, number>
  /** `page:*`, by route pattern ("/blog/*", "other"), largest first. */
  pages: Record<string, number>
  /** The project's own events, largest first. */
  events: Record<string, number>
  /** Every day in the range, oldest first, with zeros for days with nothing. */
  days: DayTotals[]
}

A report built from counter names, so nobody has to parse from: by hand.

4.6

Functions: peepless/testing

From src/testing.ts and the modules it re-exports, read at build time.

testStore()

function
async function testStore(makeStore: () => Store | Promise<Store>, opts: TestStoreOptions = {}): Promise<void>

Runs the store contract against stores from makeStore and resolves when every rule holds:

  • adds are atomic: concurrent adds of one counter all count
  • a counter named twice in one add counts once
  • an add with no counters changes nothing
  • read returns what was added, as { day: "YYYY-MM-DD", counter, count: number }, for that
project only, with since and until both inclusive

A store without read is checked for the write rules it can show without one (that adds resolve).

TestStoreOptions

type
interface TestStoreOptions {
  /** How many adds of one counter run at once in the atomicity check. Default 25. */
  concurrency?: number
}