thrivestack-node-sdk
Version:
Official ThriveStack Analytics SDK for Node.js and Next.js server-side applications
352 lines (255 loc) • 9.22 kB
Markdown
# thrivestack-node-sdk
Official ThriveStack Analytics SDK for Node.js and Next.js server-side applications.
[](https://badge.fury.io/js/thrivestack-node-sdk)
[](https://opensource.org/licenses/MIT)
A comprehensive analytics tracking SDK for Node.js applications with a privacy-first approach.
## Features
- **Privacy-First**: Respects Do Not Track settings and provides consent management
- **Event Batching**: Efficiently batches events to reduce API calls
- **Session Management**: Automatic session tracking with configurable timeouts
- **Geolocation**: Automatic IP detection and location information
- **User & Group Tracking**: Comprehensive user and group identification
- **TypeScript Support**: Full TypeScript support with type definitions
- **Debug Mode**: Built-in debugging capabilities for development
## Installation
```bash
npm install thrivestack-node-sdk
```
## Quick Start
### Basic Usage
```typescript
import { ThriveStack } from 'thrivestack-node-sdk';
// Initialize ThriveStack
const thriveStack = new ThriveStack({
apiKey: process.env.THRIVESTACK_API_KEY!,
source: 'my-nodejs-app'
});
// Initialize the SDK
await thriveStack.init('user123');
// Capture a page visit
await thriveStack.capturePageVisit({
title: 'Home Page',
url: 'https://myapp.com/home'
});
// Capture a custom event
await thriveStack.captureEvent('purchase_completed', {
amount: 99.99,
currency: 'USD',
product_id: 'prod_123'
});
```
### Next.js Integration
#### API Routes
```typescript
// app/api/events/route.ts
import { ThriveStack } from 'thrivestack-node-sdk';
const thriveStack = new ThriveStack({
apiKey: process.env.THRIVESTACK_API_KEY!,
source: 'nextjs-api'
});
export async function POST(request: Request) {
const { userId, eventName, properties } = await request.json();
await thriveStack.init(userId);
await thriveStack.captureEvent(eventName, properties);
return Response.json({ success: true });
}
```
#### Server Actions
```typescript
// app/actions/tracking.ts
'use server'
import { ThriveStack } from 'thrivestack-node-sdk';
const thriveStack = new ThriveStack({
apiKey: process.env.THRIVESTACK_API_KEY!,
source: 'nextjs-server-action'
});
export async function trackUserAction(userId: string, action: string, data: any) {
await thriveStack.init(userId);
await thriveStack.captureEvent('user_action', {
action_type: action,
...data
});
}
```
#### Middleware
```typescript
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { ThriveStack } from 'thrivestack-node-sdk';
const thriveStack = new ThriveStack({
apiKey: process.env.THRIVESTACK_API_KEY!,
source: 'nextjs-middleware'
});
export async function middleware(request: NextRequest) {
const response = NextResponse.next();
const userId = request.headers.get('x-user-id') || 'anonymous';
await thriveStack.init(userId);
await thriveStack.capturePageVisit({
title: `Page: ${request.nextUrl.pathname}`,
url: request.url,
path: request.nextUrl.pathname
});
return response;
}
```
## Quick Start
```typescript
import { ThriveStack } from 'thrivestack-backend-node';
// Initialize ThriveStack
const thriveStack = new ThriveStack({
apiKey: 'your-api-key-here',
source: 'my-nodejs-app'
});
// Initialize the SDK
await thriveStack.init('user123');
// Capture a page visit
await thriveStack.capturePageVisit({
title: 'Home Page',
url: 'https://myapp.com/home'
});
// Capture a custom event
await thriveStack.captureEvent('purchase_completed', {
amount: 99.99,
currency: 'USD',
product_id: 'prod_123'
});
```
## Configuration Options
```typescript
interface ThriveStackOptions {
apiKey: string; // Required: Your ThriveStack API key
apiEndpoint?: string; // Optional: Custom API endpoint (default: https://api.app.thrivestack.ai/api)
respectDoNotTrack?: boolean; // Optional: Respect DNT environment variable (default: true)
enableConsent?: boolean; // Optional: Enable consent-based tracking (default: false)
batchSize?: number; // Optional: Events to batch in one request (default: 10)
batchInterval?: number; // Optional: Milliseconds to wait before sending batched events (default: 2000)
source?: string; // Optional: Source identifier for tracking
sessionTimeout?: number; // Optional: Session timeout in milliseconds (default: 30 minutes)
debounceDelay?: number; // Optional: Session activity debounce delay (default: 2000ms)
defaultConsent?: boolean; // Optional: Default consent for analytics/marketing (default: false)
}
```
## API Reference
### Core Methods
#### `new ThriveStack(options)`
Initialize a new ThriveStack instance.
#### `async init(userId?: string, source?: string)`
Initialize the SDK with optional user ID and source.
#### `shouldTrack(): boolean`
Check if tracking is allowed based on DNT settings.
#### `isTrackingAllowed(category): boolean`
Check if specific tracking category is allowed.
### Event Tracking
#### `async capturePageVisit(pageInfo?)`
Capture a page visit event.
```typescript
await thriveStack.capturePageVisit({
title: 'Page Title',
url: 'https://example.com/page',
path: '/page',
referrer: 'https://google.com'
});
```
#### `async captureEvent(eventName, properties?)`
Capture a custom event.
```typescript
await thriveStack.captureEvent('user_action', {
action_type: 'button_click',
element_id: 'submit-btn',
value: 'form_submitted'
});
```
### User & Group Management
#### `async setUser(userId, emailId?, properties?)`
Set user information and optionally make identify API call.
```typescript
await thriveStack.setUser('user123', 'user@example.com', {
first_name: 'John',
last_name: 'Doe',
company: 'Example Corp'
});
```
#### `async setGroup(groupId, groupDomain?, groupName?, properties?)`
Set group information and optionally make group API call.
```typescript
await thriveStack.setGroup('group456', 'example.com', 'Example Corporation', {
industry: 'Technology',
size: '100-500'
});
```
### Consent Management
#### `setConsent(category, hasConsent)`
Update consent settings for a tracking category.
```typescript
thriveStack.setConsent('functional', true); // Always needed
thriveStack.setConsent('analytics', true); // User analytics
thriveStack.setConsent('marketing', false); // Marketing tracking
```
### Utility Methods
#### `getDeviceId(): string | null`
Get the current device ID.
#### `getSessionId(): string`
Get the current session ID.
#### `getInteractionHistory(): Array`
Get the interaction history.
#### `clearInteractionHistory(): void`
Clear the interaction history.
#### `getConfig(): object`
Get current configuration.
#### `enableDebugMode(): void`
Enable debug mode for troubleshooting.
## Environment Variables
- `DO_NOT_TRACK`: Set to '1' to disable tracking
- `NODE_ENV`: Used for environment detection
- `LANG`: Used for language detection
## Session Management
The SDK automatically manages sessions with the following features:
- **Automatic Session Creation**: Sessions are created when first needed
- **Session Timeout**: Configurable session timeout (default: 30 minutes)
- **Activity Tracking**: Session activity is tracked with debouncing
- **Session Persistence**: Sessions are stored in memory for the process lifetime
## Event Batching
Events are automatically batched to improve performance:
- **Batch Size**: Configurable number of events per batch (default: 10)
- **Batch Interval**: Configurable delay before sending batches (default: 2000ms)
- **Retry Logic**: Automatic retry with exponential backoff on failures
- **Queue Management**: Events are queued and processed asynchronously
## Geolocation
The SDK automatically detects location information:
- **Local IP Detection**: Uses Node.js network interfaces
- **GeoIP Lookup**: Uses geoip-lite for local lookups
- **External Service Fallback**: Falls back to ipinfo.io if needed
- **Location Data**: Includes city, region, country, coordinates, and timezone
## Error Handling
The SDK includes comprehensive error handling:
- **Network Retries**: Automatic retry with exponential backoff
- **Graceful Degradation**: Continues to work even if some features fail
- **Error Logging**: Detailed error logging for debugging
- **Fallback Mechanisms**: Multiple fallback options for critical features
## TypeScript Support
The SDK is written in TypeScript and includes full type definitions:
```typescript
import { ThriveStack, ThriveStackOptions, EventData } from 'thrivestack-backend-node';
const options: ThriveStackOptions = {
apiKey: 'your-key',
source: 'my-app'
};
const thriveStack = new ThriveStack(options);
```
## Development
### Building
```bash
npm run build
```
### Development Mode
```bash
npm run dev
```
### Running Example
```bash
npm run dev src/example.ts
```
## License
ISC
## Support
For support and questions, please refer to the ThriveStack documentation or contact support.