@dataglue/sdk
v0.3.0
Published
Server-side DataGlue client: track, identify, alias, conversions, click links, workflow endpoints, imports, AI observability and reads. Zero runtime dependencies.
Maintainers
Readme
@dataglue/sdk
Server-side DataGlue client for Node 18+. Zero runtime dependencies — it uses
the platform fetch. ESM and CJS builds, full TypeScript types.
It talks only to the DataGlue public API and edge functions, never to a
database, so a workspace whose data plane moves on-prem keeps working with the
same code and a different baseUrl.
Install
pnpm add @dataglue/sdk # npm i / yarn addQuick start
import { DataGlue } from '@dataglue/sdk'
const dg = new DataGlue({
apiKey: process.env.DATAGLUE_API_KEY!, // Conversions → API keys
workspaceId: process.env.DATAGLUE_WORKSPACE_ID!,
hostname: 'yoursite.com', // the site the data is about
})
dg.identify({ distinctId: 'user_42', email: '[email protected]', traits: { plan: 'pro' } })
dg.track('subscription_started', { distinctId: 'user_42', properties: { plan: 'pro' } })
await dg.shutdown() // flush before the process exitstrack, identify and the ai.* calls queue and return immediately. They flush when flushAt
messages accumulate (default 20) or after flushInterval ms (default 10 000).
Everything else on the client is a direct, awaited call.
Always await dg.shutdown() before a short-lived process exits (a Lambda
handler, a cron script, a CLI). Otherwise the queued batch dies with the
process.
Outcomes
Needs a key with the outcomes:read scope (console → Settings → API keys).
const outcomes = await dg.outcomes.list();
const signed = outcomes.find((o) => o.slug === "deal-signed");
const { data } = await dg.outcomes.counts({ outcomeId: signed.outcome_id, from: "2026-09-01" });
const page = await dg.outcomes.instances(signed.outcome_id, { limit: 50 });- The window defaults to the last 30 days and is capped at 366.
- Instances carry profile and session ids only. Reading the person behind one is
dg.profiles.get(id), which needsanalytics:read.
Feature flags and A/B tests
Give a visitor the same group on your server as in their browser, so you can
vary an API response, an email or a price as part of a test. Needs a key with
flags:read (to read flag definitions) and analytics:write (to record who
saw what). Create one in the console under Flags → Server keys.
import express from "express";
import { DataGlue } from "@dataglue/sdk";
const dg = new DataGlue({
apiKey: process.env.DATAGLUE_SERVER_KEY!, // flags:read + analytics:write
workspaceId: process.env.DATAGLUE_WORKSPACE_ID!,
hostname: "www.example.com", // the site the browser test runs on
});
// Vary an API response. The page sends its glue_user_id (localStorage
// "glue_user_id", set by the glue script) so both sides agree, e.g.
// fetch("/api/pricing", { headers: { "x-glue-user-id": localStorage.getItem("glue_user_id") ?? "" } })
app.get("/api/pricing", async (req, res) => {
const visitor = String(req.header("x-glue-user-id") ?? "");
const variant = await dg.getFeatureFlag("pricing-page", visitor, {
properties: { plan: req.user?.plan }, // only what you know on the server
});
const copy = (await dg.getFeatureFlagPayload("pricing-page", visitor)) as { headline?: string } | null;
res.json({
headline: copy?.headline ?? "Simple pricing",
annualDiscount: variant === "test" ? 0.2 : 0.1, // "control", false and errors all land here
});
});getFeatureFlag(key, distinctId, { properties })gives the variant key for an A/B flag, ortrue/falsefor an on/off flag, and records one$feature_flag_calledexposure.isFeatureEnabledis the same as a boolean.getFeatureFlagPayloadandgetAllFlagsrecord nothing.- Same group as the browser: evaluation runs locally with the exact code
the glue script uses. Pass the browser's
glue_user_idasdistinctId. - Never throws, fails closed: no definitions yet, a network error, a bad
key, a timeout or a bad argument gives
"control"(when the flag has one) orfalse. Errors go toonErrorif you set it. Treatfalselike control. - Definitions load on first use (waiting at most
flagsTimeoutMs) and then refresh everyflagsPollIntervalwith an ETag. A failed refresh keeps the last good set. Turning a flag off reaches your server within one interval. - Exposures are sent once per (flag, variant, distinctId) per
flagsExposureWindowMs, through the normal event queue, againsthostname. Use the site's hostname so they land on the browser's profile. - Targeting: only the properties you pass are known here. Browser-only properties (UTM, URL, device, location) and server-only rules (office networks, email lists) are not available, so a flag aimed at those will not match on the server. Sticky "keep the first group" assignments live in the browser and are not seen either.
AI observability
Record your app's model calls, and your users' verdicts on them. They show in
the console under Setup → Advanced → AI observability, grouped by traceId.
const dg = new DataGlue({ apiKey, workspaceId, aiRedaction: 'truncate' }) // no hostname needed
const started = Date.now()
const reply = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages })
dg.ai.capture({
traceId: conversation.id, // one conversation or job
spanName: 'support-chat',
model: 'gpt-4o-mini',
provider: 'openai',
input: messages,
output: reply.choices[0].message,
inputTokens: reply.usage?.prompt_tokens,
outputTokens: reply.usage?.completion_tokens,
latencyMs: Date.now() - started,
distinctId: customer.id, // links the trace to the visitor profile
})
// Later, when the user taps thumbs-down:
dg.ai.feedback({ traceId: conversation.id, score: 'bad', comment: 'It had not shipped.' })ai.capture options: traceId and model (required), spanName,
provider, input, output, inputTokens, outputTokens, latencyMs,
totalCostUsd, error (an Error or a string; stored as its message),
distinctId, sessionId, spanId, parentId, timestamp, properties,
and redact to override the client's redaction for one call. Leave out
totalCostUsd and DataGlue prices the tokens from its catalogue, or your
workspace's price overrides.
ai.feedback options: traceId and score ('good' or 'bad', both
required), comment, distinctId, timestamp, properties. Traces rated
bad by users or by your team show up under the console's Rated bad filter.
properties: the server keeps the first 40 of yours on each row. Keys are cut
to 80 characters and text values to 1,000. Past 40, the rest are dropped and
the row records how many in $ai_properties_dropped. The SDK's own fields
(the score, $ai_redaction, the truncation marks) never count against the 40.
These calls never throw. They sit inside your AI request path, so bad
input, a shut-down client and failed sends are handed to onError instead,
and the row is dropped. An AI send failure never makes flush() reject.
Rows go to import-data (kind "ai") with your server API key, at most 500
rows and 900 KB per request, retried on 429/5xx with the same ids so a resent
batch is not counted twice. Never call them from a browser: the key is a
server key.
Redaction
aiRedaction decides what leaves your server as input and output:
| Mode | Sends |
|---|---|
| 'off' (default) | Input and output as given: prompts and answers leave your server unless you choose 'truncate' or 'drop'. The server still cuts anything above 64 KB and marks it truncated. |
| 'truncate' | Every text inside them cut to aiTruncateAt characters (default 1 000) plus …, keeping the message shape (roles, keys). |
| 'drop' | No input or output at all. Model, tokens, latency, cost and errors still go. |
Any other value is treated as 'drop'. The mode is recorded on the row as the
$ai_redaction property. properties cannot carry content around it: keys the
server reads as fields (input, messages, prompt, trace_id, …) are
removed from properties before sending. Error messages are not redacted; keep
prompt text out of them.
Options
| Option | Default | Meaning |
|---|---|---|
| apiKey | — | Workspace API key (dgc_…), created in the console under Conversions → API keys. Needs analytics:read for reads and analytics:write for writes and imports. Server only — a key with analytics:read can read every profile in the workspace. |
| workspaceId | — | Workspace UUID. |
| baseUrl | DataGlue cloud | https://<project>.supabase.co/functions/v1, or a custom hostname proxying it. |
| hostname | — | Default site hostname for events and profiles. Required unless passed per call. |
| conversionApiKey | — | The key conversion() and commercialEvent() present as a bearer token. It needs conversions:write or commercial:write respectively. One key can carry every scope, in which case pass the same value twice. |
| flushAt | 20 | Flush when this many messages are queued. |
| flushInterval | 10000 | Flush at least this often, in ms. 0 disables the timer. |
| maxRetries | 3 | Retry attempts after the first, for 429/5xx/network only. |
| retryBaseMs | 250 | First backoff ceiling. Full jitter, doubling per attempt. |
| timeoutMs | 15000 | Per-request timeout. |
| fetch | globalThis.fetch | Injectable for tests or a custom agent. |
| flagsPollInterval | 300000 | How often flag definitions refresh, in ms. 0 loads once. |
| flagsTimeoutMs | 3000 | Longest a flag call waits for the first definitions load. |
| flagsExposureWindowMs | 3600000 | One exposure per (flag, variant, distinctId) per window. |
| aiRedaction | 'off' | What ai.capture sends as input/output: 'off', 'truncate' or 'drop'. See Redaction. |
| aiTruncateAt | 1000 | Characters kept per text under 'truncate' (1 to 65 536). |
| onError | no-op | Receives errors the flag methods and ai.* calls swallowed. Errors it throws are ignored. |
Identity
Every write must be about someone. The SDK resolves, in order: distinctId,
then glueUserId, then email (lowercased). It never invents an id — a call
with no identifier throws DataGlueValidationError, because a random id would
create a new person on every call, which looks like traffic and is amnesia.
The resolved value becomes the profile's glue_user_id. DataGlue keys visitors
on (workspace_id, glue_user_id, hostname), so use a stable id from your own
system.
Writes
track(event, options)
dg.track('checkout_completed', {
distinctId: 'user_42',
properties: { cart_value_cents: 4999, currency: 'AUD' },
timestamp: new Date(), // optional; ISO string or Date
sessionId: 'srv-job-118', // optional
hostname: 'shop.example.com',
})An unparseable timestamp throws rather than silently defaulting to now — an
imported two-year-old signup dated today lands in this week's funnel.
identify(options)
dg.identify({
distinctId: 'user_42',
email: '[email protected]',
traits: { plan: 'pro', seats: 12 },
})Traits merge into the profile; they never replace it. An email marks the profile identified.
alias(options)
Binds an id from another system to a DataGlue profile.
await dg.alias({
sourceSystem: 'hubspot', // [a-z][a-z0-9_]*
sourceObject: 'contact', // default 'contact'
sourceRecordId: '0012x000ABCd',
email: '[email protected]', // or distinctId, or profileId
})This does not merge two DataGlue profiles. Visitor ownership is
server-side, and merging on a caller's word is how one person's journey ends up
containing another person's. If the identifier matches two live profiles the
call returns 409 profile_ambiguous rather than picking one.
conversion(options)
Needs conversionApiKey, not the workspace key.
await dg.conversion({
externalId: 'cust_991', // your id for the customer — the anchor
amount: 4999, // minor units; an amount implies kind 'sale'
currency: 'AUD',
invoiceId: 'inv_2026_0041',
customerEmail: '[email protected]',
clickId: 'dg_…', // if you captured one
})
// → { success, conversion_id, duplicate, profile_id, click_id }Idempotent by (kind, externalId, eventName, invoiceId). The same sale posted
five times is one row and one webhook; the repeats return duplicate: true
with the original id. Omit amount and the kind defaults to lead; pass
kind: 'custom' for anything else.
For a legacy sale, commercialEventType may be one of sale_recorded,
contract_signed, invoice_issued, or payment_received. It is stored as
conversion metadata for the commercial-event projection; omitting it preserves
the existing unclassified-sale behavior.
commercialEvent(options)
Needs a conversionApiKey with commercial:write. It records a typed,
idempotent commercial fact through POST /track/commercial.
await dg.commercialEvent({
eventType: 'payment_received',
idempotencyKey: 'stripe:payment_intent:pi_123',
externalId: 'cust_991',
amount: 4999,
currency: 'AUD',
sourceSystem: 'stripe',
sourceObject: 'payment_intent',
sourceRecordId: 'pi_123',
sourceEventId: 'evt_123',
occurredAt: '2026-09-15T05:00:00Z',
evidence: { invoice_id: 'inv_2026_0041' },
})Use a positive minor-unit amount for refunds and chargebacks too: their
eventType supplies the direction. Do not submit profileId, value semantics,
or direction; the server derives them from the event taxonomy.
Commercial CRM dimensions
Use commercialCustomer, commercialAccount, and commercialOpportunity to
create the source-keyed dimensions that commercial events reference. They need
the same commercial:write conversion API key as commercialEvent.
const account = await dg.commercialAccount({
sourceSystem: 'hubspot',
sourceObject: 'company',
sourceRecordId: '123',
name: 'Acme Pty Ltd',
customerLinks: [{ externalId: 'contact_991', role: 'primary_contact' }],
})
const opportunity = await dg.commercialOpportunity({
sourceSystem: 'hubspot',
sourceObject: 'deal',
sourceRecordId: '456',
accountId: account.account_id,
currentPipelineAmount: 100000,
currency: 'AUD',
customerLinks: [{ externalId: 'contact_991', role: 'stakeholder' }],
})
await dg.commercialEvent({
eventType: 'payment_received',
idempotencyKey: 'stripe:payment:pi_123',
opportunityId: opportunity.opportunity_id,
externalId: 'contact_991',
amount: 4999,
currency: 'AUD',
})currentPipelineAmount is pipeline only. Customer LTV remains a derived value
from payment, reversal, refund, and credit event types; no account or
opportunity write can change it.
link.create(options) / link.list()
const { link, duplicate } = await dg.link.create({
slug: 'spring-24',
destinationUrl: 'https://example.com/landing',
campaign: { utm_source: 'email', utm_campaign: 'spring-24' },
})Re-creating the same slug returns the existing link with duplicate: true, so
the call is safe to retry.
endpoint.send(endpointId, payload, options)
Posts to a workflow endpoint.
await dg.endpoint.send('e7c1…-uuid', { order_id: 118, total_cents: 4999 }, {
key: process.env.DATAGLUE_ENDPOINT_KEY!, // per endpoint, not per workspace
idempotencyKey: 'order-118', // required
})Reusing an idempotency key with different data is a 409 on purpose.
import(options)
const preview = await dg.import({
kind: 'profiles',
csv: await readFile('customers.csv', 'utf8'),
mapping: { external_id: 'Customer ID', email: 'Work Email' },
dryRun: true,
})
// → { rows_received, rows_valid, rows_rejected, rejections: [{row, error}], preview: [...] }Drop dryRun to write. Idempotent by external_id: re-uploading the same file
updates the same profiles and inserts no duplicate events. Bounded at 2 000
rows / 1 MiB per request.
Reads
await dg.whoami()
await dg.profiles.search({ email: '[email protected]', identified: true, limit: 50 })
await dg.profiles.get(profileId)
await dg.events.list({ event: 'page_view', sinceMinutes: 15 })
await dg.sessions.list({ profileId, converted: true, from: '2026-09-01' })
await dg.conversions.list({ from: '2026-09-01' })
await dg.recordings.list({ sessionId })
await dg.funnels.list()
await dg.webAnalytics({ from: '2026-09-01' })Lists return { data, count, limit, offset }, capped at 500 rows per page.
Two of them can answer available: false with a reason — recordings and
funnels, whose tables are owned by other tracks and may not be deployed in a
given environment. available: false is not an empty list. Do not render it
as proof that nothing happened.
people.activity(options)
One person's activity feed, newest first, for rendering in another app: visits (with their pages), forms, bookings, emails, CRM steps, conversions and the moment they identified. It is the same journey the console's person page shows, read across every record DataGlue treats as that person (merged records and deterministic identity links).
let cursor: string | undefined
do {
const page = await dg.people.activity({ email: '[email protected]', limit: 50, cursor })
render(page.person, page.items)
cursor = page.nextCursor ?? undefined
} while (cursor)
await dg.people.activity({ id: profileId, kinds: ['form', 'booking'], from: '2026-09-01' })
await dg.people.activity({ id: profileId, includePages: false })- Pass exactly one of
id(a profile id) oremail. An email matches exactly, in any case. An unknown person is a404. limitis 1 to 100 (default 50).kindsis any ofvisit,form,booking,email,crm,conversion,identity,event; an unknown kind is a400.- Keep calling with
nextCursoruntil it isnull. A page can be empty whilehasMoreis still true: the feed never returns an item it has not read in full. - Key rows by
item.id. Rarely, the same item can appear on two pages. - A visit lists its pages in time order. On a very long visit,
pages_completeisfalseand the list stops short;page_countis then what was read. context_completeisfalseon the rare item whose related rows (thousands of conversions on one step, bookings, or a visit's pages) passed a read cap: its notes or booking pairing may be incomplete. It errs on the cautious side: items read together share the flag, so it can befalsefor an item whose own rows were all read.truealways means complete.- Needs the
analytics:readscope. What comes back is a fixed list of fields: page paths without query strings, the referrer's origin only, and no raw event properties, IP addresses, user agents or CRM record details.
Over HTTP: GET /public-api/:workspaceId/people/:id/activity or
GET /public-api/:workspaceId/people/activity?email=, with limit, cursor,
from, to, kinds (comma-separated) and include_pages=false. The answer is
{ data: { person, items }, next_cursor, has_more }.
webAnalytics returns truncated: true when its scan hit the 5 000-session
bound; the totals are then a floor, not the answer.
Errors
import { DataGlueRateLimitError, DataGlueValidationError } from '@dataglue/sdk'
try {
await dg.conversion({ externalId: 'cust_991', amount: 4999, currency: 'AUD' })
} catch (error) {
if (error instanceof DataGlueValidationError) { /* the request is wrong */ }
if (error instanceof DataGlueRateLimitError) { /* retries were exhausted */ }
}| Error | When |
|---|---|
| DataGlueAuthError | 401 / 403 — key wrong, revoked, or for another workspace |
| DataGlueValidationError | 400 / 404 / 409 — retrying unchanged will not help |
| DataGlueRateLimitError | 429 after retries; carries retryAfterMs |
| DataGlueServerError | 5xx after retries |
| DataGlueNetworkError | fetch failed or timed out |
All extend DataGlueError and carry status, code, requestId, path and
the parsed body.
Retries cover 429, 5xx and transport failures only, with full jitter
(random(0, base × 2^attempt)) and Retry-After when the server sent one. A
4xx is never retried. link.create, endpoint.send and import opt out of
retry entirely so a partially applied write is never replayed blindly.
Build and test
pnpm build:sdk # esbuild → dist/index.mjs + dist/index.cjs, tsc → dist/*.d.ts
pnpm test:sdk # node --test with a stubbed fetchClient shape (capture/identify/alias, queue-and-flush with
flushAt + flushInterval, flush()/shutdown()) adapted from PostHog's
Node client, packages/node/src/client.ts in
PostHog/posthog-js@901c3d9af7e2cb13f5a6101b92ef49662a3e1f0e
(Apache-2.0). The exact license snapshot ships in licenses/. No PostHog code
is imported and no PostHog service is contacted.
