TypeScript SDK Reference
The official TypeScript SDK for the SubscribeFlow API. Synchronous client initialization, full type safety.
Installation
Or with bun:
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.
getByEmail(email)
Get a subscriber by email address.
list(params?)
List subscribers with cursor-based pagination.
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.
addTags(subscriberId, params)
Add tags to a subscriber.
removeTag(subscriberId, tagSlug)
Remove a single tag from a subscriber.
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.
getByName(name)
Get a tag by name.
list(params?)
List all tags, optionally filtered by category.
update(tagId, params)
Update tag fields.
delete(tagId)
Delete a tag and remove all subscriber associations.
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.
getBySlug(slug)
Get a template by slug.
list(params?)
List templates, optionally filtered by category.
update(templateId, params)
Update template fields.
delete(templateId)
Delete a template.
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.
list(params?)
List campaigns, optionally filtered by status.
update(campaignId, params)
Update campaign fields.
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.
duplicate(campaignId)
Duplicate a campaign as a new draft.
retry(campaignId)
Retry a failed campaign.
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.
list()
List all webhook endpoints.
update(webhookId, params)
Update webhook fields.
delete(webhookId)
Delete a webhook endpoint.
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.
retryDelivery(webhookId, deliveryId)
Retry a failed delivery.
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.
list()
List all triggers.
update(triggerId, params)
Update trigger fields.
delete(triggerId)
Delete a trigger.
billing
getSubscription()
Get the current billing subscription.
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.
preferenceCenter
Access preference center operations using a subscriber token.
getInfo()
Get the subscriber's preferences and available tags.
subscribeTag(tagId)
Subscribe to a tag.
unsubscribeTag(tagId)
Unsubscribe from a tag.
exportData()
Export all subscriber data as JSON (DSGVO Art. 20).
deleteAccount()
Permanently delete the subscriber account (DSGVO Art. 17).
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);
}
}
}