Skip to content

@hookbase/sdk

The Hookbase SDK provides a type-safe client for sending webhooks to your customers.

Installation

bash
npm install @hookbase/sdk

Quick Start

typescript
import { Hookbase } from '@hookbase/sdk';

const hookbase = new Hookbase({
  apiKey: process.env.HOOKBASE_API_KEY,
});

// Send a webhook
await hookbase.messages.send(appId, {
  eventType: 'order.created',
  payload: {
    orderId: 'ord_123',
    amount: 99.99,
  },
});

Client Configuration

typescript
const hookbase = new Hookbase({
  apiKey: process.env.HOOKBASE_API_KEY,
  baseUrl: 'https://api.hookbase.app', // Optional, defaults to production
  timeout: 30000, // Request timeout in ms
  retries: 3, // Number of retries on failure
});

Applications

Applications represent your customers. Each customer should have one application.

Create Application

typescript
const app = await hookbase.applications.create({
  name: 'Acme Corp',
  uid: 'customer_123', // Your internal customer ID
  metadata: {
    plan: 'enterprise',
    email: '[email protected]',
  },
});

Get or Create Application

typescript
// Returns existing app or creates new one
const app = await hookbase.applications.getOrCreate('customer_123', {
  name: 'Acme Corp',
});

List Applications

typescript
// Paginated list
const { data, hasMore } = await hookbase.applications.list({
  limit: 50,
  offset: 0,
});

// Async iterator for all applications
for await (const app of hookbase.applications.listAll()) {
  console.log(app.name);
}

Get by UID

typescript
const app = await hookbase.applications.getByUid('customer_123');

Event Types

Event types define the webhook events your customers can subscribe to.

Create Event Type

typescript
await hookbase.eventTypes.create({
  name: 'order.created',
  displayName: 'Order Created',
  description: 'Triggered when a new order is placed',
  category: 'Orders',
  schema: {
    type: 'object',
    properties: {
      orderId: { type: 'string' },
      amount: { type: 'number' },
    },
  },
});

List Event Types

typescript
const eventTypes = await hookbase.eventTypes.list({
  category: 'Orders',
});

Messages

Messages are the webhooks you send to your customers.

Send Message

typescript
const result = await hookbase.messages.send(appId, {
  eventType: 'order.created',
  payload: {
    orderId: 'ord_123',
    amount: 99.99,
    currency: 'USD',
  },
  eventId: `order_created_${order.id}`, // Idempotency key
  metadata: {
    source: 'api',
  },
});

console.log(result.messageId);
console.log(result.outboundMessages); // Delivery attempts

List Messages

typescript
const messages = await hookbase.messages.list(appId, {
  eventType: 'order.created',
  startDate: '2024-01-01',
  endDate: '2024-01-31',
});

Resend Message

typescript
await hookbase.messages.resend(appId, messageId);

Retry Failed Delivery

typescript
await hookbase.messages.retry(appId, outboundMessageId);

Endpoints

Endpoints are managed by your customers through the Portal, but you can also manage them programmatically.

List Endpoints

typescript
const endpoints = await hookbase.endpoints.list(appId);

Get Endpoint Statistics

typescript
const stats = await hookbase.endpoints.getStats(appId, endpointId);
// { successRate: 0.99, avgLatency: 150, totalDeliveries: 1000 }

Portal Tokens

Portal tokens authenticate the embedded Portal component.

Create Portal Token

typescript
const token = await hookbase.portalTokens.create(appId, {
  expiresIn: 3600, // 1 hour
});

// Return token.token to your frontend

Webhook Verification

Help your customers verify incoming webhooks.

Create Verifier

typescript
import { createWebhook } from '@hookbase/sdk';

const webhook = createWebhook(process.env.WEBHOOK_SECRET);

// Verify and parse webhook
const payload = webhook.verify(rawBody, headers);

Manual Verification

typescript
import { verifySignature } from '@hookbase/sdk';

const isValid = verifySignature({
  payload: rawBody,
  signature: headers['webhook-signature'],
  timestamp: headers['webhook-timestamp'],
  secret: process.env.WEBHOOK_SECRET,
});

Error Handling

typescript
import { HookbaseError, RateLimitError, ValidationError } from '@hookbase/sdk';

try {
  await hookbase.messages.send(appId, message);
} catch (error) {
  if (error instanceof RateLimitError) {
    // Wait and retry
    await sleep(error.retryAfter * 1000);
    await hookbase.messages.send(appId, message);
  } else if (error instanceof ValidationError) {
    console.error('Invalid request:', error.errors);
  } else if (error instanceof HookbaseError) {
    console.error('API error:', error.message, error.code);
  }
}

TypeScript Support

The SDK is fully typed. Import types as needed:

typescript
import type {
  Application,
  Endpoint,
  EventType,
  Message,
  OutboundMessage,
} from '@hookbase/sdk';

Released under the MIT License.