Developer guide: 15. Integrations, webhooks, CLI and SDKs

Connectors, destinations, warehouse sources, outbound webhooks, the CLI and the SDKs.

Embed
Preview of the card
<a href="https://lucidace.com/help/developer-guide-integrations-webhooks-cli-and-sdks"><img src="https://lucidace.com/help/_api/public/orgs/af34862a-c837-4478-8335-0505efe40459/spaces/2f4b888b-c4e6-488b-81bd-6e838fb12d2e/pages/45b79383-a724-44d9-8e10-955a8ab2e20f/social-card.svg?v=3e7ae33eec8b" alt="Developer guide: 15. Integrations, webhooks, CLI and SDKs" width="600" height="315"></a>

15. Integrations, webhooks, CLI and SDKs

15.1 Connectors (sources and destinations)

A connector is a configured instance of a catalog entry. A source pulls data from a vendor into Lucida; a destination pushes events, persons or cohorts out. The connector routes are served by the Go lc-connectors service behind the same API host and the same keys, so every call below is {p}/connectors.... The service generates its own OpenAPI document from its route registrations (go/cmd/lc-connectors/openapi.go); the routes below are also merged into services/lc-api/openapi.json. Scopes: connector:read, connector:write.

lc "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/catalog?limit=200" | jq '{n:(.data|length), next_cursor}'
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/catalog" | jq '.data[] | select(.id=="adroll")'
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/catalog?q=watchtower" | jq '.data[].id'

The catalog is cursor-paged (?limit= default 100, ?cursor= from next_cursor) and filters by ?category= and ?q= (case-insensitive match on id, name or description).

A catalog entry: id, name, category, auth (api_key or oauth2), capabilities (source, destination, backfill), description, settings[] and credentials[] (names), and config_schema ({settings:[{name,type,required,secret}], credentials:[...]}). The catalog has more than 600 entries in categories such as ads, ai, analytics, billing, cdp, cms, commerce, crm, developer, devops, finance, experimentation; about 30 are destinations (for example meta_capi, google_ads_conversions, tiktok_events, segment_out, mixpanel_out). Page it with limit and cursor.

Create one from its config_schema:

lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors?skip_check=true" -d '{
  "kind":"adroll","name":"AdRoll ads","config":{"advertisable_eid":"ABC123"},
  "credentials":{"api_key":"<vendor key>"},"sync_interval_secs":3600}' | jq '{id,status,has_credentials}'

Field

Rules

kind

a catalog id; unknown is 422 unknown connector kind

name

1 to 200 characters

config, credentials

per the entry's config_schema. Credentials are envelope-encrypted and never returned (has_credentials: true)

sync_interval_secs

at least 60, default 900

?skip_check=true

A pull source is tested on create. If the vendor check fails, nothing is created and you get 422. Pass skip_check=true to save a source whose vendor is not reachable yet. Destinations are not probed on create

Verified with fake credentials: creating adroll without skip_check answers 422 with connection check failed, nothing was created: stream advertisables: http 401 .... With skip_check=true it is created active; POST .../{id}/test then answers 200 with {"status":"failed","error":"stream advertisables: http 401: ...","records_in":0,"preview_count":0,"drift":[]}. An OAuth entry created without credentials is paused until the OAuth flow completes (POST .../{id}/oauth/start).

Method and path

Purpose

GET, POST {p}/connectors

list, create

GET {p}/connectors/catalog

catalog

GET, PATCH, DELETE {p}/connectors/{id}

read, change (name, config, credentials, sync_interval_secs), delete (204)

POST .../{id}/enable, .../disable

resume / pause (status active or paused)

POST .../{id}/test

dry-run check; never writes. Returns status, error, records_in, preview_count, drift

POST .../{id}/sync

start a sync now (real calls to the vendor; do not run against accounts you do not own)

GET .../{id}/runs, .../stats, .../delivery-log

run history (status, records_in, records_out), counters, destination deliveries

GET .../{id}/dlq; POST .../dlq/replay

failed destination records and replay

GET .../{id}/drift, PUT .../{id}/routing (see "Destination delivery rules" below), GET, PUT .../{id}/models, .../file-models

schema drift, per-stream routing, data models

GET .../{id}/tables; POST .../tables/discover, .../tables/actions

per-table source controls

GET, POST .../{id}/backfills; GET .../backfills/{bid}; POST .../backfills/{bid}/cancel

historical backfill

GET .../{id}/cdc; POST .../cdc/resume

change-data-capture state (database sources)

GET, PUT, DELETE .../{id}/draft; POST .../draft/publish

edit a connector as a draft, then publish

POST .../{id}/preview, GET .../{id}/preview/events, POST .../{id}/estimate, POST .../{id}/post, GET .../{id}/channels

destination dry-run, estimate, send one event, list channels

POST .../{id}/unquarantine, GET, POST .../{id}/live-check

clear a quarantine, live checks against the vendor

POST {p}/connectors/transform/test, POST {p}/connectors/flag-imports/preview, POST .../{id}/github/install

test a transform, preview a flag import, GitHub App install

Exports to storage (export-schedules) and warehouse sync share this service; they are described with batch exports.

Destination delivery rules. These apply to every real-time destination (a connector with a destination capability and realtime: true routing), on every path that delivers records: live events, backfills, batched flushes and audience syncs. Set them with PUT {p}/connectors/{id}/routing, which stores them under config.route; fields you leave out keep their stored value.

Rule

Default

How to change it

Consent

A person with any explicit consent denial never reaches a destination (the event's $consent, or the person's stored $consent). No decision recorded counts as no denial

A route's own consent: {categories:[...], missing: "drop"|"hold"|"allow"} replaces the default: every listed category must be granted; missing says what happens without a recorded decision (drop default, hold parks the record in the DLQ until a replay re-checks, allow). An explicit denial always drops

$internal events

Dropped: events flagged $internal (internal traffic) never leave

config.route.internal: true lets them through

Cohort filter

None

config.route.cohorts: ["<cohort id>", ...] (at most 20) limits the route to people in any listed cohort. It fails closed: if the membership lookup is unavailable the batch errors and retries and nothing is sent. The preview does not apply this filter

Retry

A failed delivery retries in the call, then parks in the DLQ

Automatic redrive for 24 hours: parked letters that can heal (failed delivery, quarantine, rate cap, consent hold) are retried with doubling backoff from 1 minute to 1 hour, then wait for a manual POST .../dlq/replay. The attempt counters live in memory, so a restart retries sooner

Delivery log

GET .../delivery-log keeps 14 days

not configurable

For a full webhook walkthrough (filter, dry run, per-attempt log, replay) see Real-time destinations.

Delivery is at-least-once and the event uuid travels as the dedupe or idempotency key; never rely on exactly-once. A record a vendor refuses is logged as a warning in the delivery log and not retried.

lc -X PUT "$LUCIDA_API/v1/projects/$PROJECT_ID/connectors/$CID/routing" -d '{
  "filter":"events: [purchase]","transform":"","realtime":true,
  "internal":false,"cohorts":["<cohort uuid>"],"consent":{"categories":["marketing"],"missing":"drop"}}'

Hermeticor destination (catalog id hermeticor, a messaging destination): credential api_key (an app-bound key from Hermeticor's product-server preset, or events:write plus profiles:write; profiles:read and lists:write for cohort sync); settings base_url (default https://hermeticor.com), app (Hermeticor app slug, optional), events (event names to forward; unset = every non-$ event of an identified person), list_id and consent_category (default marketing). One path per event name: forward it here or send it from your product, never both (Hermetica). Events go to POST /v1/events/batch as {name, occurredAt, properties, dedupeKey, profile:{externalId, email?}}, up to 500 per call; dedupeKey is the event's dedupe_key property when set, else lucida-<event uuid>, so retries, replays and the same key sent directly never double-count. Nothing is forwarded for a person who denied analytics. Cohort joins go to POST /v1/lists/{id}/members/batch with a consent assertion (a join with no recorded consent for the category is not sent); leaves are looked up with POST /v1/profiles/lookup and removed with POST /v1/lists/{id}/members/remove. Items rejected inside a 200 answer are logged and not retried; other 4xx are permanent (DLQ), 5xx and 429 retry. Engagement comes back as hermeticor_message_<status|kind> events: create a webhook source with mapping.preset hermeticor and auth.mode hermetica (the Hermetica-Signature: t=,v1= HMAC scheme), and point a Hermeticor webhook endpoint with topics message.status and message.activity at its URL. Machine activity is skipped, no email is stored, and the person is the message metadata lc_distinct_id/distinct_id/externalId, else hermeticor:<profileId>.

15.2 Outbound webhooks

A webhook endpoint is a URL in one project that Lucida calls with a signed JSON POST when something happens. Scopes: settings:read, settings:write.

Method and path

Purpose

GET {p}/webhooks/event-types

subscribable events

GET, POST {p}/webhooks

list, create

GET, PATCH, DELETE {p}/webhooks/{id}

read, change (name, url, events, enabled), delete. Any other field in a PATCH (such as secret) is 422 with errors[] naming it; a secret changes only through rotate-secret

POST {p}/webhooks/{id}/rotate-secret

{overlap_hours?} (default 24, max 168, 0 cuts the old secret off at once); answers the new secret once

POST {p}/webhooks/{id}/test

send a webhook.test delivery now; logged once, never retried

GET {p}/webhooks/{id}/deliveries

delivery log: status, attempts, next_attempt_at, last_status, last_error, response_ms, delivered_at

Event types (GET .../event-types): flag.changed, export.run_failed, experiment.state_changed, alert.fired, alert.resolved, cohort.recalculated, annotation.created, digest.ready, health.issue_firing, health.issue_resolved, vision.matched, vision.alert_fired, vision.alert_resolved, vision.alert_broken, vision.budget_warning, replay.notification, intervention.fired, webhook.test. An empty events list subscribes to all.

HOOK=$(lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/webhooks" \
  -d '{"name":"ops","url":"https://example.com/hooks/lucida","events":["flag.changed","alert.fired"]}')
HID=$(echo "$HOOK" | jq -r .id); WHSEC=$(echo "$HOOK" | jq -r .secret)   # whsec_..., shown ONCE, store it now
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/webhooks/$HID/test" | jq '{status,last_status,last_error}'
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/webhooks/$HID/deliveries" | jq '.data[] | {event_type,status,attempts,last_status}'

Rules: the URL must be public https/http; a private or loopback address, or a host name that resolves to one, is 400 with target address is not public (for example https://localtest.me/..., which resolves to 127.0.0.1) at create and update time (delivery applies the same check). You may send your own secret (16 characters or more) when you create the endpoint; it is echoed back once, like a generated one. Verified: a test to https://example.com/hooks/lucida is logged as status: failed, last_status: 405, last_error: "endpoint answered 405", because that host does not accept POST. Any non-2xx or network error is retried with exponential backoff (30 s doubling, capped at 6 h, up to 8 attempts), then failed. Delivery is at least once: dedupe on the envelope id.

Every request has headers Lucida-Signature: t=<unix>,v1=<hex>, Lucida-Event: <type>, Lucida-Delivery: <delivery id>, and body {"id","type","created_at","project_id","data"}. v1 is HMAC-SHA256 of "<t>.<raw body>" keyed with the endpoint secret. Compute it over the raw bytes. During a secret rotation overlap the header carries two signatures, t=<unix>,v1=<new>,v1=<old>: accept the request if any v1 matches (the receiver below does). A working receiver (tested against a locally signed request):

import http from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";

const SECRET = process.env.LUCIDA_WEBHOOK_SECRET; // whsec_...
const seen = new Set();                            // use a durable store in production

export function verify(secret, header, rawBody, toleranceSec = 300) {
  const parts = (header ?? "").split(",").map((s) => s.split("="));
  const t = parts.find(([k]) => k === "t")?.[1];
  const sigs = parts.filter(([k]) => k === "v1").map(([, v]) => v);   // two while a rotation overlaps
  if (!t || !sigs.length || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
  const mac = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  return sigs.some((v) => v.length === mac.length && timingSafeEqual(Buffer.from(mac), Buffer.from(v)));
}

http.createServer((req, res) => {
  const chunks = [];
  req.on("data", (c) => chunks.push(c));
  req.on("end", () => {
    const raw = Buffer.concat(chunks).toString("utf8");
    if (!verify(SECRET, req.headers["lucida-signature"], raw)) { res.writeHead(401).end(); return; }
    const evt = JSON.parse(raw);
    if (!seen.has(evt.id)) { seen.add(evt.id); console.log(evt.type, evt.data); }
    res.writeHead(200).end("ok");                  // any 2xx stops retries
  });
}).listen(8080);

Signature schemes differ by sender, so do not reuse this verifier everywhere: outbound webhooks use Lucida-Signature: t=<unix>,v1=<hex> as above, while data destinations (webhook type) and custom-code destinations send X-Lucida-Signature: sha256=<hex> over the raw body only (no timestamp), audit-log (SIEM) sinks send X-Lucida-Signature: sha256=<hex> over <timestamp>.<body>, flag triggers (POST /v1/flag-triggers/{token}) use the same scheme as outbound webhooks (Lucida-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"> with the trigger's secret, 5 minute tolerance), and flag-health hooks (POST /v1/flag-health/{token}) use it too when signed (Lucida-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"> with the hook's secret, 5 minute tolerance; Watchtower hooks always sign, and send the same value as X-Watchtower-Signature, which Lucida accepts as well).

For a Slack-style relay, post evt.data from the 2xx branch to your chat webhook. Example data: flag.changed has key, change, enabled, version; experiment.state_changed has experiment_id, name, status, action; export.run_failed has run_id, export_id, name, kind, data_from, data_to, error.

15.3 Issue trackers, proxy records, data catalog, other integrations

Method and path

Scope

Purpose

GET, POST {p}/issue-trackers; PUT, DELETE .../{id}; POST .../{id}/test

replay:read / admin

connect a tracker for "file an issue from a replay" (13.5). Body {name, provider:"linear"|"github"|"jira"|"gitlab", target, base_url?, account?, issue_type?, credential?}; target is the Linear team id, GitHub owner/repo, Jira project key or GitLab project id; Jira needs base_url. test makes one authenticated read

GET, POST {p}/proxy-records; DELETE .../{id}; POST .../{id}/check

settings:read / settings:write

first-party proxy domains: {domain:"t.example.com", path_prefix:"/lc"} returns a token, status (pending until DNS verifies), cname_target and a proxy_secret (shown once); check re-verifies; POST .../{id}/secret makes a new secret. Send the secret as X-Lucida-Proxy-Secret (lc-proxy: LC_PROXY_SECRET) with the visitor address in X-Forwarded-For (or X-Real-IP) and the hosted gateway uses that address for geo; without it the address of your proxy is used. Run the proxy with lucida proxy setup. An app-level relay (a route handler) sends the pair X-Forwarded-For: <visitor ip> plus X-Lucida-Proxy-Secret: <proxy_secret>; see Reverse proxy

GET {p}/catalog/tables, /catalog/relationships, /catalog/certifications, /catalog/policy

insight:read

the data catalog of synced warehouse tables: joins and certified tables. POST .../relationships/propose, .../certifications/propose (data_catalog), POST .../accept, .../reject, .../certify, .../deprecate (data_catalog_approval), PUT policy (admin)

POST /v1/integrations/github/secret-scanning

public (GitHub signature)

receives GitHub secret-scanning alerts; not for you to call

Watchtower (errors, logs, traces, web vitals, LLM observability) is not built into Lucida. Use the watchtower connector (catalog id), the browser option watchtower: { correlate: true, origins: [...] }, which writes lucida.session_id into baggage, the watchtower: { client } option (or globalThis.watchtower), which sets lucida.session_id on Watchtower's RUM session via setAttribute, and deep links. See Watchtower. Messaging (Klaviyo, Braze, Customer.io, Iterable, OneSignal, Twilio ...) and support tools (Zendesk, Intercom, Gleap) are connectors; Lucida never sends email, push or SMS itself. See Messaging platforms and Support tools. Cohort pushes: Cohort changes push.

15.4 Terraform provider

Provider lucidaanalytics/lucida manages a project's definitions as code. Resources: lucida_flag, lucida_experiment, lucida_cohort, lucida_action, lucida_insight, lucida_metric, lucida_dashboard, lucida_alert, lucida_endpoint, lucida_key, lucida_export_schedule, lucida_connector, lucida_destination, lucida_traffic_exclusion; data sources lucida_project, lucida_flag. Each resource has its natural key plus one definition JSON argument.

provider "lucida" {
  project_id = var.lucida_project_id   # or $LUCIDA_PROJECT_ID
  # api_key from $LUCIDA_API_KEY; host from $LUCIDA_HOST for self-hosting
}
resource "lucida_flag" "checkout" {
  key        = "new-checkout"
  definition = jsonencode({ name = "New checkout", enabled = true, filters = { rollout = 25 } })
}

terraform import lucida_flag.checkout <flag id> adopts an existing object. Secrets (lucida_key.secret, connector credentials) are sensitive and are written to state: use an encrypted backend. Install, drift rules and limits: Terraform provider. Do not manage one object from both Terraform and the CLI.

15.5 The lucida CLI

Install: brew install lucidaanalytics/tap/lucida, npx @lucida-analytics/cli doctor, or a release archive (Install the CLI). Log in with lucida login (browser), lucida login --device (prints a URL and a code), or pipe a key on stdin or $LC_API_KEY; the key is kept in the OS keychain or a 0600 file. Environment: LC_API_URL, LC_API_KEY, LC_PROJECT_ID, LC_SECRET_KEY (capture), LC_GATEWAY_URL. Capture commands (events send, import events, demo seed) go to the capture host: from v0.1.5 the CLI defaults to the hosted capture host https://capture.lucidace.com (and to the API URL only when LC_API_URL points elsewhere): set LC_GATEWAY_URL (or --gateway) for a self-hosted or other capture host. --project overrides the default project.

Command

Purpose

lucida --version, version

print the version (checked: lucida v0.1.5)

login, projects list, doctor

sign in; list projects; check API reachability, key validity, clock skew (doctor only reads: it never creates or revokes a key)

doctor [--json], doctor --site URL [--cookies] [--trackers] [--profile hipaa], doctor connector <id> [--write]

API reachability, clock skew and key (--json: {api, ok, checks:[{id, status, detail, remedy}]}, exit 1 on a failed check); a site's snippet, proxy, CSP, cookies before consent, tracker inventory; live-check a connector

init [--framework id] [--key lc_pk_...] [--proxy ...] [--install] [--verify]

add the SDK snippet to a project in the current folder; without --framework it detects the framework. --framework ids: next, nuxt, sveltekit, astro, react-native, angular, vue, react, node, django, python, rails, ruby, laravel, php, go, flutter, plus html. All but next and html write the env var and an init module and print the install command. init --framework next [--write] prints five edits (install, NEXT_PUBLIC_LUCIDA_KEY, root layout with getBootstrap and LucidaNextProvider, next.config with lucidaRewrites() and skipTrailingSlashRedirect, and the request hook lucidaMiddleware); --write creates proxy.ts (Next 16 or later, exporting proxy) or middleware.ts (older), and next.config.mjs only when you have no next.config.*. It never overwrites a file; the layout is only printed. init --framework html [--app-host URL] (CLI 0.1.6 or later) prints the classic-script snippet with its integrity hash instead (no files written, section 3)

pull [--dir lucida] [--kinds ...]

write definitions as YAML (actions, cohorts, flags, insights, metrics, experiments, dashboards, alerts, endpoints)

plan [--dir]

show what apply would change; changes nothing

apply [--dir] [--dry-run] [--secret-out file]

create or update by natural key; absent fields are left alone; a new key's secret prints once or goes to a 0600 file

prune [--dir] [--yes]

delete remote objects missing locally; plan only without --yes

flags list, flags get <key>, flags toggle <key> --on|--off

flags

flags scan [--path .] [--format json] [--open-pr <flag>], flags fixture --out flags.json

find flag references and stale flags in code; test fixtures

rollout check <flag>, experiments check <experiment>

CI gates; exit 1 on a guardrail breach, SRM and so on

events send <name> --distinct-id id [--props '{}'], events send --file f.json, events list, events tail

send and read events

query (--file ir.json | --sql '...') [--json]

run a query

keys list|create|rotate|delete, webhooks list|create|delete|test

project keys (account keys need a web session) and webhooks

dashboards pdf <id> [--out f.pdf] [--variables '{}']

export a dashboard

import flags --from launchdarkly|growthbook|statsig|optimizely|unleash|flagsmith|configcat|split|devcycle|flagd

import flags from a file, token or URL

import events --from mixpanel|amplitude|posthog|ga4|heap|matomo|pendo|plausible|lucida|csv

backfill events (needs a secret capture key)

import posthog --project <ph id> [--only flags,cohorts,...] [--since d] [--dry-run] [--report f]

move a PostHog project: flags, experiments, cohorts, actions, dashboards, insights, persons, events. Key from $POSTHOG_PERSONAL_API_KEY or --key-stdin. See Migrate from PostHog

migrate instance, migrate [--status]

move data between Lucida instances; run database migrations (self-hosting)

mcp, mcp tools, mcp exec <tool> [--args '{}'] [--confirm token], mcp add <client>

local stdio MCP server; list tools; run one tool; write a client config (claude-code, cursor, vscode, windsurf, zed, codex, claude-desktop, claude-code-plugin; --readonly)

codegen --project id --lang ts|swift|kotlin|python|go --out dir, schema status

typed event helpers from the tracking plan; drift check

replay export <id>, replay verify <bundle.json> [--public-key k | --fetch-key]

signed replay evidence

proxy setup <nginx|caddy|cloudflare|vercel|nextjs> --host H --gateway G [--check]

first-party proxy config

demo seed --project id, micro, transform run, dbt import

sample data, local collector for CI, offline transforms, dbt manifest import

lucida login --device && lucida pull --dir lucida && lucida plan --dir lucida
lucida apply --dir lucida --secret-out .lucida-secrets   # 0600 file with name=secret lines

Plan and apply details: Plan and apply.

15.6 SDKs

Pick the public key for browsers and apps, the secret key for servers. Published today: @lucida-analytics/browser 0.1.8, react 0.1.3, next 0.1.5, vue 0.1.2 and the CLI 0.1.6. Details and every option are in each SDK's README; install status per language is in Install an SDK and SDK install status.

npm install @lucida-analytics/browser                  # browser
npm install @lucida-analytics/node                     # node
pip install lucida-analytics                           # python (import lucida; never `pip install lucida`)
go get github.com/lucidaanalytics/lucida-go@main       # go
// browser
import { createClient } from "@lucida-analytics/browser/core";
export const lucida = createClient("lc_pk_...", {
  apiHost: "https://capture.lucidace.com",
  consent: { mode: "opt_in" },        // the default is opt_out; use opt_in where consent law applies
});
lucida.capture("signed_up", { plan: "pro" });
// replay is an opt-in module: import { replay } from "@lucida-analytics/browser/replay"
// node
import { Lucida } from "@lucida-analytics/node";
const lucida = new Lucida(process.env.LUCIDA_PK!, { host: process.env.LUCIDA_CAPTURE!, secretKey: process.env.LUCIDA_SK });
lucida.capture({ distinctId: "user_123", event: "purchase", properties: { amount: 49.5 } });
await lucida.shutdown();                                // flush before exit
# python
from lucida import Lucida
with Lucida("lc_pk_...", host="https://capture.lucidace.com", secret_key="lc_sk_...") as lc:
    lc.capture("user_123", "purchase", {"total": 12})
    lc.identify("user_123", {"plan": "pro"})
    enabled = lc.is_feature_enabled("new-checkout", "user_123")
// go
c := lucida.New("lc_pk_...", lucida.Config{Host: "https://capture.lucidace.com", SecretKey: "lc_sk_..."})
defer c.Shutdown(ctx)
c.Capture(lucida.CaptureInput{DistinctID: "user_123", Event: "purchase", Properties: map[string]any{"total": 12}})
on, ok := c.IsFeatureEnabled(ctx, "new-checkout", "user_123", lucida.FlagOptions{})

Browser init options (createClient(key, options) and init; the full list with types is BrowserConfig in the SDK):

Option

Meaning

apiHost, uiHost, flagsApiHost

capture host (default https://capture.lucidace.com); the app host for toolbar and replay links (from browser 0.1.14 it defaults to https://lucidace.com when apiHost is https://capture.lucidace.com; set it when apiHost is a proxy); a separate origin for /v1/flags

assetHost

origin that serves the SDK's versioned static files (/static/v<version>/..., the classic script's modules). Default apiHost. From 0.1.12 it may also be a path on this site (for example /lc-assets) as well as an absolute URL

modules

classic script only: replay, heatmaps, forms, toolbar, guides, inspector, experiments, early-access, consent, loaded from assetHost. Refused in extension mode

consent

{mode: "opt_in" | "opt_out" | ..., queueBeforeConsent, respectDnt, storageKey, policyVersion, logBeacon, cookielessOnReject, geo}; also top-level respectDnt, respectGpc. A respectGpc you set wins; left unset, the project's respect_gpc setting decides (0.1.15)

persistence, cookie, cookieless, persistedProperties, flagPersistence, consentPersistence

where SDK state lives (cookie default, localStorage, sessionStorage, localStorage+cookie, memory, none)

autocapture

true, false or an object: captureText (default true; form-control text is never captured), maskAllAttributes (every $elements attribute value becomes ***, except attributeAllowlist), attributeIgnore, allowSelectors, denySelectors, urlAllowlist, urlIgnorelist, events, rageClicks, deadClicks, copyCut, outboundLinks, fileDownloads, siteSearch and more

capturePageview, capturePageleave, scrollRoot

pageview mode ("history" default, "hash", true, false), $pageleave, the scrolling element

urlPrivacy

{maskParams, maskCampaignParams, stripHash} mask query parameters and drop the fragment in every URL the SDK sends. From 0.1.12 also pathRules: [{match, replace}] (rewrite matching path segments) and maskPathIds: boolean (replace id-like path segments)

beforeSend

one hook or an array, run on every event before it is queued: return the event (amended) or null to drop it. A hook that throws drops the event

propertyDenylist, sampleRate

property names never sent; keep this share (0..1) of events

personProfiles

"always" (default), "identified_only", "never"

replay

{enabled, sample_rate, trigger, include_urls, exclude_urls, block_selectors, mask_selectors, mask_all_inputs, mask_all_text, ...} for the replay module; replayOwner picks who records when Watchtower is on the page

clickIds, crossDomains, referralParams, customCampaignParams

ad click ids, cross-domain visitor link, referral codes (off by default), extra campaign params

bootstrap, localFlags, flagStream, disableFlagsOnFirstLoad, sendFeatureFlags

flag loading and local evaluation

flushAt, flushIntervalMs, offlineQueue, rateLimit, rewritePath, requestHeaders, disableBeacon, onRequestError

delivery

blockBots, blockedUserAgents, disabled, debug, nonce, exposeGlobal

bots, test switch, logging, CSP nonce, global client (exposeGlobal is on by itself when a Watchtower browser SDK is on the page, from 0.1.15; false opts out)

Atlas sign-in module (0.1.15). Pass atlasIdentity({ property? }) from @lucida-analytics/browser/atlas in modules. It identifies the visitor as the Atlas user id on sign-in and resets on sign-out (only if it did the identify). It needs Atlas JS 0.29 or later (window.Atlas.session, atlas:session event). Example: Next.js install.

Consent in opt_in mode. From 0.1.12 the SDK makes no network request and writes no storage before consent is granted; config and flags are fetched when consent is granted. (Before 0.1.12 the config request could still go out first.)

Recipe: pages that show other people's data (an admin console, a CRM, a support inbox). Keep what is on screen out of events and recordings:

createClient("lc_pk_...", {
  apiHost: "https://capture.lucidace.com",
  autocapture: { captureText: false, maskAllAttributes: true, attributeAllowlist: ["data-testid"] },
  urlPrivacy: {
    maskParams: ["customer", "q"],
    stripHash: true,
    maskPathIds: true,                                   // 0.1.12: /customers/8841 -> a masked segment
    pathRules: [{ match: "/customers/*", replace: "/customers/:id" }], // 0.1.12
  },
  // no replay module imported; or keep it and never record these pages: see section 13
});

Leave the replay module out, or set replay_url_blocklist / replay_never_record (section 13). captureText: false and maskAllAttributes: true stop names, emails and ids from reaching $elements.

createClient from /core is the small, tree-shakeable entry: no autocapture, and nothing is loaded you did not import. The package root's init adds autocapture and loads its modules with a variable import(), which defeats code splitting; use it only when you want that all-in-one setup. Framework SDK peer dependencies are now caret ranges (^0.1.x), so a patch release of browser does not need matching react, next or vue versions. optIn() (browser 0.1.4) grants analytics and replay only, not marketing (section 3). replayOwner is not defaulted to lucida: with it unset, the recorder yields to a Watchtower recorder that is already running and logs a console.warn when it does; set replayOwner: "lucida" to always record (see Watchtower). exclude_urls and include_urls replay patterns match the full URL and the path plus query, so ^/account works.

All server SDKs batch (20 events or 5 s), gzip bodies over 1 KB, retry 408, 429 and 5xx with backoff, and drop the oldest events when the in-memory queue (1000) is full. Other SDKs in the repo (sdks/*): browser frameworks react, next, vue, nuxt, svelte, astro, angular, remix, react-router, tanstack-start, hono, edge, convex; mobile ios, android, flutter, react-native, capacitor, cordova, kmp; server java, java-servlet, ruby, rails, php, laravel, django, dotnet, elixir, rust; games and native unity, unreal, godot, roblox, cpp; tools gtm, github-action (release gate), cli; OpenFeature providers openfeature, java-openfeature, php-openfeature, ruby-openfeature, rust-openfeature, and flags-sdk.


15.7 Warehouse sources and joins

A warehouse source mirrors tables of your SQL warehouse into Lucida on a schedule, so /sql can read them next to events. It is an ordinary connector underneath (same runner, sealed credentials, run history and health alerts), shaped for tables. Scopes: connector:read, connector:write.

Method and path

Purpose

POST {p}/warehouse/sources

create a source (201)

GET {p}/warehouse/sources

list ({data, next_cursor})

GET {p}/warehouse/sources/{id}

one source with its tables (rows, bytes stored, last_synced_at, last_error, sql_name) and its last 5 runs

DELETE {p}/warehouse/sources/{id}

delete the source, its synced rows and its joins (204)

POST {p}/warehouse/sources/{id}/sync

sync now

POST, GET {p}/warehouse/joins; DELETE {p}/warehouse/joins/{id}

register, list, remove joins

lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources" -d '{
  "name":"pg_main","kind":"postgres",
  "config":{"host":"db.example.com","database":"app"},"credentials":{"user":"lucida_ro","password":"<password>"},
  "tables":[{"table":"public.orders","cursor_column":"updated_at","key_column":"id"}],
  "schedule":{"interval_secs":900}}'
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/sql" -d '{"sql":"SELECT count() FROM warehouse.pg_main.orders"}'
  • name is the source name in warehouse.<source>.<table>: lower_snake_case, at most 30 characters, no double underscore (422 with errors[] otherwise). A repeated name is 409. kind is a SQL warehouse connector (postgres, mysql, bigquery, snowflake, redshift, databricks, mssql, clickhouse and the like), stripe or an object store (s3, r2, gcs), both below; anything else is 422. config and credentials are those of the kind (see its config_schema in the connector catalog); credentials are sealed and never returned.

  • tables[]: table (the reference in the source, db.schema.table), name (the Lucida table name, default the last part of table, same naming rule), cursor_column (an increasing column; each sync reads rows past the last cursor), cursor_type (timestamp default, number or string) and key_column (rows with the same key replace each other, so updates mirror). At least one table is required.

  • schedule.interval_secs defaults to 900 (minimum 60). The source is tested on create: a failed connection check creates nothing and answers 422; pass ?skip_check=true to save a source that is not reachable yet.

  • Synced rows are stored per project and read in /sql as warehouse.<source>.<table>, with the same project scope and access rules as every other table; hidden tables are masked.

  • A join turns a column of a synced table into a person or group property: POST {p}/warehouse/joins {source, table, column, to, key, group_type?}. source is the source id or its name, table a synced table of it, column the column copied (the property gets the same name), key the column holding the person's distinct_id or the group key, to is person or group (group_type is required for group). To match people by email instead, add "match":"email_sha256" to a person join: key is then a column holding an email (or its SHA-256), and the person is found by the hash of their stored email (or $email) property. Emails are trimmed, lowercased and hashed with SHA-256 before matching; a row no person matches is dropped (it never creates a person) and the raw email never becomes a property. A repeated (source, table, column) is 409. Once synced, the property is an ordinary person or group property in insights.

  • Stripe (kind: "stripe", credential api_key, a restricted read key is enough) syncs the Stripe list API into warehouse.<source>.charges, customers, subscriptions and invoices (all four when tables is omitted; tables takes names such as [{"table":"charges"}]). Rows are upserted by Stripe id; created is the incremental cursor (re-read with a 7 day lookback so a charge that later settles or is refunded is updated; subscriptions are re-read whole each run). Columns are flat and in Stripe's units: amounts are minor units (cents), created is unix seconds, created_at is RFC 3339. charges has id, amount, amount_captured, amount_refunded, currency, status, paid, refunded, captured, created, created_at, customer, invoice, payment_intent, description, email, billing_email, receipt_email, billing_name, failure_code, where email is billing_details.email, else receipt_email.

  • S3, R2 and GCS (kind: "s3" | "r2" | "gcs"): each tables[] entry is {table: <key prefix or glob>, name, format?} (format csv, jsonl or parquet, default from the extension; .gz is expanded). Every row of every object is a row of warehouse.<source>.<name> with its columns plus _object_key, _object_modified and _row; new and changed objects are read, each once. File tables are read in /sql; they cannot be joined to people (they have no cursor). HubSpot is not created here; it stays on the generic connector routes.

  • A failing sync is reported by the same connector health check that flags any errored connector.

Worked example: Stripe revenue by week, charges matched to people by email.

# 1. Create the source (the key is sealed; the check call lists one charge) and sync now.
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources" -d '{
  "name":"stripe","kind":"stripe","credentials":{"api_key":"rk_live_..."},
  "tables":[{"table":"charges"},{"table":"customers"}],"schedule":{"interval_secs":900}}'
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources/$SOURCE_ID/sync"

# 2. After the first run, GET shows rows, bytes and last_synced_at per table.
lc "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/sources/$SOURCE_ID" | jq '.tables'

# 3. Join charges to people by email hash: each person gets a property "amount" (their latest charge, in cents).
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/warehouse/joins" -d '{
  "source":"stripe","table":"charges","column":"amount","to":"person","key":"email","match":"email_sha256"}'

# 4. Revenue trend: the charges, matched to persons by the same email hash, weekly, in dollars.
SQL=$(cat <<'SQL'
SELECT toStartOfWeek(toDateTime(JSONExtractInt(c.data, 'created'))) AS week,
       count() AS charges, uniq(p.person_id) AS people,
       sum(JSONExtractInt(c.data, 'amount') - JSONExtractInt(c.data, 'amount_refunded')) / 100 AS revenue
FROM warehouse.stripe.charges AS c
INNER JOIN persons AS p
  ON lower(hex(SHA256(lowerUTF8(trimBoth(JSONExtractString(p.properties, 'email'))))))
   = lower(hex(SHA256(lowerUTF8(trimBoth(JSONExtractString(c.data, 'email'))))))
WHERE JSONExtractString(c.data, 'status') = 'succeeded'
GROUP BY week ORDER BY week LIMIT 52
SQL
)
lc -X POST "$LUCIDA_API/v1/projects/$PROJECT_ID/sql" -d "$(jq -n --arg sql "$SQL" '{sql:$sql}')"

The join in step 3 copies one column of one row onto the person (the latest charge), so it answers per-person questions in insights, such as a cohort of people whose last charge was over 10000. A trend over time sums the charges themselves, which is why step 4 reads the table and matches persons by the same hash; drop the INNER JOIN to include customers Lucida has never seen. The hash in the query must follow the join's rule: trim, lowercase, SHA-256 hex. A key column that already holds a 64-character hex digest is taken as an already-hashed email.

Updated