Node.js
@stancelens/node: send events and read stats from Node 18+, Bun, Deno and edge runtimes.
Built on fetch, with no runtime dependencies. Send events from your backend, record server-side page views and read your stats through the REST API. Need one client for browser and server code? See the JavaScript SDK.
Install from source
@stancelens/node isn't on npm yet. Build a tarball in a checkout of the Stancelens repository and install it in your app:
cd stancelens/packages/node
bun install && bun run build && bun pm pack # writes stancelens-node-0.1.0.tgz
# in your app
npm install /path/to/stancelens/packages/node/stancelens-node-0.1.0.tgzYou need an API key from an owner or admin of the site (Account → API keys). Keep it on the server: it can write events and erase users.
Track events
import { Stancelens } from "@stancelens/node";
const stancelens = new Stancelens({ apiKey: process.env.STANCELENS_API_KEY!, siteId: "SITE_ID" });
stancelens.track("signup", { uid: "user_42", props: { plan: "pro" } });
stancelens.identify("user_42", { company: "Acme" }, { vid: anonIdFromBrowser }); // vid optional
stancelens.revenue("purchase", 49, "USD", { uid: "user_42" });
stancelens.pageview({ url: "https://example.com/pricing", ip, ua });These calls only queue the event, and throw a TypeError for a bad one (no name, or no uid, vid or ip). Batches of up to 100 are sent when flushAt events are queued or every flushInterval ms. The timer starts with the first event and doesn't keep the process alive.
await stancelens.flush()sends everything queued and never rejects; delivery errors go toonError.await stancelens.shutdown()flushes, stops the timer and drops later events.- On Node and Bun the client also flushes on
beforeExit, which doesn't run onprocess.exit()or signals, so callshutdown()in your SIGTERM handler.flushOnExit: falseskips the hook.
Identity
- Every event needs
uid,vidorip. vid, an anonymous visitor ID you manage, is used as given.- Without
vidbut withip(and ideallyua), the server derives the same daily-rotating anonymous ID the browser script uses. IP addresses aren't stored. - With only
uid, the uid is also sent as the visitor ID, so a user's events stay together.
Event options
uid, vid, url, path, referrer, title, props (strings, numbers, booleans, null; up to 50 keys), revenue (number or { amount, currency }), timestamp (Date or epoch ms; up to 30 days back), ip, ua, language, timezone (IANA name, used for the country estimate; the IP isn't), duration (ms), appVersion. Events are sent with platform: "server" and sdk: "stancelens-node/<version>". A page view that carries a browser's user agent is recorded as web, so server-side page views count with browser traffic; everything else is server. With ua set, the server fills in browser, OS and device, and drops known bots.
Options
new Stancelens({
apiKey, siteId,
host: "https://stancelens.com",
flushAt: 20,
flushInterval: 5000, // ms; 0 turns the timer off
maxQueueSize: 10_000, // further events are dropped and counted
maxRetries: 3, // network errors, 408, 429, 5xx; honours Retry-After
timeout: 10_000, // ms per request
fetch, // custom fetch
onError: (error, events) => {}, // undelivered events; default console.warn
disabled: false, // accept calls, send nothing
flushOnExit: true,
});stancelens.dropped counts events that weren't stored (queue full, sent after shutdown, failed after retries, or refused by the server); stancelens.queued is the number waiting.
Edge and serverless
Timers don't run between requests on Cloudflare Workers or Vercel Edge, and serverless functions may freeze after responding. Flush before the request ends: ctx.waitUntil(stancelens.flush()) on Workers, await stancelens.flush() at the end of a Lambda handler. Creating the client at module scope is fine; no timer starts until the first event.
Read stats
const agg = await stancelens.stats.aggregate({ period: "7d", metrics: ["visitors", "revenue"] });
agg.results.visitors?.value;
await stancelens.stats.timeseries({ period: "30d", interval: "day" });
await stancelens.stats.breakdown("path", { limit: 10, page: 1, filters: { country: ["US", "DE"] } });
await stancelens.stats.breakdown("props.plan", { from: "2026-01-01", to: "2026-01-31" });
await stancelens.stats.realtime();
await stancelens.stats.export({ period: "today", filters: { user_id: "user_42" } }); // raw events
await stancelens.stats.deleteUser("user_42"); // erasure, owner or admin key- Non-2xx answers reject with
StancelensError, carryingstatusand the parsedbody;statusis 0 when the server couldn't be reached. period:today,yesterday,24h,7d,30d(server default),mtd,lastmonth,90d,6mo,12mo,ytd,all, in the site timezone (details).from/to("YYYY-MM-DD", or a Date, which sends its UTC calendar day; inclusive) select a custom range of site-local days.filters:{ dimension: value | value[] }. A list means any of;!excludes,~means contains. Dimensions are the API filter dimensions.
Server-side page views
Each adapter records a page view for a successful (2xx) GET that responds with text/html and isn't a browser prefetch, with the visitor's IP, user agent, referrer and language. It never throws into the request. Use it instead of the browser script on those pages, not with it, or page views are counted twice. Every adapter takes getUserId(req), skip(req) and trustProxy.
import { expressMiddleware, fastifyPlugin, honoMiddleware } from "@stancelens/node";
// Express (or connect, or node:http)
app.use(expressMiddleware(stancelens, { getUserId: (req) => req.user?.id }));
// Fastify: applies to every route
await app.register(fastifyPlugin(stancelens));
// Hono: pass the IP for your runtime; on edge runtimes also flush with waitUntil
app.use(honoMiddleware(stancelens, {
getIp: (c) => c.req.header("cf-connecting-ip"),
flushWithWaitUntil: true,
}));Express and Fastify use their own req.ip, so their trust proxy settings apply. Hono has no portable way to read the client IP: without getIp (or trustProxy) and without a user ID, the Hono adapter records nothing.