growlytics-tracking
v1.0.4
Published
Enterprise-grade Node.js SDK for Growlytics tracking service with high performance batching, queueing, retries, and offline resilience.
Maintainers
Readme
Growlytics Node.js Tracking SDK
An enterprise-grade, high-performance, and resilient Node.js SDK for the Growlytics event tracking platform.
[!TIP] 📖 Looking for a step-by-step integration guide? Check out the INTEGRATION_GUIDE.md included in this package. It contains simple, layman-friendly examples and a specialized prompt to copy-paste for your AI coding assistant (like ChatGPT/Claude/Gemini/Copilot) to automate the integration!
Key Features
- Zero Dependencies: Keeps your
node_modulescompletely clean and free of supply-chain vulnerabilities. - Dual Package Support: Native ES Module (
esm) and CommonJS (cjs) builds. - TypeScript Support: Full, detailed TypeScript declarations out of the box for autocomplete on tracking structures.
- In-Memory Buffering & Batching: Groups events together and transmits them in batches to reduce network overhead.
- Network Resilience & Retries: Automatic HTTP requests retries with exponential backoff and full jitter for handling intermittent network failures.
- Automatic Context Population: Automatically populates server OS, runtime version, ISO timestamps, and generates random UUIDs for
anonymous_idandrequest_idif missing. - Graceful Shutdown: Automatically flushes queued events when your Node process exits.
Installation
Install via npm:
npm install growlytics-trackingOr via yarn:
yarn add growlytics-trackingQuick Start
1. Global Singleton Pattern (Recommended)
Ideal for single-instance web servers (e.g. Express, Koa, NestJS). Call initiate once at app startup, then import and track events anywhere.
CommonJS (JavaScript):
const Growlytics = require('growlytics-tracking');
// Initialize the tracker once at application startup
Growlytics.initiate({
clientId: 1001,
workspaceId: 2001,
applicationId: 3001,
apiKey: 'your-api-key-here',
debug: false
});
// Track events anywhere in your code
Growlytics.track('product_view', {
session_id: 'sess_123',
user_identifier: {
customer_id: 'cust_123',
email: '[email protected]',
},
product: {
product_id: 'SKU123',
name: 'Bathroom Mat',
price: 499,
currency: 'INR'
}
});ES Modules (TypeScript / JavaScript):
import Growlytics from 'growlytics-tracking';
// Initialize
Growlytics.initiate({
clientId: 1001,
workspaceId: 2001,
applicationId: 3001,
apiKey: 'your-api-key-here',
batchSize: 20,
flushIntervalMs: 2000
});
// Track
Growlytics.track('add_to_cart', {
session_id: 'sess_123',
cart: {
cart_id: 'cart_123',
total_items: 1,
total_amount: 499
}
});2. Multi-Instance Pattern
If your application needs to connect to multiple workspaces or clients, instantiate the tracker class directly:
import { GrowlyticsTracker } from 'growlytics-tracking';
const trackerA = new GrowlyticsTracker({
clientId: 1001,
workspaceId: 2001,
apiKey: 'key-a'
});
const trackerB = new GrowlyticsTracker({
clientId: 5005,
workspaceId: 9009,
apiKey: 'key-b'
});
trackerA.track('custom_event', { data: 'value' });SDK Configuration Options
Initialize the SDK with the following configuration options:
| Option | Type | Default | Description |
|---|---|---|---|
| clientId | number | 0 | Fallback Client ID (if not provided per event payload). |
| workspaceId | number | 0 | Fallback Workspace ID (if not provided per event payload). |
| applicationId | number | 0 | Fallback Application ID (if not provided per event payload). |
| apiKey | string | "" | Authentication write key passed via the Authorization header. |
| baseUrl | string | "https://api.growlytics.co" | Base URL of the Growlytics event ingestion endpoint. |
| path | string | "/events" | Ingestion path appended to baseUrl. |
| batchSize | number | 20 | Max number of events sent in a single HTTP batch. |
| flushIntervalMs | number | 2000 | Periodically flushes queued events (in milliseconds). |
| maxQueueSize | number | 1000 | Max buffer capacity. Discards oldest events if queue overflows. |
| maxRetries | number | 3 | Number of times to retry failed connection drops/5xx responses. |
| retryInitialDelayMs | number | 1000 | Base delay for the first exponential retry. |
| retryMaxDelayMs | number | 30000 | Maximum cap on retry backoff delay. |
| debug | boolean | false | Enables logs for troubleshooting. |
| disableAutoContext | boolean | false | Set to true to disable automatic server environment context capture. |
| onError | function | undefined | Callback invoked when a batch fails permanently after all retries. |
Automatic Context and Value Generations
To save developer time and ensure data reliability, the SDK automatically generates and merges fields:
- Timestamps: If
timestampis omitted in the event, the current system ISO time is added. - UUID Generations:
anonymous_id: If not provided, a random, cryptographically secure UUID v4 is generated for the event.request_id: A unique, random UUID v4 is generated for every tracked event to prevent duplicate ingestion.
- Device Details: Unless
disableAutoContextis set totrue, the SDK gathers the server environment (Node version, OS platform, and OS release) and populates thedeviceobject:
Note: Any nested values provided inside the event"device": { "device_type": "server", "os": "darwin", "os_version": "21.6.0", "browser": "node", "browser_version": "v18.16.0", "language": "en-US", "user_agent": "growlytics-node-sdk/1.0.0 (node v18.16.0; darwin 21.6.0)" }deviceparameter will override these defaults.
Advanced Usage
1. Serverless Environments (AWS Lambda, Vercel)
In serverless execution environments, Node's event loop may be frozen immediately after returning a response. To guarantee that tracked events reach Growlytics before the environment suspends, call .flush() synchronously before terminating your function:
exports.handler = async (event) => {
Growlytics.track('lambda_execution', { function_name: 'payment-processor' });
// Force flush the tracking queue immediately
await Growlytics.flush();
return { statusCode: 200, body: 'Done' };
};2. Failure Callbacks (onError)
If you want to log permanent failure payloads to a fallback logger, database, or alerting tool, register the onError hook:
Growlytics.initiate({
clientId: 1001,
onError: (error, failedEvents) => {
console.error(`Growlytics Delivery Failure: ${error.message}`);
// Save to backup file or dispatch to alerting systems
backupLogger.log(failedEvents);
}
});License
MIT License. Copyright (c) Growlytics.
