Skip to content

TypeScript SDK Reference

The official TypeScript SDK for the SubscribeFlow API. Synchronous client initialization, full type safety.

Installation

npm install @subscribeflow/sdk

Or with bun:

bun add @subscribeflow/sdk

Client initialization

import { SubscribeFlowClient } from '@subscribeflow/sdk';

const client = new SubscribeFlowClient({
  apiKey: process.env.SUBSCRIBEFLOW_API_KEY!,
  baseUrl: 'https://api.subscribeflow.net', // default
});

Resources

subscribers

create(params)

Create a new subscriber.

const subscriber = await client.subscribers.create({
  email: 'alice@example.com',
  tags: ['newsletter'],
  metadata: { source: 'website' },
});

get(subscriberId)

Get a subscriber by ID.

const subscriber = await client.subscribers.get('subscriber-id');

getByEmail(email)

Get a subscriber by email address.

const subscriber = await client.subscribers.getByEmail('alice@example.com');

list(params?)

List subscribers with cursor-based pagination.

const { items, cursor, total } = await client.subscribers.list({
  limit: 50,
  status: 'active',
});

update(subscriberId, params)

Update subscriber fields.

const updated = await client.subscribers.update('subscriber-id', {
  metadata: { plan: 'professional' },
});

delete(subscriberId)

Permanently delete a subscriber and all associated data.

await client.subscribers.delete('subscriber-id');

addTags(subscriberId, params)

Add tags to a subscriber.

await client.subscribers.addTags('subscriber-id', {
  tags: ['beta-testers'],
});

removeTag(subscriberId, tagSlug)

Remove a single tag from a subscriber.

await client.subscribers.removeTag('subscriber-id', 'beta-testers');

generatePreferenceToken(subscriberId)

Generate a preference center token.

const tokenResponse = await client.subscribers.generatePreferenceToken(
  'subscriber-id',
);
console.log(tokenResponse.token);

tags

create(params)

Create a new tag.

const tag = await client.tags.create({
  name: 'Product Updates',
  description: 'New features and improvements',
  category: 'product',
  is_public: true,
});

get(tagId)

Get a tag by ID.

const tag = await client.tags.get('tag-id');

getByName(name)

Get a tag by name.

const tag = await client.tags.getByName('Product Updates');

list(params?)

List all tags, optionally filtered by category.

const { items } = await client.tags.list({ category: 'product' });

update(tagId, params)

Update tag fields.

await client.tags.update('tag-id', { description: 'Updated description' });

delete(tagId)

Delete a tag and remove all subscriber associations.

await client.tags.delete('tag-id');

templates

create(params)

Create an email template.

const template = await client.templates.create({
  name: 'Welcome Email',
  subject: 'Welcome to {{company}}!',
  mjml_content: '<mjml><mj-body>...</mj-body></mjml>',
  category: 'transactional',
});

get(templateId)

Get a template by ID.

const template = await client.templates.get('template-id');

getBySlug(slug)

Get a template by slug.

const template = await client.templates.getBySlug('welcome-email');

list(params?)

List templates, optionally filtered by category.

const { items } = await client.templates.list({ category: 'transactional' });

update(templateId, params)

Update template fields.

await client.templates.update('template-id', { subject: 'New Subject' });

delete(templateId)

Delete a template.

await client.templates.delete('template-id');

preview(templateId, variables?)

Render a template with variables and return the HTML output.

const preview = await client.templates.preview('template-id', {
  company: 'Acme Inc',
});
console.log(preview.html);

campaigns

create(params)

Create a campaign draft.

const campaign = await client.campaigns.create({
  name: 'March Newsletter',
  template_id: 'template-uuid',
  tag_filter: { include_tags: ['newsletter'], match: 'any' },
});

get(campaignId)

Get a campaign by ID.

const campaign = await client.campaigns.get('campaign-id');

list(params?)

List campaigns, optionally filtered by status.

const campaigns = await client.campaigns.list({ status: 'draft' });

update(campaignId, params)

Update campaign fields.

await client.campaigns.update('campaign-id', { name: 'Updated Name' });

send(campaignId)

Send a campaign to all matching subscribers.

const result = await client.campaigns.send('campaign-id');
console.log(`Sending to ${result.total_recipients} recipients`);

cancel(campaignId)

Cancel a running campaign.

await client.campaigns.cancel('campaign-id');

duplicate(campaignId)

Duplicate a campaign as a new draft.

const newCampaign = await client.campaigns.duplicate('campaign-id');

retry(campaignId)

Retry a failed campaign.

await client.campaigns.retry('campaign-id');

countRecipients(campaignId)

Preview how many subscribers match the campaign's tag filter.

const count = await client.campaigns.countRecipients('campaign-id');
console.log(`${count.count} subscribers`);

emails

send(params)

Send a transactional email to a single recipient.

const result = await client.emails.send({
  template_slug: 'welcome-email',
  to: 'alice@example.com',
  variables: { company: 'Acme Inc' },
  idempotency_key: 'welcome-alice-2024',
});

webhooks

create(params)

Create a webhook endpoint. Returns the signing secret.

const webhook = await client.webhooks.create({
  url: 'https://your-app.com/webhooks/subscribeflow',
  events: ['subscriber.created', 'tag.subscribed'],
});
console.log('Secret:', webhook.signing_secret);

get(webhookId)

Get a webhook by ID.

const webhook = await client.webhooks.get('webhook-id');

list()

List all webhook endpoints.

const { items } = await client.webhooks.list();

update(webhookId, params)

Update webhook fields.

await client.webhooks.update('webhook-id', {
  events: ['subscriber.created'],
});

delete(webhookId)

Delete a webhook endpoint.

await client.webhooks.delete('webhook-id');

test(webhookId, eventType?)

Send a test event to a webhook endpoint.

const result = await client.webhooks.test('webhook-id', 'subscriber.created');
console.log('Success:', result.success);

listDeliveries(webhookId)

List delivery history for a webhook.

const deliveries = await client.webhooks.listDeliveries('webhook-id');

retryDelivery(webhookId, deliveryId)

Retry a failed delivery.

await client.webhooks.retryDelivery('webhook-id', 'delivery-id');

getDeliveryStats(webhookId)

Get delivery statistics for a webhook.

const stats = await client.webhooks.getDeliveryStats('webhook-id');
console.log(`Success rate: ${stats.success_rate}%`);

rotateSecret(webhookId)

Rotate the signing secret.

const rotated = await client.webhooks.rotateSecret('webhook-id');
console.log('New secret:', rotated.signing_secret);

triggers

create(params)

Create an event-based email trigger.

const trigger = await client.triggers.create({
  event_type: 'subscriber.created',
  template_id: 'welcome-template-uuid',
  description: 'Send welcome email on signup',
});

get(triggerId)

Get a trigger by ID.

const trigger = await client.triggers.get('trigger-id');

list()

List all triggers.

const triggers = await client.triggers.list();

update(triggerId, params)

Update trigger fields.

await client.triggers.update('trigger-id', { is_active: false });

delete(triggerId)

Delete a trigger.

await client.triggers.delete('trigger-id');

billing

getSubscription()

Get the current billing subscription.

const subscription = await client.billing.getSubscription();

createCheckoutSession(plan)

Create a Stripe Checkout session for plan upgrade.

const session = await client.billing.createCheckoutSession('starter');
console.log('Checkout URL:', session.url);

createPortalSession()

Create a Stripe Billing Portal session.

const session = await client.billing.createPortalSession();
console.log('Portal URL:', session.url);

syncSubscription()

Synchronize the subscription state with Stripe.

await client.billing.syncSubscription();

preferenceCenter

Access preference center operations using a subscriber token.

const prefCenter = client.preferenceCenter(token);

getInfo()

Get the subscriber's preferences and available tags.

const info = await prefCenter.getInfo();

subscribeTag(tagId)

Subscribe to a tag.

await prefCenter.subscribeTag('tag-id');

unsubscribeTag(tagId)

Unsubscribe from a tag.

await prefCenter.unsubscribeTag('tag-id');

exportData()

Export all subscriber data as JSON (DSGVO Art. 20).

const exportData = await prefCenter.exportData();

deleteAccount()

Permanently delete the subscriber account (DSGVO Art. 17).

await prefCenter.deleteAccount();

TypeScript types

The SDK provides full type definitions. You can import component schemas directly:

import type { paths, components } from '@subscribeflow/sdk';

type Subscriber = components['schemas']['SubscriberResponse'];
type Tag = components['schemas']['TagResponse'];
type Campaign = components['schemas']['CampaignResponse'];

const subscriber: Subscriber = await client.subscribers.get('id');

Error handling

All errors extend SubscribeFlowError:

import { SubscribeFlowError } from '@subscribeflow/sdk';

try {
  await client.subscribers.get('non-existent-id');
} catch (error) {
  if (error instanceof SubscribeFlowError) {
    console.error('Status:', error.status);   // HTTP status code
    console.error('Type:', error.type);        // Error type identifier
    console.error('Detail:', error.detail);    // Human-readable message
  }
}

Check specific error types by status code:

try {
  await client.subscribers.create({ email: 'alice@example.com' });
} catch (error) {
  if (error instanceof SubscribeFlowError) {
    switch (error.status) {
      case 401:
        console.error('Invalid API key');
        break;
      case 402:
        console.error('Plan limit exceeded:', error.detail);
        break;
      case 404:
        console.error('Not found');
        break;
      case 422:
        console.error('Validation failed:', error.detail);
        break;
      case 429:
        console.error('Rate limit exceeded');
        break;
      default:
        console.error('API error:', error.detail);
    }
  }
}