Docs Go to app →

Node SDK

@letterapp/node is the official Node.js client. It batches ingestion events in memory, retries on transient failures, and generates idempotency keys for you — so the common letter.track(...) call from a request handler is non-blocking and safe to retry. It also sends transactional email with letter.send(...).

If you’d rather call the HTTP API directly, see the Ingestion API and Transactional email. Third-party apps that only speak SMTP (Twenty, WordPress, Laravel) should use SMTP instead of this SDK.

Package@letterapp/node on npm
LicenseMIT
RuntimeNode 20+, ESM
Size~7 KB packed, zero runtime dependencies

Install

pnpm add @letterapp/node
# or
npm install @letterapp/node
# or
yarn add @letterapp/node

The package is published as ESM with TypeScript types. It has no runtime dependencies — fetch and crypto.randomUUID come from Node 20+‘s standard library. Bundles cleanly in Next.js, Hono, Express, Fastify, Lambda, and Vercel Edge Functions.

You’ll need an API key from Dashboard → Settings → API keys before the SDK will do anything useful.

Quick start

import { Letter } from "@letterapp/node";

const letter = new Letter({
  apiKey: process.env.LETTER_API_KEY!,
});

letter.identify({
  userId: user.id,
  email: user.email,
  traits: { name: user.name, plan: "free" },
});

letter.group({
  userId: user.id,
  accountId: workspace.id,
  name: workspace.name,
  traits: { plan: workspace.plan, mrr: 49 },
});

letter.track({
  userId: user.id,
  event: "Workspace Created",
  properties: { workspaceId: workspace.id },
});

// Required before process exit on long-running servers.
await letter.close();

Create the apiKey in Dashboard → Settings → API keys. It’s shown once on creation and never again — store it somewhere safe.

Bootstrapping an existing user base? See Initial import for a checkpointed, re-runnable script template built on top of this SDK.

Constructor options

OptionDefaultWhat it does
apiKey—Required. lt_live_… from Settings.
baseUrlhttps://api.letter.appOverride for self-hosting.
flushAt50Send a batch when this many items are queued.
flushInterval100 (ms)Send queued items at most this often.
maxRetries3Retry attempts on 5xx and 429.
fetchglobal fetchOverride for tests / proxies.
onErrorconsole.errorCalled when a background flush or a chatToken() call fails.

Methods

  • identify(opts) / group(opts) / track(opts) — enqueue, return void. Errors surface via onError. Fast path for long-running servers.
  • identifySync(opts) / groupSync(opts) / trackSync(opts) — make the HTTP call immediately, return a promise. Use in serverless functions where there is no background time.
  • send(opts) — send one transactional email. Always immediate; see below.
  • chatToken(opts) — a token that signs a user in to the Letter chat on your site. Cached per user; resolves to null instead of throwing; see below.
  • flush() — drain the queue now. Resolves when the in-flight request settles.
  • close() — flush, stop the timer, refuse new enqueues. Call this before process.exit() so no events are lost.

Transactional email

send() mails one person right now: a receipt, a password reset, a verification link. It is never batched and never waits for flush() or close() — batching a password reset would be a bug, not an optimization.

const result = await letter.send({
  to: "user@example.com",
  subject: "Reset your password",
  html: "<p>Click <a href='https://...'>here</a> to reset.</p>",
  tag: "password-reset",
  idempotencyKey: `password-reset:${token}`,
});

result.messageId; // provider id, appears in delivery events
result.replayed; // true if an idempotency-key replay returned an earlier send

Only to, subject and one of html / text are required. from defaults to the project’s sender and must be on a verified domain. A plain-text part is derived from the HTML when you don’t supply one. The full option list and the suppression rules are in Transactional email.

Failures throw a LetterError carrying status, code and reason. The reason is what tells “this recipient is unreachable” apart from “our account is blocked”:

import { Letter, LetterError } from "@letterapp/node";

try {
  await letter.send({ to, subject, html });
} catch (err) {
  // Hard-bounced or reported spam. Nothing to retry, nothing to fix.
  if (err instanceof LetterError && err.reason === "suppressed") return;
  throw err;
}

Signed-in users in the chat

If your site has the Letter chat, sign your logged-in users in to it: they’re never asked for their email, their conversation follows them to every browser, and your Inbox shows who they are. chatToken() gets the token the page passes to LetterChat.identify({ token }), signed by Letter with the chatbot’s identity secret, so the API key stays the only secret your server holds.

// On the server, for the page a signed-in user is about to see:
const token = await letter.chatToken({
  chatbot: "AbC123xYz789", // data-chatbot in the chat's install snippet
  userId: user.id,          // the same id you identify them with
  email: user.email,
  name: user.name,
  data: { plan: user.plan }, // optional: shown to your team next to the chat
});

Then in the page, once the chat script has loaded: LetterChat.identify({ token }), and LetterChat.reset() when they sign out. The chat docs have the HTML and Next.js versions.

  • Cached. Tokens last an hour, and each user’s is reused until five minutes before it expires, so most page views make no request. New details (a new name, say) get a new token. Concurrent calls for the same user share one request.
  • Never throws over the network. It’s on the way to a page, so it makes one attempt with a 3-second timeout. When Letter doesn’t answer, or refuses (a claim it won’t sign, an unknown chatbot), it resolves to null and reports why to onError; the chat then stays anonymous. A missing userId still throws, like identify().
  • chatbot can be left out when the project has a single chatbot, or a single published one.

The other options are the token’s claims: email, name, avatar (an http(s) URL), company ({ name, url }) and data (flat strings, numbers and booleans, up to 50 keys). It calls POST /v1/chat/token.

Retry behavior

  • 429: wait Retry-After seconds, then retry (up to maxRetries).
  • 5xx or network errors: exponential backoff (250 ms × 2^attempt + jitter).
  • 4xx other than 429: thrown immediately, no retry.

The SDK auto-generates a UUID messageId per track call, so retries dedupe at the server. See Idempotency for the underlying guarantee.

send() is the exception: it only retries when you pass an idempotencyKey. Without one, a retry after a timeout could put a second copy of the email in someone’s inbox, which is worse than failing the call.

chatToken() doesn’t retry either: it’s on the way to a page, and the next page view asks again.

Serverless mode

In serverless / edge-function environments there’s no background time between requests to drain the queue, so set flushAt: 1 and use the *Sync methods (or await letter.flush() at the end of each handler):

const letter = new Letter({
  apiKey: process.env.LETTER_API_KEY!,
  flushAt: 1, // send immediately
});

await letter.trackSync({ userId, event: "Checkout Started" });

Or simply await letter.flush() after enqueueing in the same request handler.

Errors

Errors thrown by *Sync methods (or surfaced via onError) use the same shape as the HTTP API — see Error format.

Versioning

The SDK follows semver. While we’re at 0.x:

  • patch (0.1.0 → 0.1.1) — bug fixes only.
  • minor (0.1.0 → 0.2.0) — new options, new methods, behavior changes. Read the release notes.
  • major (0.x → 1.0.0) — only once the HTTP API and method signatures are stable. Until then, pin a minor range ("@letterapp/node": "^0.1.0").

Every request sends a User-Agent: @letterapp/node@<version> header so we can spot outdated clients in server logs and reach out before deprecating anything.