@emit-vision/sdk-js
v0.4.2
Published
Browser SDK for self-hosted emit-vision analytics and error tracking.
Readme
@emit-vision/sdk-js
Browser SDK for Emit Vision, the self-hostable analytics and error tracking stack in this repo.
For a full local walkthrough, see docs/sdk-guide.md.
Installation
npm install @emit-vision/sdk-jsTo consume the package from another local project before publishing:
pnpm nx run sdk-js:build
cd packages/sdk-js
pnpm packThen install the generated tarball:
npm install /absolute/path/to/emit-vision/packages/sdk-js/emit-vision-sdk-js-0.1.0.tgzQuick Start
import { init, captureEvent } from "@emit-vision/sdk-js";
init({
dsn: "http://evk_local_development_seed_key_000000000000@localhost:4301/v1",
environment: "development",
release: "[email protected]",
autoCapture: {
errors: true,
unhandledRejections: true,
},
});
captureEvent("user_signed_up", { plan: "free" });When to Use This Package
Use @emit-vision/sdk-js directly when your app is already client-side and you
want the thinnest possible integration path.
Good fits include:
- Vanilla TypeScript or JavaScript browser apps
- Vite or other framework-agnostic frontend bundles
- Apps that want full control over when
init(),captureEvent(), andflush()run
If you are in React or Next.js, the helper packages wrap this SDK without changing the ingest contract:
@emit-vision/sdk-reactfor provider and hook ergonomics in React trees@emit-vision/sdk-nextfor app-router projects that want a client provider with server-side config composition
Those helpers are convenience layers, not alternate transports. The same browser-only privacy and safety guidance still applies.
API Reference
init(options: EmitVisionOptions): void
Initializes the SDK. Call it once, as early as possible.
| Option | Type | Default | Description |
| ------------------- | ----------------------------------------------------- | --------------------------------------------- | -------------------------------------------------------------------------- | ------ | --- | ---------------------------------------------------------- |
| dsn | string | — | Local DSN in the form http://<api-key>@localhost:4301/v1 |
| apiKey | string | — | Explicit API key if you do not want to use a DSN |
| endpoint | string | http://localhost:4301 | Explicit ingest API base URL |
| environment | string | — | Environment label such as development or production |
| release | string | — | Release or git SHA attached to outgoing events |
| sessionId | string | — | Session identifier attached to future events |
| deployment | { deploymentId?: string; buildId?: string } | — | Optional deployment metadata attached to outgoing events |
| featureFlags | Record<string, string | number | boolean | null> | — | Optional feature-flag snapshot attached to outgoing events |
| autoCapture | { errors?: boolean; unhandledRejections?: boolean } | { errors: true, unhandledRejections: true } | Controls automatic browser error capture |
| autoCaptureErrors | boolean | true | Backward-compatible alias that enables or disables both auto-capture hooks |
| debug | boolean | false | Emits SDK lifecycle messages to console.debug |
| flushIntervalMs | number | 5000 | Automatic flush cadence in milliseconds |
| batchSize | number | 20 | Queue size that triggers an immediate flush |
| flagEvalTtlMs | number | 60000 | Default TTL (ms) for the in-memory flag evaluation cache |
captureEvent(name: string, properties?, options?): void
captureEvent("checkout_completed", { value: 99.99, currency: "USD" });captureError(error: unknown, options?): void
captureError(new Error("Payment failed"), {
context: { orderId: "123" },
});identify(userId: string, traits?): void
identify(user: EmitVisionUser): void
identify("user_123", {
email: "[email protected]",
username: "jane",
});setContext(context: Record<string, unknown>): void
setContext({ page: "/checkout", experiment: "variant_b" });setDeploymentContext(context: { deploymentId?: string; buildId?: string }): void
setDeploymentContext({ deploymentId: "deploy_123", buildId: "build_456" });setFeatureFlags(flags: Record<string, string | number | boolean | null>): void
setFeatureFlags({ newCheckout: true, pricingVariant: "control" });setTags(tags: Record<string, string>): void
setTags({ team: "payments", feature: "checkout" });flush(): Promise<void>
await flush();Feature Flag Evaluation
The SDK can fetch and evaluate feature flags from your Emit Vision project. Evaluated
variants are automatically merged into the telemetry context so that every subsequent
captureEvent or captureError call includes the active flag assignments.
import {
init,
evaluateFlags,
getFlag,
refreshFlags,
} from "@emit-vision/sdk-js";
init({
dsn: "http://evk_local_development_seed_key_000000000000@localhost:4301/v1",
environment: "production",
});
// Fetch all active flags for a user. Pass evaluationKey explicitly —
// the SDK never reads email or username automatically.
const flags = await evaluateFlags({ evaluationKey: "user_abc123" });
// flags → { "new-checkout": true, "pricing-variant": "control", ... }
// Fetch a single flag with a typed fallback.
const showNewCheckout = await getFlag("new-checkout", false, {
evaluationKey: "user_abc123",
});
// Force a fresh fetch (bypass cache) after a flag change.
await refreshFlags({ evaluationKey: "user_abc123" });evaluateFlags(options: FlagEvaluationOptions): Promise<FeatureFlagsContext>
Fetches all active flags for the given evaluation key. Results are cached in memory
for flagEvalTtlMs milliseconds (default: 60 000). Network failures return an empty
object without throwing.
getFlag<T>(flagKey, fallback, options): Promise<T>
Returns the value for a single flag. Returns fallback when the flag is absent or when
the network is unavailable. Never throws.
refreshFlags(options: FlagEvaluationOptions): Promise<FeatureFlagsContext>
Bypasses the in-memory cache and performs a fresh fetch. Useful immediately after a flag change in the dashboard.
FlagEvaluationOptions
| Option | Type | Required | Description |
| --------------- | ---------- | -------- | --------------------------------------------------------------------------- |
| evaluationKey | string | Yes | Opaque key used to bucket the caller (e.g. user ID, device ID, session ID). |
| environment | string | No | Overrides the environment set at init time for this request. |
| ttlMs | number | No | Per-call TTL override in milliseconds. |
| flagKeys | string[] | No | Limit evaluation to specific flag keys. Omit to evaluate all active flags. |
Set the default cache TTL at init time with the flagEvalTtlMs option (default: 60 000).
init({
dsn: "...",
flagEvalTtlMs: 30_000, // refresh evaluations every 30 s
});Notes
- Manual
captureError()calls mark errors as handled. - Auto-captured
window.errorandunhandledrejectionevents are marked as unhandled. - The queue is in-memory only, so call
flush()before critical navigations if you need immediate delivery. - Flag evaluations are cached in memory only — nothing is written to
localStorage. - Do not use
emailorusernameas theevaluationKey— use an opaque user ID or session ID. - Use the helper packages when they reduce boilerplate, but keep direct browser SDK usage for the simplest client-side apps.
