Skip to content

Recipes

Each recipe is a complete file you can copy. They read the API key from SMSFABRIC_API_KEY; start with an sf_test_ key so nothing reaches a real phone.

A receiver that verifies the signature on the raw body, answers within the 10-second limit, ignores duplicate deliveries and handles the event afterwards. Install express alongside the SDK.

server.ts
import express from 'express';
import { SMSFabric, SignatureVerificationError, type WebhookPayload } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
const secret = process.env.SMSFABRIC_WEBHOOK_SECRET ?? '';
const app = express();
// Keep a durable store in production (a table with a unique key on the event id).
const seen = new Set<string>();
app.post('/hooks/smsfabric', express.raw({ type: 'application/json', limit: '1mb' }), (req, res) => {
let event: WebhookPayload;
try {
event = sms.webhooks.constructEvent(req.body, req.header('SMSFabric-Signature'), secret);
} catch (err) {
if (err instanceof SignatureVerificationError) return res.sendStatus(400);
throw err;
}
res.sendStatus(200); // answer first, work afterwards
if (seen.has(event.id)) return;
seen.add(event.id);
handle(event).catch((err: unknown) => console.error('webhook handler failed', event.id, err));
});
async function handle(event: WebhookPayload): Promise<void> {
switch (event.type) {
case 'message.delivered':
case 'message.failed':
console.log(event.type, event.data['id'], event.data['errorCode'] ?? '');
break;
case 'message.received':
console.log('Inbound from', event.data['from'], ':', event.data['body']);
break;
default:
console.log('Ignored', event.type);
}
}
app.use(express.json()); // other routes; the webhook route above keeps the raw body
app.listen(3000, () => console.log('Listening on :3000'));

Register it with webhooks.create and send a test event with webhooks.test. To expose a local server while you develop, use a tunnel with an https URL.

Two functions for a sign-in by phone number: startSignIn sends a code and returns the verification id to keep with the attempt; finishSignIn checks the code the user typed. Refusals turn into messages you can show.

otp-sign-in.ts
import { SMSFabric, SMSFabricError } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY }); // scopes: verify:send, verify:check
export type StartResult = { ok: true; verificationId: string; expiresAt: string } | { ok: false; reason: string; retryAfterSec?: number };
export type FinishResult = { ok: true } | { ok: false; reason: string; attemptsLeft?: number };
export async function startSignIn(phone: string, locale: 'en' | 'ar' = 'en'): Promise<StartResult> {
try {
const v = await sms.verifications.send({ to: phone, locale });
return { ok: true, verificationId: v.id, expiresAt: v.expiresAt };
} catch (err) {
if (!(err instanceof SMSFabricError)) throw err;
switch (err.code) {
case 'validation_failed':
return { ok: false, reason: 'Enter the number with its country code, like +201001234567.' };
case 'verify_resend_limited':
case 'verify_velocity_exceeded':
return { ok: false, reason: 'Too many codes requested. Try again shortly.', retryAfterSec: 600 };
case 'verify_country_not_allowed':
return { ok: false, reason: 'We cannot send codes to this country yet.' };
case 'verify_prefix_blocked':
case 'verify_recipient_blacklisted':
return { ok: false, reason: 'We cannot send a code to this number.' };
default:
throw err;
}
}
}
export async function finishSignIn(verificationId: string, code: string): Promise<FinishResult> {
if (!/^\d{4,10}$/.test(code)) return { ok: false, reason: 'Enter the digits from the SMS.' };
try {
const result = await sms.verifications.check(verificationId, code);
switch (result.status) {
case 'approved':
return { ok: true };
case 'pending':
return { ok: false, reason: 'That code is not right.', attemptsLeft: result.attemptsLeft };
default:
return { ok: false, reason: 'This code can no longer be used. Request a new one.' };
}
} catch (err) {
if (err instanceof SMSFabricError && err.code === 'verification_already_approved') return { ok: true };
throw err;
}
}

Bind the verification id to the user’s session on your server, never to a value the browser sends back alone, and create the session only after finishSignIn returns ok: true. More in Verify.

messages.send takes up to 100 recipients per call. This script splits a list into chunks of 100 and gives each chunk an idempotency key derived from the batch name and the chunk number. If the script crashes and runs again, the chunks that already went out return their stored responses instead of sending again.

bulk-send.ts
import { SMSFabric, SMSFabricError, type Message } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
const CHUNK = 100;
function chunk<T>(items: T[], size: number): T[][] {
const out: T[][] = [];
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
return out;
}
export async function bulkSend(batchId: string, recipients: string[], body: string): Promise<Message[]> {
const unique = [...new Set(recipients)];
const sent: Message[] = [];
for (const [i, to] of chunk(unique, CHUNK).entries()) {
try {
const messages = await sms.messages.send({ to, body, metadata: { batchId } }, { idempotencyKey: `${batchId}:${i}` });
sent.push(...messages);
} catch (err) {
if (err instanceof SMSFabricError) console.error(`Chunk ${i} failed: ${err.status} ${err.code}`, err.requestId);
throw err; // stop, fix, run again: finished chunks are not sent twice
}
}
return sent;
}
const result = await bulkSend('promo-2026-11-21', ['+201001234567', '+201001234568'], 'Our Giza branch opens on Saturday. Reply STOP to opt out.');
const blocked = result.filter((m) => m.status === 'blocked').length;
console.log(`${result.length} accepted, ${blocked} blocked by the blacklist`);

Keep the recipient list and the chunk size fixed between runs: the same key with a different body returns 422 idempotency_key_reused. Idempotency keys are kept for 24 hours.

Webhooks are the right way to learn about delivery in production. For a script, a test or a one-off check, poll messages.get until the message reaches a final status:

send-and-wait.ts
import { setTimeout as sleep } from 'node:timers/promises';
import { SMSFabric, type MessageStatus, type MessageWithEvents } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
const FINAL: ReadonlySet<MessageStatus> = new Set<MessageStatus>(['delivered', 'failed', 'blocked']);
export async function waitForDelivery(id: string, timeoutMs = 120_000): Promise<MessageWithEvents> {
const deadline = Date.now() + timeoutMs;
let delay = 1_000;
for (;;) {
const message = await sms.messages.get(id);
if (FINAL.has(message.status)) return message;
if (Date.now() + delay > deadline) throw new Error(`Message ${id} is still ${message.status} after ${timeoutMs} ms`);
await sleep(delay);
delay = Math.min(delay * 2, 10_000);
}
}
const [message] = await sms.messages.send({ to: '+201001234567', body: 'Delivery check' });
if (message) {
const final = await waitForDelivery(message.id);
console.log(final.status, final.errorCode ?? '', final.events.map((e) => e.type).join(' → '));
}

sent means the carrier accepted the message; delivered needs a delivery report from the handset, which some carriers never send. Treat a message that stays sent as sent, not as failed.