Skip to content

About

TS and JS SDK for Hintway

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Hintway Analytics JavaScript / TypeScript SDK

The Hintway Analytics JS/TS SDK is a lightweight, isomorphic library for sending analytics events to the Hintway Analytics platform from any JavaScript runtime: Node.js, modern browsers, and edge runtimes (Cloudflare Workers, Vercel Edge, Deno, Bun).

It is a faithful port of the official Hintway Go SDK, with the same wire format, endpoints, and behavior. If you are already using the Go SDK on the backend, this one is a drop-in equivalent for your frontend or Node services.

It supports:

  • Immediate and batched event tracking
  • Automatic retry when the server becomes available
  • Persistent device identity (file-based in Node, localStorage in browsers)
  • Verbose logging for debugging
  • Full TypeScript types out of the box
  • Zero runtime dependencies

Installation

npm install @hintway/sdk
# or
pnpm add @hintway/sdk
# or
yarn add @hintway/sdk

Requires Node.js 18+ (for native fetch). All modern browsers and edge runtimes are supported.

Quick Start

1. Initialize the SDK

import { Hintway } from '@hintway/sdk';

// Get the singleton instance
const hintway = Hintway.instance();

// Optional: Enable verbose logging to see network requests
hintway.setVerbose(true);

// Initialize the SDK
hintway.init({
  tenantId: '481b9cfb-4b48-4d99-a310-d383c6cc5d3b',
  serverUrl: 'https://in.hintway.app',
  platform: 'my_backend_service',
  appVersion: '1.0.0',
  autoBatching: true,
  flushIntervalSec: 2,
});

// Wait briefly for background tenant validation to complete
await new Promise((r) => setTimeout(r, 1000));

// Your code here...

// Always shutdown when done to flush remaining events
await hintway.shutdown();

⚠️ Important: init() must be called before sending any events. Subsequent calls are ignored (idempotent).

Internal Behavior

On initialization, the SDK:

  1. Loads or generates a persistent device identifier
    • Node: stored in analytics.id next to process.cwd()
    • Browser: stored in localStorage under hintway.analytics.id
    • Edge runtimes: in-memory only (regenerated on cold start unless you provide a custom storage adapter)
  2. Creates a new session ID
  3. Starts a background task to validate the tenant against GET /validate?tenant_id=<id>
  4. Enables or disables analytics based on server availability

If the server is unreachable, events are safely queued in memory until connectivity is restored (when autoBatching is on).

Tracking Events

Simple Event

hintway.trackEvent('app_started');

Event with String Payload

hintway.trackEvent('user_logged_in', 'admin_user');

Event with Structured Data

hintway.trackEvent('order_completed', {
  order_id: 12345,
  total_amount: 99.99,
  currency: 'USD',
  items_count: 3,
});

Custom Data

Attach a custom JSON object to all subsequent events. Useful for user context, environment metadata, region, etc.

Setting Custom Data

hintway.setCustomData({
  user_id: 'user_123',
  subscription: 'premium',
  environment: 'production',
  region: 'us-east-1',
});

// Now all subsequent events include this custom data
hintway.trackEvent('feature_used', 'dark_mode_toggle');

Clearing Custom Data

hintway.setCustomData(null);
// or:
hintway.clearCustomData();

Behavior

  • Custom data persists across event calls until explicitly cleared or replaced
  • Empty / null custom data is omitted from the request payload
  • Non-serializable values are silently dropped (mirrors the Go SDK)

Batching

Automatic Batching

When autoBatching is enabled at init time, events tracked via trackEvent() are queued automatically and flushed every flushIntervalSec seconds:

hintway.init({
  tenantId,
  platform,
  appVersion,
  autoBatching: true,
  flushIntervalSec: 10,
});

If the server is unreachable, queued events remain in memory until the server becomes available again.

Manual Batching

Manual batching gives you explicit control over when events are sent — useful at the end of a transaction, an API request, or a navigation:

hintway.batchedTrackEvent('transaction_started', 'checkout');
hintway.batchedTrackEvent('payment_processed', {
  amount: 49.99,
  method: 'credit_card',
  status: 'success',
});

hintway.flushManualBatch();

⚠️ Wire-format note for compatibility with the Go SDK: when batchedTrackEvent is called with a string, the string is sent raw (not wrapped in {"data": "..."}). When called with an object, the object is JSON-encoded directly. trackEvent wraps strings in {"data": "..."}. This asymmetry is preserved on purpose so payloads match the Go SDK byte-for-byte.

Lifecycle Handling

Always call shutdown() before your application exits. It cancels background timers, drains any remaining queued events into a final batch, appends an app_exit event, and best-effort-flushes the result with a 2-second hard timeout.

Node script

import { Hintway } from '@hintway/sdk';

async function main() {
  const hintway = Hintway.instance();
  hintway.init({
    tenantId: 'tenant-id',
    serverUrl: 'https://in.hintway.app',
    platform: 'cli_app',
    appVersion: '1.0.0',
    autoBatching: true,
    flushIntervalSec: 5,
  });

  hintway.trackEvent('app_started');
  // ... application logic ...
  hintway.trackEvent('app_completed');

  console.log('Shutting down...');
  await hintway.shutdown();
  console.log('Done!');
}

main();

Express / HTTP server

import express from 'express';
import { Hintway } from '@hintway/sdk';

const hintway = Hintway.instance();
hintway.init({
  tenantId: 'tenant-id',
  platform: 'web_service',
  appVersion: '1.0.0',
  autoBatching: true,
  flushIntervalSec: 10,
});

const app = express();

app.use((req, _res, next) => {
  hintway.trackEvent('api_request', { path: req.path, method: req.method });
  next();
});

// Flush on graceful shutdown
async function gracefulShutdown() {
  await hintway.shutdown();
  process.exit(0);
}
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

Browser (SPA)

import { Hintway } from '@hintway/sdk';

const hintway = Hintway.instance();
hintway.init({
  tenantId: 'tenant-id',
  platform: 'web_app',
  appVersion: '1.0.0',
  autoBatching: true,
  flushIntervalSec: 5,
});

hintway.trackEvent('page_view', { path: window.location.pathname });

// Flush whatever is queued before the user leaves
window.addEventListener('beforeunload', () => {
  hintway.flushManualBatch();
});

Edge runtime (Cloudflare Workers / Vercel Edge)

import { Hintway } from '@hintway/sdk';

export default {
  async fetch(request: Request): Promise<Response> {
    const hintway = Hintway.instance();
    hintway.init({
      tenantId: 'tenant-id',
      platform: 'edge_worker',
      autoBatching: false, // requests are short — send immediately
    });

    hintway.trackEvent('edge_request', { path: new URL(request.url).pathname });

    // shutdown() ensures the final flush happens before the request ends
    await hintway.shutdown();
    return new Response('ok');
  },
};

API Reference

Method Description
Hintway.instance() Returns the singleton manager.
setVerbose(boolean) Enable/disable [Hintway]-prefixed console logs.
init(options) Initialize. Idempotent. See HintwayInitOptions.
trackEvent(name, props?) Track an event. props may be a string, an object, or omitted.
batchedTrackEvent(name, props?) Add an event to the manual batch queue.
flushManualBatch() Send the accumulated manual batch as one POST /batch.
setCustomData(map) Attach a custom JSON object to all subsequent events.
clearCustomData() Remove any previously-set custom data.
shutdown() Best-effort final flush + cancel background tasks.
setIdentityStorage(storage) Override the persistent-identity storage. Call before init().

HintwayInitOptions

Field Type Default Description
tenantId string — Required. Your Hintway tenant ID.
serverUrl string https://in.hintway.app Server base URL.
platform string — Required. Free-form platform identifier.
appVersion string 1.0.0 Application version string.
autoBatching boolean — Required. When true, events are queued and flushed periodically.
flushIntervalSec number 10 Auto-flush interval. Ignored when autoBatching is false.

Wire format

All requests use Content-Type: application/json. The exact JSON shape sent to the server matches the Go SDK:

{
  "tenant_id": "tenant-xyz",
  "tracking": {
    "name": "user_logged_in",
    "value": "{\"data\":\"admin\"}",
    "identity": "12345678-9abc-def0-1234-56789abcdef0",
    "session_id": "...",
    "platform": "web_app",
    "app_version": "1.0.0",
    "custom": "{\"env\":\"prod\"}",
    "timestamp": "2026-04-25T18:21:09Z"
  }
}

Endpoints:

  • GET /validate?tenant_id=<id> — tenant health check (5 s timeout)
  • POST /track — single event (used when autoBatching: false and server is alive)
  • POST /batch — { "tracks": [...] } (used by both auto and manual batching)

Building from source

npm install
npm run build      # outputs dist/index.mjs, dist/index.cjs, dist/index.d.ts
npm test           # runs the vitest suite
npm run lint       # tsc --noEmit

License

MIT — see LICENSE.

About

TS and JS SDK for Hintway

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages