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,
localStoragein browsers) - Verbose logging for debugging
- Full TypeScript types out of the box
- Zero runtime dependencies
npm install @hintway/sdk
# or
pnpm add @hintway/sdk
# or
yarn add @hintway/sdkRequires Node.js 18+ (for native fetch). All modern browsers and edge runtimes are supported.
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).
On initialization, the SDK:
- Loads or generates a persistent device identifier
- Node: stored in
analytics.idnext toprocess.cwd() - Browser: stored in
localStorageunderhintway.analytics.id - Edge runtimes: in-memory only (regenerated on cold start unless you provide a custom storage adapter)
- Node: stored in
- Creates a new session ID
- Starts a background task to validate the tenant against
GET /validate?tenant_id=<id> - 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).
hintway.trackEvent('app_started');hintway.trackEvent('user_logged_in', 'admin_user');hintway.trackEvent('order_completed', {
order_id: 12345,
total_amount: 99.99,
currency: 'USD',
items_count: 3,
});Attach a custom JSON object to all subsequent events. Useful for user context, environment metadata, region, etc.
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');hintway.setCustomData(null);
// or:
hintway.clearCustomData();- 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)
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 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: whenbatchedTrackEventis called with a string, the string is sent raw (not wrapped in{"data": "..."}). When called with an object, the object is JSON-encoded directly.trackEventwraps strings in{"data": "..."}. This asymmetry is preserved on purpose so payloads match the Go SDK byte-for-byte.
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.
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();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);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();
});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');
},
};| 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(). |
| 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. |
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 whenautoBatching: falseand server is alive)POST /batch—{ "tracks": [...] }(used by both auto and manual batching)
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 --noEmitMIT — see LICENSE.