# Product analytics for Node.js

Track server-side events from Node.js with the Pug Node SDK: explicit user attribution, profile identify, and analytics reads. Open source, self-hostable under AGPL-3.0.

Source: https://pug.sh/integrations/nodejs

For events that must be trusted (payments, server jobs, webhooks) use the Pug Node SDK. It names the user explicitly rather than inferring a browser session, and the same private key reads profiles and insights back into your own code.

- Pug Node SDK: one SDK for the server
- @pug-sh/node
- Open source: MIT SDK, AGPL-3.0 server

## Add Pug to Node.js

Four steps, start to first insight. Everything below uses the Node SDK exactly as it ships.

### 1. Install the Node SDK

A separate package from the browser one, because it does a different job: no autocapture, no ambient session, and read access on top of ingestion.

```bash
npm install @pug-sh/node
# or: pnpm add @pug-sh/node · yarn add @pug-sh/node · bun add @pug-sh/node
```

### 2. Construct one client with your private key

Create the client once per process and reuse it, since it owns the batching queue. The constructor throws unless the key starts with prv_, so a public key pasted in by mistake fails loudly at boot instead of silently dropping events.

`src/pug.ts`

```ts
import { Pug } from '@pug-sh/node'

export const pug = new Pug({
  apiKey: process.env.PUG_PRIVATE_KEY!, // prv_…: never ship this to a browser
})
```

### 3. Track the events you can’t trust a browser for

Every server call names the user, so there is no session to infer and nothing an ad blocker can drop. track() never throws (invalid input and a closed client are logged and dropped), so it is safe to call from inside a webhook handler without a try/catch.

`src/webhooks/stripe.ts`

```ts
import { pug } from '../pug'

export async function onInvoicePaid(event: StripeEvent) {
  const userId = event.data.object.metadata.userId

  pug.track(userId, 'order_completed', {
    amount: event.data.object.amount_paid / 100,
    currency: 'USD',
  })

  await pug.identify(userId, { plan: 'pro', billing_status: 'active' })
}
```

### 4. Read the data back where you need it

The private key also authorizes reads: the same profiles, activity, and insight queries the dashboard runs. Reads throw PugError with the underlying code, time out after 10 seconds, and are never retried, so the retry policy is yours; ingestion still never throws.

`src/reports.ts`

```ts
import { PugError } from '@pug-sh/node'
import { pug } from './pug'

try {
  const profile = await pug.profiles.getByExternalId('user_123')

  for await (const p of pug.profiles.list()) {
    console.log(p.externalId)
  }
} catch (err) {
  if (err instanceof PugError) console.error(err.code, err.message)
}
```

## What to watch for in Node.js

The specifics that decide whether the numbers you see are the numbers that happened.

### A private key is not a public key

The browser key (pub_…) is write-scoped and meant to be shipped. The server key (prv_…) additionally authorizes reads of every profile and insight in the project. It belongs in server environment variables only, and the SDK refuses to start without one.

### Use the same id as the browser

Server events land on the same profile as client events when both name the same user id, the one you pass to identify() in the browser. Get that right and one person’s client and server activity share a single timeline.

### Ingestion never throws, reads do

track() and identify() log and drop rather than propagate, so analytics can never take down a request handler. Read methods run in your control flow and throw PugError carrying the Connect code and cause.

### Not on Node? Go, Ruby, or HTTP

Go and Ruby have server SDKs of their own, with the same private key and the same never-fail tracking. Every SDK is a convenience layer over the same Connect services your backend can call directly, so Python, or anything else that can POST JSON, reaches the identical endpoints.

## Report AI crawlers from Express. Crawlers don’t run JavaScript, so only your server sees them.

Install @pug-sh/crawlers, a separate package with no dependencies, and mount its Express middleware with your private key. For a request from a known crawler, such as GPTBot, ClaudeBot, or ChatGPT-User, it sends one report to Pug after the response finishes, with the status code; your visitors’ requests never leave your server. With plain node:http, call the middleware at the start of your handler as middleware(req, res). Pug checks the IP against the ranges the operator publishes, so a scraper borrowing GPTBot’s name reads as unverified. Behind a CDN your server sees the CDN’s address, so pass getIP to read the client IP header. Each report counts toward your usage as a crawler_request event.

`src/app.ts`

```ts
import { crawlers } from '@pug-sh/crawlers'

app.use(crawlers({ apiKey: process.env.PUG_PRIVATE_KEY }).express())
```

[AI crawler setup in the docs](https://docs.pug.sh/crawlers/)

## Product analytics in your Node.js app

### Trusted server events

track() names the user explicitly (no ambient browser session), so payments, webhooks, and jobs land on the right profile.

### Profile traits from your backend

identify() writes plan, role, or billing state from the one place that knows them.

### Reads as well as writes

The same private key reads profiles, activity, and the insight queries the dashboard runs, from inside your own backend logic.

### Pairs with the Web SDK

Client autocapture and authoritative server events share one timeline per person when both name the same user.

## Read it in the docs

The Node SDK reference goes deeper than a setup page can: every option, every event, and the edge cases.

- [Server-side reads](https://docs.pug.sh/sdks/node/#server-side-reads): The profiles, activity, and insights namespaces, method by method.
- [Visitor location](https://docs.pug.sh/sdks/node/#visitor-location): Passing the visitor’s country and city, since the server adds no geo to these events.
- [Authentication](https://docs.pug.sh/get-started/authentication/): Issuing keys, what each scope allows, and rotation.
- [API reference](https://docs.pug.sh/api/): Field-by-field schemas for the events, profiles, and insights services.
- [HTTP API](https://docs.pug.sh/sdks/http/): Sending events and identifies from any language by POSTing JSON, without an SDK.
- [AI crawler reports](https://docs.pug.sh/crawlers/): The Express and node:http adapters, getIP behind a CDN, and what each report sends.

* [Start from the beginning](https://docs.pug.sh/get-started/)
* [See all SDKs](https://pug.sh/sdks)

## Pug + Node.js: common questions

### When should I use the Node SDK instead of the Web SDK?

Use the Node SDK for events that must be trustworthy or happen off the browser: completed payments, subscription changes, background jobs, webhooks. Use the Web SDK for in-page autocapture. They write to the same profile, so a person’s client and server events live on one timeline.

### Does the Node SDK autocapture?

No. Autocapture is a browser feature. On the server you call track() explicitly with the user id and event name. The server adds no geo or user agent to these events either, so pass the visitor’s country and city with track()’s location option.

### Can the Node SDK read data back?

Yes. With a private key it exposes profiles (get, get by external id, and an auto-paginating list), activity (feed, event explorer, heatmap, profile stats), and insights (the same query spec the dashboard uses), so Pug data can drive your own backend logic.

### Will a failed analytics call break my request handler?

No. track() and identify() never throw: invalid input, a closed client, and transport failures are logged and dropped. Only the read methods throw, and they throw PugError carrying the Connect code, because those run inside your control flow and you need to decide what to do.

### What if my backend isn’t Node?

Go and Ruby have SDKs of their own, on the same model. Anywhere else, call the same Connect services directly over HTTP with your private key. The SDKs are convenience wrappers, not a gate: any runtime that can POST JSON can send events and run reads.
