@pug-sh/node sends events from your Node.js backend and reads analytics
back - profiles, activity and insights. It authenticates with your private
key (prv_...), so it belongs on the server only. It follows the
same model as every Pug SDK with one exception: a server has no ambient
user or session to reset, so you name the distinctId on each call instead.
Install
npm install @pug-sh/node
# or: pnpm add @pug-sh/node | yarn add @pug-sh/node | bun add @pug-sh/nodeThe package is ESM-only - require() can’t load it - and needs Node.js 18+.
Import the Pug class:
import { Pug, PugError } from '@pug-sh/node'Keep the private key in an environment variable or a secret store, never in code shipped to a browser or app.
Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in Install with AI.
Add Pug product analytics to this Node backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/node/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Install @pug-sh/node. It is ESM and needs Node 18+. 2. Construct one Pug instance at boot and reuse it across requests - do not build one per request. Its apiKey is the private key (prv_...), read from an environment variable, and it must never be imported into client-side code. 3. Remember the argument order: pug.track(distinctId, kind, props?, options?). The distinctId comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. 4. Add track calls for the three or four state changes you identified. 5. Call identify() when a user record is created or changes materially, not on every request. 6. Await pug.close() in the graceful-shutdown path so queued events and identifies flush, and wire an onError handler so dropped events and identifies are logged rather than lost. Name events from the catalog before you invent one. The Node SDK checks 114 of the 127 well-known events against their schemas when track() runs, not at compile time: a property of the wrong type drops the whole event, and one named as the catalog spells it (product_id) rather than in camelCase (productId) is sent as a custom property instead. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, take property names - in camelCase - and types from that page, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no reset() or destroy() on the server SDK, and no immediate option on track - use flush(). Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables I need to set.
Initialize
Construct a Pug instance once at boot with your private key - every other
call needs it first. Private keys live under Settings > API Keys, but one is
only shown when you create it - if you don’t have
yours, issue a new one.
import { Pug } from '@pug-sh/node'
// Construct once at boot, reuse it across requests.
const pug = new Pug({
apiKey: process.env.PUG_PRIVATE_KEY!, // prv_... - server-side only, never ship to a client
})new Pug(options) throws if apiKey is missing or doesn’t start with
prv_; after that, ingestion never throws.
| Option | Type | Default | Description |
|---|---|---|---|
apiKey |
string |
required | Private key (prv_...), sent as x-api-key. |
endpoint |
string |
https://api.pugs.dev |
Pug server origin; set it only when self-hosting. |
batch |
Partial<BatchConfig> |
maxSize 100, maxWaitMs 5000, maxQueueSize 10000 |
One queue each for events and identifies: items per request (capped at 1000), the longest an item waits before a send, and how many to hold before the oldest are dropped. |
onError |
OnError |
none | Dead-letter hook for events and identifies that couldn’t be delivered, called as (err, { events, identifies }): a permanent send failure, a queue overflow, or what close() couldn’t send. One of the two lists is always empty. |
Call await pug.close() on graceful shutdown, or before a script exits, so
nothing queued is lost: a pending send doesn’t keep the process alive. See
flush() and close().
Track events
After the distinctId, the next argument is the event name (its kind).
Any name works without a schema; well-known events
add typed properties and richer dashboards.
// distinctId (who the event is for) comes first - a server has no ambient user.
pug.track('user-123', 'order.completed', { amount: 49, currency: 'USD' })
// Well-known events get typed, validated properties.
pug.track('user-123', 'purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' })pug.track(distinctId, kind, props?, options?) takes the distinctId
first: your external ID, or an anon-... ID forwarded from the client. It
never throws and returns at once; events are validated, batched and sent in
the background, and invalid input is logged and dropped. A kind may hold only
ASCII letters, digits, _, . and -; anything else drops the event.
There is no immediate option on the server - flush explicitly instead:
await pug.flush() // send what's queued now, and wait for that attempt
await pug.close() // drain on graceful shutdown so nothing queued is lostBoth cover events and identifies, and neither guarantees delivery: after
flush() a transient failure re-queues for a later send, and by the time
close() resolves, whatever it couldn’t send has gone to onError and the log.
After close(), track() and identify() calls are dropped with a warning.
track(distinctId, kind, props?, options?) options:
| Option | Type | Description |
|---|---|---|
timestamp |
number |
Override the event time, as epoch milliseconds (e.g. Date.now()). Anything but a whole number of milliseconds from 1970 to 9999 is ignored with a warning, and the event is sent at the current time. |
sessionId |
string |
A UUID to use as this event’s session ID - otherwise the instance uses one for its lifetime. Anything but a UUID drops the event. |
location |
EventLocation |
Where the visitor is. Without it a server event carries no geo at all. See Visitor location. |
Property values are JSON values: a safe integer is sent as an int and any
other number as a double, a string is cut to 1024 bytes with a warning, an
object or array becomes a JSON string, and null or undefined is omitted. A
Date is sent as a timestamp and a bigint as an int, though TypeScript
rejects both. NaN, Infinity and anything else that can’t be sent are
dropped with a warning - the property, not the event.
A well-known event’s props are checked against
its schema before the event is queued, under the fields’ camelCase names
(productId), not the catalog’s product_id, which is sent as a custom
property without a warning; an event missing a required field is dropped. The
schema sets each field’s type, so amount: 10 is sent as a double. A
wrong-typed value, or one failing a rule such as currency needing three
uppercase letters, drops the whole event, and the log names the field
(quantity: expected int32, got string). TypeScript doesn’t catch a wrong type,
since the call falls back to the signature for custom events. Keys outside the
schema pass through as custom properties. Two field types take a particular
shape:
- int64 fields such as
sizeBytestake a safe integer. A string drops the event, and abigintworks but doesn’t compile. - Duration fields such as
positiontake{ seconds, nanos }, sent as a string like"90.5s".
track() logs and drops an event over 900 KiB, and one whose distinctId is
empty or starts with cookieless-, a prefix the server reserves; it would
reject the whole batch.
Visitor location
The server adds no geo to events sent with a private key: an event carries the
location you give it (added in 0.0.6), or none at all.
pug.track('user-123', 'purchase',
{ productId: 'sku_123', amount: 29.99, currency: 'USD' },
{ location: { country: 'DE', city: 'Berlin' } })| Field | Type | Notes |
|---|---|---|
country |
string |
ISO 3166-1 alpha-2 (DE). Case and surrounding spaces are normalized; a code Pug doesn’t recognize is dropped. |
continent, region, city, postalCode, metroCode |
string |
Sent as given, trimmed. |
timezone |
string |
IANA name (Europe/Berlin). |
latitude, longitude |
number |
Decimal degrees, -90 to 90 and -180 to 180. Sent only as a pair: one without the other is dropped. |
Each field becomes the matching $-prefixed
auto-property: city
lands as $city. It’s the only way to set an auto-property from this SDK:
props become custom properties, and one whose key starts with $ drops
the event.
A field that is absent, null or empty is skipped silently. One that looks like
a mistake - unknown key, wrong type, a country code Pug doesn’t know, a
coordinate out of range - is dropped with a warning and the rest of the event
still sends, and a location with nothing usable logs a warning.
Identify and sessions
Use a stable, unique external ID - your database user ID, not an email, which can change. Only the first identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed.
// On the first identify, pass the client's anonymous ID to merge its prior anonymous activity.
pug.identify('user-123', { email: 'user@example.com', plan: 'pro' }, {
anonymousId: 'anon-abc123',
})pug.identify(externalId, traits?, options?) never throws and returns at
once: identifies are queued and sent in batches like events, and what can’t be
delivered goes to onError. A read straight after an identify may not see it
yet.
traits must be a plain object: a string, array, Date or Map is logged and
nothing is sent, as is an externalId that is empty or starts with the
reserved cookieless- prefix, or an identify over 900 KiB. Traits travel as a
protobuf Struct, where a Date value becomes an empty object and undefined
or a bigint becomes null, overwriting the stored trait; TypeScript rejects
all three. A NaN or Infinity trait is skipped with a warning, and the rest
still goes out.
Pass { anonymousId } (must start with anon-) on the first identify to merge
a client’s prior anonymous activity into the profile, and { deviceId } to
attach a device. There is no reset() or rotate().
Sessions
The SDK uses one session ID for the instance’s lifetime; override it per call
with track(..., { sessionId }).
Auto-tracking
There is no auto-tracking: you send every event with pug.track(). The server
adds no geo or user agent to these events, so pass the visitor’s
location yourself.
Consent and privacy
The Node SDK has no consent gate and no redaction hooks: respect the visitor’s
consent choice before you call track(), and keep PII out of the properties you
pass.
Server-side reads
The private key also authorizes reads - the insights, profiles and activity
data the dashboard shows. Reads throw PugError and are never retried.
Ingestion (track() / identify()) still never throws.
import { PugError } from '@pug-sh/node'
try {
// Look up a profile by your external ID.
const profile = await pug.profiles.getByExternalId('user-123')
// Auto-paginating async iterator over every matching profile.
for await (const p of pug.profiles.list()) {
console.log(p.externalId)
}
// Run an insights query - the same spec the dashboard uses.
const result = await pug.insights.query({ /* spec, timeRange, granularity */ })
} catch (err) {
// Reads throw; ingestion (track/identify) never does.
if (err instanceof PugError) console.error(err.code, err.message)
}| Namespace | Methods |
|---|---|
pug.profiles |
get(id, opts?), getByExternalId(externalId, opts?), delete(id), list(req?): an auto-paginating async iterator |
pug.activity |
feed, eventExplorer, heatmap, profileSessions, profileStats, filterSchema, propertyValues |
pug.insights |
query, segmentUsers, filterSchema, propertyValues |
profiles.get and getByExternalId return the profile itself. Every read times
out after 10 seconds, with no option to change it, and a list() loop is one
streamed request: it throws once the whole loop, your loop body included, passes
10 seconds.
A PugError carries the Connect code as a number, as in the Code enum from
@connectrpc/connect (5 is not_found, 4 is deadline_exceeded; see the
error model), and the underlying error as cause.
Reads leave out traffic tagged as a bot at ingest: web-SDK events from crawler
user agents and datacenter networks. Events from this SDK are never tagged. Set
includeBots: true (0.0.7+) to count bot traffic - profiles.get and
getByExternalId take it in their second argument, and profiles.list,
insights.query (on its spec) and the activity feed, eventExplorer,
heatmap, profileSessions and profileStats take it in the request:
const profile = await pug.profiles.getByExternalId('user-123', { includeBots: true })
const { sessions } = await pug.activity.profileSessions({ distinctId: 'user-123', includeBots: true })The request and response shapes match the shared.* Connect services - see the
API reference for field-by-field schemas. From a backend without an SDK,
call those services directly with your private key (see
Authentication).
Upgrading
v0.1.0
identify()returnsvoidand queues, where it used to return a promise and send right away. The identify goes out with the next batch,flush()orclose(), throughBatchIdentifyor, on a server without it, oneIdentifycall each. Drop any.then()on its result;await pug.identify(...)still compiles but no longer waits for the send.onErrorgets(err, { events, identifies })instead of(err, events). Failed identifies retry on transient errors and reach it like events, where 0.0.7 only logged them.- An event or identify over 900 KiB is dropped at the call with a log.
- A
NaNorInfinitytrait is skipped with a warning; 0.0.7 sent it and the server stored it as a string.
v0.0.7
Nothing here breaks compilation, but input that 0.0.6 altered and sent anyway
is now dropped with a [Pug SDK] error, so check your logs after upgrading.
- A well-known event with a wrong-typed prop is dropped, where 0.0.6 sent it without that field under an “unsupported scalar type” warning.
identify()needs plain-object traits. A string, array,DateorMapused to go out as empty traits ({}); now the call logs and sends nothing.- int64 and Duration props are sent. 0.0.6 skipped a number in an int64
field such as
sizeBytes, and skipped a Duration such asposition, or dropped the whole event when itssecondswas a number. - A
distinctIdstarting withcookieless-is dropped, since the server rejects the whole batch over one. - Server-side drops are logged. Events the server refuses from a batch it otherwise accepts now log a warning with the reasons.
includeBotsis new on reads. Reads leave bot-tagged traffic out whichever SDK version you run; 0.0.7 is the first that can ask for it back.