Skip to main content

Overview

The EmitKit TypeScript/JavaScript SDK provides a type-safe, developer-friendly interface for monitoring critical product moments and sending real-time alerts.

Features

Type-Safe

Full TypeScript support with auto-generated types

Zero Dependencies

No external runtime dependencies, minimal bundle size

Error Handling

Type-safe error classes with detailed information

Rate Limiting

Automatic rate limit tracking and handling

Idempotency

Built-in support for safe retries

Tree-Shakeable

Optimized bundle size with ES modules

Installation

npm install @emitkit/js

Basic Usage

import { EmitKit } from '@emitkit/js';

const client = new EmitKit('emitkit_xxxxxxxxxxxxxxxxxxxxx');

// Create an event
const result = await client.events.create({
  channelName: 'payments',
  title: 'Payment Received',
  metadata: { amount: 99.99 }
});

console.log('Event ID:', result.data.id);
console.log('Rate limit remaining:', result.rateLimit.remaining);

Configuration

Basic Configuration

const client = new EmitKit('your_api_key');

Advanced Configuration

const client = new EmitKit('your_api_key', {
  // Custom base URL (for self-hosted instances)
  baseUrl: 'https://api.your-domain.com',

  // Request timeout in milliseconds (default: 30000)
  timeout: 60000,

  // Custom fetch implementation
  fetch: customFetch
});

Methods

events.create()

Create a new event and optionally send notifications. Parameters:
  • channelName (string, required): Channel name (auto-creates if doesn’t exist)
  • title (string, required): Event title
  • description (string, optional): Event description
  • icon (string, optional): Single emoji icon
  • tags (string[], optional): Array of tags
  • metadata (object, optional): Custom JSON metadata
  • userId (string | null, optional): User identifier
  • notify (boolean, optional): Send push notification to connected devices (default: true)
  • source (string, optional): Source identifier
Options:
  • idempotencyKey (string): For safe retries
  • timeout (number): Request timeout override
  • headers (object): Additional headers
Returns: Promise<EmitKitResponse>
const result = await client.events.create({
  channelName: 'payments',
  title: 'Payment Received',
  description: 'User upgraded to Pro plan',
  icon: '💰',
  tags: ['payment', 'upgrade'],
  metadata: {
    amount: 99.99,
    currency: 'USD',
    plan: 'pro'
  },
  userId: 'user_123',
  notify: true
});

identify()

Create or update a user identity with properties and aliases. Parameters:
  • user_id (string, required): Your internal user ID
  • properties (object, optional): Custom user properties
  • aliases (string[], optional): Alternative identifiers
Returns: Promise<EmitKitResponse<IdentifyUserResponse>>
await client.identify({
  user_id: 'user_123',
  properties: {
    email: '[email protected]',
    name: 'John Doe',
    plan: 'pro'
  },
  aliases: ['[email protected]', 'johndoe']
});

Response Types

EmitKitResponse

interface EmitKitResponse<T = any> {
  data: T;                    // Response data
  rateLimit: RateLimitInfo;   // Rate limit info
  requestId: string;          // Request ID for debugging
  wasReplayed: boolean;       // Idempotent replay flag
}

RateLimitInfo

interface RateLimitInfo {
  limit: number;      // Max requests allowed
  remaining: number;  // Remaining requests
  reset: number;      // Unix timestamp when limit resets
  resetIn: number;    // Milliseconds until reset
}

Error Handling

The SDK provides type-safe error classes for different error scenarios:
import {
  EmitKit,
  EmitKitError,
  RateLimitError,
  ValidationError
} from '@emitkit/js';

try {
  await client.events.create({...});
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log('Rate limit exceeded!');
    console.log(`Retry in ${error.rateLimit.resetIn}ms`);
  } else if (error instanceof ValidationError) {
    console.log('Validation failed:');
    error.validationErrors.forEach(err => {
      console.log(`- ${err.path.join('.')}: ${err.message}`);
    });
  } else if (error instanceof EmitKitError) {
    console.log(`API Error ${error.statusCode}:`, error.message);
    console.log('Request ID:', error.requestId);
  }
}
See Error Handling for detailed documentation.

Rate Limit Tracking

Access rate limit information from responses:
const result = await client.events.create({...});

console.log(result.rateLimit);
// {
//   limit: 100,
//   remaining: 95,
//   reset: 1733270400,
//   resetIn: 45000
// }

// Access last known rate limit
console.log(client.rateLimit);

Next Steps