IonBlink's server SDK. IonBlink is product analytics built for agents. This package sends events from your
server: orders, sign-ups, webhooks, background jobs. It uses only fetch, has no dependencies, and runs unchanged on
Node 18+, Bun, Deno, Cloudflare Workers and Vercel Edge. It adds about 4 KB gzipped to a bundle. Calls never throw
after the constructor, and the constructor tells you how to fix what is wrong. For browsers and apps, use ionblink-js
and ionblink-react-native from ionblink-js.
npm install ionblink-nodeimport { IonBlink } from 'ionblink-node'
const ib = new IonBlink(process.env.IONBLINK_SECRET_KEY!)
ib.event('Order Completed', { revenue: 49, currency: 'USD' }, { userId: 'u_123' })On a long-running server the event goes out within a second. In a script, a serverless function or an edge handler,
await ib.flush() before you return (see Serverless rules). Get the secret key (ib_sk_…) in
the IonBlink app under Settings → Sites → Server keys, and keep it on the server.
Paste this into Claude Code, Cursor, Codex or any coding agent:
Add IonBlink server events to this project: read https://github.com/Winding-Labs/ionblink-node/blob/main/AGENTS.md and follow it.
- API reference
- Join server events to browser sessions
- Framework recipes
- Serverless rules
- Errors and debugging
- Privacy
- Versioning
- Releases
- License
import { IonBlink, IonBlinkError, whoFrom } from 'ionblink-node'Create one client per process and share it (on Cloudflare Workers, one per request). The constructor throws a
TypeError with the fix in its message when:
- the key is missing (it says how to pass it, and that
{ disabled: true }skips it in tests); - the key is a site key (
ib_pk_…): those are for browsers and apps; - the key doesn't look like
ib_sk_and 40 letters and digits (it says what is off, and never prints the key); - it runs in a browser (
windowanddocumentboth exist) or a React Native or Expo app (navigator.productisReactNative): anything shipped to a browser or in an app bundle is public, so a secret key never goes there; hostisn't an https URL (plainhttponly forlocalhost,127.x.x.xand[::1]): every request carries the key;- an option has a bad value.
Surrounding whitespace in the key (a trailing newline from an env file) is trimmed.
| Option | Default | What it does |
|---|---|---|
host |
'https://api.ionblink.com' |
Where events go: https only (http for localhost). A first-party proxy URL (https://example.com/ib) also works. Redirects are never followed, so the key never reaches another host; a 3xx answer is rejected. |
flushAt |
20 |
Send once this many events are queued, all identities together. |
flushInterval |
1000 |
Send queued events at most this many ms after they were queued. 0 turns the timer off. The timer never keeps a process alive. |
maxRetries |
3 |
Retries after a network error, a timeout, a 429 or a 5xx. |
timeout |
10000 |
Timeout per request in ms (AbortController). |
fetch |
global fetch |
A custom fetch: a proxy agent, or a test double. |
disabled |
false |
Every call is a no-op and the key may be empty. Handy in tests. |
debug |
false |
Log what is sent and what came back with console.log. Never logs the key. |
onError |
none | (error: IonBlinkError) => void, called for dropped events, give-ups, a rejected key and invalid calls. |
gzip |
true where CompressionStream exists |
Gzip request bodies. Node 18+, Bun, Deno and Workers all have it. |
Records an event. Returns at once; the event waits in memory for the next send.
name: 1-64 characters, not starting with$(reserved for IonBlink). Use "Object Action" in Title Case:'Order Completed','Report Exported'.props: a plain object of JSON values, orundefined. At most 50 properties per object, keys cut to 64 characters, strings cut to 1,024, objects and arrays nested at most 4 deep (countingpropsitself), and the whole JSON at most 8 KB (keys that would pass it are dropped).undefinedvalues are dropped,NaNandInfinitybecomenull, andDates become ISO strings.who: who the event is about.{ userId }(your own user id, 1-200 characters),{ anonId, sessionId }from the browser, or both, which joins the visitor's session to the person. At least one ofuserIdandanonId;sessionIdonly withanonId.null,undefinedand''count as absent, so{ userId: user?.id, ...whoFrom(req.headers) }works for signed-out visitors too.
ib.event('Order Completed', { order_id: 'o_1', revenue: 49, currency: 'USD' }, { userId: 'u_123' })Set traits on a person. identify('u_123', { plan: 'pro' }) is the same as set({ id: 'u_123', plan: 'pro' }).
Traits follow the props rules. id is your own user id (1-200 characters): never an email.
ib.identify('u_123', { plan: 'pro', company: 'Acme' })
ib.set({ id: 'u_123', seats: 12 })Anyone can make a browser claim any user id (the browser SDK's identify() runs in the page), so IonBlink shows a
browser's id as claimed. A person becomes verified when your server binds the browser session they signed in from:
call this once your server has authenticated the request, with the browser's ids from its headers
(whoFrom). The server's user id replaces whatever the browser claimed.
// after sign-in succeeded: userId from your own session, never from the request body
ib.identify({ userId: user.id, ...whoFrom(req.headers), traits: { plan: user.plan } })Without browser ids (whoFrom found none) it only sets traits, like identify(userId, traits). anonId and
sessionId must be the UUIDs the browser sent, and sessionId needs anonId; anything else is invalid and nothing
is sent. An event() whose who has both userId and anonId binds the same way.
Sends everything queued now, and waits for requests already in flight. It resolves when all of it is sent or given up, and it never rejects. Events queued after the call don't hold it up.
Stops the timer, flushes, and waits for requests in flight, for at most timeoutMs. Later calls do nothing (with a
note when debug is on). Call it before a long-running process exits. Never rejects.
Reads the browser's ids from the x-ionblink-anon and x-ionblink-session request headers and returns
{ anonId?, sessionId? }. It takes fetch Headers (Hono, Next.js, Workers, Deno, Bun) or a plain object (Node and
Express req.headers). Values that aren't UUIDs are left out, so the result is always safe to spread into who.
What onError receives. The SDK hands these to onError and carries on; it never throws them at you.
| Field | Meaning |
|---|---|
code |
'bad_key', 'rejected', 'dropped', 'gave_up' or 'invalid' (see Errors and debugging). |
message |
What happened, in plain words. |
count |
How many events were lost (0 when none were). |
status |
The HTTP status, when the API answered. |
IonBlink, IonBlinkError, whoFrom, VERSION, and the wire protocol: PROTOCOL_VERSION, LIMITS and the types
ServerBatch, ServerEvent, ServerAnswer, Json (see src/protocol.ts). Types: IonBlinkOptions,
Who, Props, Traits, IonBlinkErrorCode, FetchLike. Subpaths: ionblink-node/hono and ionblink-node/express.
ESM and CommonJS both ship, each with its own types.
Events queue in memory, grouped by identity: one request carries one identity (a person, an anonymous visitor, or
both). A send happens when flushAt events are queued or flushInterval ms have passed. It makes one request per
identity, at most 4 at a time, each at most 200 events and 60 KB as sent (bigger groups are split). The queue holds at
most 10,000 events; past that the oldest are dropped and reported.
| Answer | What the SDK does |
|---|---|
| 2xx | Done. |
| 400 | Drops the batch (onError dropped). |
| 401, 403 | Stops sending for the client's lifetime and logs once (onError bad_key). |
| 413 | Splits the batch in half and resends; a single event that still fails is dropped. |
| 429, 5xx, network error, timeout | Retries up to maxRetries times, waiting 500 ms × 2^n (±25%, at most 30 s) or the Retry-After header; then gives up (onError gave_up). |
| Other 4xx | Drops the batch (onError rejected): usually a wrong host. |
Every retry of a batch carries the same batch id, so the API never counts it twice.
A server event can join the visitor's live session in the browser, so you see the checkout request in the same
timeline as the clicks that led to it. The browser SDK's ionblink.ids() returns { anon, session }. Send them as
headers:
// browser (ionblink-js)
const ids = ionblink.ids() // undefined in basic mode
await fetch('/api/checkout', {
method: 'POST',
headers: ids ? { 'x-ionblink-anon': ids.anon, 'x-ionblink-session': ids.session } : {},
})// server
import { whoFrom } from 'ionblink-node'
ib.event('Order Completed', { revenue: 49 }, { userId: user.id, ...whoFrom(req.headers) })With both userId and anonId, IonBlink binds that browser's session to the person and shows them as verified (see
identify({ ... })), so pass the userId your server
authenticated, never one the browser sent. With only userId, the event joins a session your server bound to that
person, else the one browser that claims them, else none. If your API is on another origin, allow the two headers in
your CORS Access-Control-Allow-Headers.
Server actions can't set request headers, so pass the ids as an argument instead:
{ userId, anonId: ids?.anon, sessionId: ids?.session }. The SDK checks that both are UUIDs.
Every recipe uses one shared client module:
// lib/ionblink.ts
import { IonBlink } from 'ionblink-node'
export const ib = new IonBlink(process.env.IONBLINK_SECRET_KEY!)A long-running server needs nothing else: the timer sends. Flush on exit.
import express from 'express'
import { whoFrom } from 'ionblink-node'
import { ionblink } from 'ionblink-node/express'
import { ib } from './lib/ionblink'
const app = express()
app.use(ionblink(ib)) // sets req.ionblink (typed)
app.post('/checkout', (req, res) => {
req.ionblink?.event('Order Completed', { revenue: 49 }, { userId: 'u_123', ...whoFrom(req.headers) })
res.json({ ok: true })
})
const server = app.listen(3000)
process.on('SIGTERM', async () => {
await ib.shutdown()
server.close()
})On serverless platforms (Vercel, Lambda through serverless-http), use ionblink(ib, { flushOnFinish: true }): it
starts a flush when each response finishes. If the platform freezes the function the moment the response is sent,
await ib.flush() in the handler before you respond instead.
import { Hono } from 'hono'
import { whoFrom } from 'ionblink-node'
import { ionblink, type IonBlinkVariables } from 'ionblink-node/hono'
import { ib } from './lib/ionblink'
const app = new Hono<{ Variables: IonBlinkVariables }>()
app.use(ionblink(ib))
app.post('/checkout', (c) => {
c.get('ionblink').event('Order Completed', { revenue: 49 }, { userId: 'u_123', ...whoFrom(c.req.raw.headers) })
return c.json({ ok: true })
})
export default app // Bun: `bun run index.ts`. Node: serve(app) from @hono/node-server.The middleware calls executionCtx.waitUntil(ib.flush()) after each response where the runtime has one. On Node and
Bun there is none, so the timer sends.
Secrets live in c.env, so pass a function that makes a client per request. The middleware flushes with
waitUntil after each response, without delaying it.
import { Hono } from 'hono'
import { IonBlink } from 'ionblink-node'
import { ionblink, type IonBlinkVariables } from 'ionblink-node/hono'
const app = new Hono<{ Bindings: { IONBLINK_SECRET_KEY: string }; Variables: IonBlinkVariables }>()
app.use(ionblink((c) => new IonBlink(c.env.IONBLINK_SECRET_KEY, { flushInterval: 0 })))
app.get('/', (c) => {
c.var.ionblink.event('Page Served', {}, { userId: 'u_123' })
return c.text('ok')
})
export default appRoute handlers and server actions run the work you pass to after() once the response is sent. Flush there.
// app/api/checkout/route.ts
import { after } from 'next/server'
import { whoFrom } from 'ionblink-node'
import { ib } from '@/lib/ionblink'
export async function POST(request: Request) {
const { userId, total } = await request.json()
ib.event('Order Completed', { revenue: total, currency: 'USD' }, { userId, ...whoFrom(request.headers) })
after(() => ib.flush())
return Response.json({ ok: true })
}// app/actions.ts
'use server'
import { after } from 'next/server'
import { ib } from '@/lib/ionblink'
export async function upgradePlan(userId: string, plan: string, ids?: { anon: string; session: string }) {
// …change the plan…
ib.event('Plan Upgraded', { plan }, { userId, anonId: ids?.anon, sessionId: ids?.session })
after(() => ib.flush())
}after is in Next.js 15.1 and later. It works on the Node.js and Edge runtimes. Add import 'server-only' to
lib/ionblink.ts to make sure it never reaches a client bundle.
Make a client per request with the timer off, and hand the flush to waitUntil: the response doesn't wait for it.
import { IonBlink, whoFrom } from 'ionblink-node'
export default {
async fetch(request, env, ctx): Promise<Response> {
const ib = new IonBlink(env.IONBLINK_SECRET_KEY, { flushInterval: 0 })
ib.event('Checkout Started', {}, { userId: 'u_123', ...whoFrom(request.headers) })
ctx.waitUntil(ib.flush())
return new Response('ok')
},
} satisfies ExportedHandler<{ IONBLINK_SECRET_KEY: string }>Set the key with wrangler secret put IONBLINK_SECRET_KEY (and in .dev.vars for wrangler dev).
Await the flush before you return. The platform freezes the function after it returns, and a frozen function sends nothing.
import { ib } from './lib/ionblink'
export const handler = async (event: { userId: string }) => {
ib.event('Report Exported', { format: 'csv' }, { userId: event.userId })
await ib.flush()
return { statusCode: 200 }
}On Vercel you can also use waitUntil(ib.flush()) from @vercel/functions to respond first.
import { IonBlink } from 'npm:ionblink-node'
const ib = new IonBlink(Deno.env.get('IONBLINK_SECRET_KEY')!)
Deno.serve(async (req) => {
ib.event('Order Completed', { revenue: 49 }, { userId: 'u_123' })
return new Response('ok')
})Deno.serve is long-running, so the timer sends. On Deno Deploy that is the same.
import { IonBlink } from 'ionblink-node'
const ib = new IonBlink(Bun.env.IONBLINK_SECRET_KEY!)
Bun.serve({
fetch(req) {
ib.event('Order Completed', { revenue: 49 }, { userId: 'u_123' })
return new Response('ok')
},
})
process.on('SIGTERM', () => ib.shutdown().then(() => process.exit(0)))const ib = new IonBlink(process.env.IONBLINK_SECRET_KEY!, { flushAt: 1 })
ib.event('Backfill Done', { rows: 1200 }, { userId: 'u_123' })
await ib.shutdown()Runnable examples: examples/hono, examples/nextjs,
examples/cloudflare-worker.
The client queues events and sends them in the background. A runtime that stops or freezes your code after the response drops whatever is still queued. So:
| Runtime | Do this |
|---|---|
| Long-running server (Express, Fastify, Hono or Bun on a VM or container) | Nothing per request. await ib.shutdown() on SIGTERM. |
| AWS Lambda, Vercel functions, Netlify functions | await ib.flush() before you return. |
| Next.js route handlers and server actions | after(() => ib.flush()). |
| Cloudflare Workers | A client per request with flushInterval: 0, and ctx.waitUntil(ib.flush()). |
| Vercel Edge, Deno Deploy, other edge runtimes | waitUntil(ib.flush()) where the platform has it; otherwise await ib.flush(). |
| One-off scripts and cron jobs | flushAt: 1, and await ib.shutdown() at the end. |
flush() waits for retries too: with the defaults, an unreachable API can hold it for up to about 45 seconds. Where
time is tight, lower timeout and maxRetries (for example { timeout: 3000, maxRetries: 1 }), or use waitUntil
so the response doesn't wait.
Turn on debug: true to see each send, its size, the body, and the answer:
[ionblink] invalid: event("$oops"): names starting with "$" are reserved for IonBlink. The call was dropped.
[ionblink] sending 1 event, 201 bytes gzipped { v: 1, lane: "server", batch: "01a2…", sdk: { … }, person: "u_123", events: [ … ] }
[ionblink] IonBlink answered 503; retrying in 512 ms
[ionblink] 202 for batch 01a2…
Pass onError to count or report problems in production:
const ib = new IonBlink(process.env.IONBLINK_SECRET_KEY!, {
onError: (err) => console.warn(`ionblink ${err.code}: ${err.message}`),
})| Code | When | What to do |
|---|---|---|
bad_key |
The API answered 401 (the key is unknown or revoked) or 403 (capture is off for the site, or the request looked like it came from a browser: an Origin or Sec-Fetch-Site header, which a proxy or a browser-like fetch can add). The client stops sending and logs once with console.error, even without debug. |
401: create a new key in Settings → Sites → Server keys and redeploy. 403: turn capture on for the site, or send from your server without those headers. |
rejected |
Another 3xx or 4xx, usually a 404 from a wrong host, or a redirect (which is never followed). |
Check host: https://api.ionblink.com or your proxy URL. |
dropped |
The API answered 400, an event was too big, or more than 10,000 events were waiting. | Read the message; it carries the API's reason. |
gave_up |
Retries ran out: network errors, timeouts, 429 or 5xx. | Check that the server can reach the host. |
invalid |
A call had a bad name, props, who or id. The call was dropped; nothing threw. |
Read the message: it names the call and the fix. |
The key never appears in logs, errors or messages. If a test runs in a jsdom environment (window and document
exist), the constructor throws as it would in a browser: use the node test environment for server code, or mock the
module.
- Never send an email, a phone number or a name as
userIdorid. Use your own user id. - Send only what you need. The server scrubs common PII patterns from event props, but it can't know what your data means.
- Traits from
identify()andset()are stored as you send them. - The SDK sends only to
host, only what you pass it, plus its name and version. It reads nothing from the machine.
This package follows semver. Before 1.0, a minor version may change the API; the
CHANGELOG says how to update. The wire format is IonBlink protocol v1 (src/protocol.ts);
a breaking change to it would be protocol v2, sent side by side with v1.
On npm as ionblink-node. Releases are published from this repository's
GitHub Actions with npm trusted publishing and provenance (CONTRIBUTING.md).
MIT. Copyright (c) 2026 Winding Labs.