---
title: "@togohq/sdk-node"
description: "Every method and option of the server SDK, and how to make sure events leave before the process stops."
canonical: "https://www-stage.togohq.ai/docs/reference/sdk-node"
applies_to: "@togohq/sdk-node 2.x"
updated: "2026-11-24T00:00:00Z"
---

# @togohq/sdk-node

Every method and option of the server SDK, and how to make sure events leave before the process stops.

```bash
npm install @togohq/sdk-node
```

Node 20 or later, zero runtime dependencies. Create **one client per process**, shared by every
request. Nothing on the client throws: a problem is logged as `[togo] …` and the event is retried
or dropped. To send the drops to your error tracker, pass [`onError`](#onerror). A guide to using it: [Node.js and serverless](/docs/node).

## `init(options)`

```ts
import { init } from '@togohq/sdk-node';

const analytics = init({ writeKey: process.env.TOGO_WRITE_KEY! });
```

## Options

| Option                 | Default                    | What it does                                                                                                   |
| ---------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `writeKey`             | —                          | Required. `togo_pkt_…` (test) or `togo_pkl_…` (live)                                                           |
| `endpoint`             | `https://in.togohq.ai`     | Where events are sent                                                                                          |
| `assignEndpoint`       | `https://assign.togohq.ai` | Where experiment assignments come from                                                                         |
| `batchSize`            | `100`                      | Events per request, 100 to 500                                                                                 |
| `flushIntervalSeconds` | `10`                       | How long an event may wait before it is sent, 10 to 60 seconds                                                 |
| `maxQueueSize`         | `10000`                    | Events held in memory while Togo is unreachable, with 32 MiB; past either, the oldest are dropped and reported |
| `defaultProperties`    | —                          | Properties on every `track()` event, such as `{ service: 'billing' }`                                          |
| `appVersion`           | —                          | Your service's version, such as `'2.4.0'`. Read as `$app_version`, so a chart splits by release                |
| `appBuild`             | —                          | Your service's build number, such as `'412'`. Read as `$app_build`                                             |
| `onError`              | —                          | Called for every event, or part of one, that will not be recorded. See [`onError`](#onerror)                   |

A `batchSize` or `flushIntervalSeconds` outside its range is moved into it, with a warning in your
logs. To send an event at once, `await analytics.flush()` after it rather than lowering either.

`appVersion` and `appBuild` are each 1–64 characters; a value that is not is left out, and the SDK
logs one error saying which. Neither is sent unless you set it.

`defaultProperties` is fixed when the client is created, because a client shared by every request
must not carry one request's value onto the next. An event's own value for the same key wins, and
the SDK logs one error for the collision.

Property names starting with `$` are reserved for Togo
([Reserved properties](/docs/reference/reserved-properties)), and a name longer than 255 characters,
or holding a control character or an email address, is one Togo cannot use. The SDK reports either
through [`onError`](#onerror) and logs a `[togo]` error naming it. With a live key it drops the
property from a `track()` call, from `defaultProperties` and from `setPersonProperties()`, and sends
the rest; with a test key it sends the property as well, so `verify_tracking` reports it with its
fix — the same rule as the [browser SDK](/docs/reference/sdk-browser#reserved-names).

## The person argument

Every call names who it is about, with at least one of:

| Field         | What it is                                                                        |
| ------------- | --------------------------------------------------------------------------------- |
| `userId`      | Your id for the signed-in user — the same one the browser passes to `identify()`  |
| `anonymousId` | The browser's anonymous id, forwarded, for a visitor who has not signed in        |
| `sessionId`   | Optional. Pass only the browser's `getSessionId()`, so the event joins that visit |

An event with neither `userId` nor `anonymousId` is dropped with an error. Server events carry no
device, browser or location.

## `track(eventName, properties, person)`

```ts
analytics.track('order_paid', { plan: 'pro' }, { userId: user.id });
```

Returns the event's `eventId`, or `undefined` when nothing was queued — no person named, a refused
name, a malformed write key or one already rejected, after `shutdown()`, or a full queue. The key
is checked in the background, so a call made before a rejection comes back still returns an id, and
the rejection drops that event. An id means the event was queued, not that it arrived. A test
passes these ids to [`verify_tracking_by_event_ids`](/docs/reference/mcp-tools#verify_tracking_by_event_ids)
after `await analytics.flush()`.

## `setPersonProperties(ops, person)`

```ts
analytics.setPersonProperties({ email: user.email, set: { plan: 'pro' } }, { userId: user.id });
```

`email`, `name`, `set`, `setOnce` and `unset`, as in the
browser ([Set person properties](/docs/guides/person-properties)): `email` and `name` set the reserved
person properties `$email` and `$name`, and only defined keys are kept in the rest. Takes `userId` or `anonymousId`, not `sessionId`.
Returns the profile write's `eventId`, or `undefined` when nothing was queued — an empty call, no
person named, a malformed or already-rejected write key, after `shutdown()`, or a full queue.

## `getExperiment(name, person)`

```ts
const result = await analytics.getExperiment('checkout_cta', { userId: user.id });

if (result.variant === 'one_click') sendOneClickEmail();
else sendCurrentEmail();
```

Which variant of an experiment this person gets, named by `userId`, `anonymousId` or both. It
returns the same result as the [browser SDK's](/docs/reference/sdk-browser#getexperimentname),
resolves within 800 ms and never rejects; with neither id it resolves `unavailable`. Always keep a
default path, because `variant` is `null` when there is no answer.

A participant's first call sends `$experiment_entered`. Later server events do not carry the
variant, because a server holds nothing about a person between calls, so judge an experiment by an
event the browser sends. A `device_id` experiment answers a server with its baseline, since a server
has no device. Answers are cached in memory per person, with a test key asking every time.
[Run an A/B test](/docs/guides/experiments).

## `flush()`

`await analytics.flush()` sends everything queued now. **In a serverless function, call it before
you return**, because the platform may freeze the process as soon as the response is sent. A send
that fails on the network or with a server error is retried twice within about a second before
`flush()` resolves.

## `withFlush(handler)`

```ts
export const handler = analytics.withFlush(async (event) => {
  analytics.track('order_paid', { plan: 'pro' }, { userId: event.userId });
  return { statusCode: 200 };
});
```

Returns your handler wrapped so `flush()` runs after it finishes — also when it throws. What the
handler returns or throws is passed through unchanged. Use it for every serverless handler, so no
return path can skip the flush.

Where `AWS_LAMBDA_FUNCTION_NAME`, `FUNCTIONS_WORKER_RUNTIME`, `VERCEL` or `NETLIFY` is set, the SDK
logs one warning per process when its interval timer sends events twice with no `flush()` call
between: a handler that returns with events still queued. Once is not enough, because a handler that
runs past the interval and then flushes lets the timer fire once first. It is a log line, never an
`onError` call, because nothing was lost that time.

## `shutdown()`

`await analytics.shutdown()` sends what is queued and stops the client. Call it on `SIGTERM` in a
long-running server. A script that exits on its own sends its queue first anyway; `shutdown()` is
the explicit way to be sure.

## `onError`

```ts
const analytics = init({
  writeKey: process.env.TOGO_WRITE_KEY!,
  onError: (error) => Sentry.captureMessage(error.message, { extra: error }),
});
```

Pass it to the error tracker your service already uses. It is called once for every event that
will not be recorded, or value dropped from one, and once when the client stops sending. Your logs
still show every one. It receives `{ code, message, eventIds, eventName? }`, the same shape and
codes as the [browser SDK's](/docs/reference/sdk-browser#onerror). It runs after the call that
caused it has returned, and whatever it throws is logged. `flush()`, `withFlush()` and `shutdown()`
wait up to 2 seconds for it to finish, so a serverless function still reports before it returns.

The codes the server SDK adds to the browser's:

| `code`                  | What was lost                                                                               |
| ----------------------- | ------------------------------------------------------------------------------------------- |
| `identity_missing`      | The event: it named neither `userId` nor `anonymousId`                                      |
| `client_shutdown`       | The event: it was tracked after `shutdown()`                                                |
| `shutdown_flush_failed` | The queue: `shutdown()` could not reach Togo, and the events are lost with the process      |
| `queue_full`            | New events while the queue is full. Reported once per overflow, naming the first event lost |
| `write_key_rejected`    | Everything: Togo refused the key. The queued events are dropped and listed in `eventIds`    |

## Delivery

Events are batched and retried with backoff when the endpoint is unreachable or busy, keeping the
same event id across attempts.
