Configuration
Create one client per process and reuse it. The client keeps no connection state, so sharing it between requests is safe.
import { SMSFabric } from '@smsfabric/sdk';
export const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY, baseUrl: 'https://api.smsfabric.com', maxRetries: 2, timeoutMs: 30_000,});Options
Section titled “Options”| Option | Type | Default | What it does |
|---|---|---|---|
apiKey |
string |
SMSFABRIC_API_KEY, only when accessToken isn’t passed either |
An API key, sf_live_… or sf_test_…. Sent as X-Api-Key. |
accessToken |
string |
none | A signed-in user’s access token instead of an API key. Sent as Authorization: Bearer …. When you pass it, SMSFABRIC_API_KEY is not read. |
baseUrl |
string |
SMSFABRIC_BASE_URL, then https://api.smsfabric.com |
The API origin. Trailing slashes are removed. |
maxRetries |
number |
2 |
Extra attempts after the first one, for the failures listed under Retries. 0 turns retries off. |
timeoutMs |
number |
30000 |
Timeout for each attempt, in milliseconds. A timed-out attempt counts as a network error. |
fetch |
(input: string, init: RequestInit) => Promise<Response> |
the global fetch |
A custom fetch, for tests, a proxy or instrumentation. |
The constructor throws Error('SMSFabric: pass apiKey (or set SMSFABRIC_API_KEY) or accessToken') when it finds neither credential.
API key or access token
Section titled “API key or access token”Use an API key for servers, jobs and scripts. Its scopes decide what the client can do; see Authentication.
Use an access token only for the few endpoints that refuse API keys, so that a leaked key cannot widen its own access:
- API keys:
apiKeys.* - Team management:
org.members.*,org.invitations.* - Renaming the organization:
org.update - Saving Verify settings:
verifications.settings.update
An access token is the short-lived (15 minutes) token the portal gets when a user signs in. See User tokens.
Environment variables
Section titled “Environment variables”| Variable | Used for |
|---|---|
SMSFABRIC_API_KEY |
apiKey when you don’t pass one. |
SMSFABRIC_BASE_URL |
baseUrl when you don’t pass one. Set it to http://localhost:3000 against a local API. |
An empty value (SMSFABRIC_BASE_URL=) counts as not set, and so does an empty apiKey, accessToken or baseUrl option.
Keep keys out of code and out of version control. Load them from your secret manager or the environment.
Retries and backoff
Section titled “Retries and backoff”The client retries a request when it is safe to repeat:
GET,PUTandDELETErequests, andPOSTrequests that carry anIdempotency-Key(every create method sends one).
It retries them on a network error or timeout, on the statuses 408, 425, 429, 500, 502, 503 and 504, and on 409 only when the code is idempotency_in_progress (a request with the same key is still running). Other 4xx responses, including conflicts such as 409 contact_exists, are thrown at once.
A retried DELETE resolves when it gets 404 after an earlier attempt failed on the network, timed out or got a 5xx: that earlier attempt already deleted the object. A 404 on the first attempt is still thrown.
The delay before each retry is:
- The
Retry-Afterheader (orRateLimit-Reset) in seconds when the response has one, capped at 32 seconds. - Otherwise exponential backoff with jitter: about 250 ms, then 500 ms, then 1 s, doubling up to 8 s, each picked at random between half and the full value.
These requests are never retried, because repeating them could change the outcome:
| Method | Why |
|---|---|
verifications.check |
Every check uses one of the 5 attempts. |
verifications.send on 429 |
Its 429s are per-number and per-country limits measured in minutes. Network errors and 5xx are still retried. |
campaigns.start, pause, resume, cancel, estimate |
State changes without an idempotency key. |
apiKeys.rotate |
A second rotation would replace the new secret. |
webhooks.replay, webhooks.test |
Each call queues another delivery. |
Every update (PATCH) |
Sent once. |
When a retry runs out, the last error is thrown as an SMSFabricError.
Idempotency
Section titled “Idempotency”Every create method takes an optional second argument, { idempotencyKey }. When you leave it out, the client generates a UUID for that call and reuses it for each automatic retry, so a timeout never creates twice.
Pass your own key when your code may repeat the call, for example a job that can run again after a crash. Derive it from your data:
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });const orderId = '1042';
// Running this twice sends one SMS: the second call gets the stored response back.await sms.messages.send( { to: '+201001234567', body: `Order ${orderId} has shipped.` }, { idempotencyKey: `order-${orderId}-shipped` },);Keys are 1 to 255 characters from A–Z a–z 0–9 _ - : . and are kept for 24 hours per organization. The same key with a different body returns 422 idempotency_key_reused. More in Idempotency.
Timeouts
Section titled “Timeouts”timeoutMs applies to each attempt, so the worst case for one call is about (maxRetries + 1) × timeoutMs plus the backoff delays. For a request handler that must answer quickly, lower both:
import { SMSFabric } from '@smsfabric/sdk';
// At most 2 attempts of 5 seconds each.export const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY, timeoutMs: 5_000, maxRetries: 1 });Custom fetch
Section titled “Custom fetch”Pass fetch to log requests, add tracing headers or route through a proxy. It receives the full URL and the RequestInit the client built.
import { SMSFabric, type FetchLike } from '@smsfabric/sdk';
const loggingFetch: FetchLike = async (input, init) => { const started = Date.now(); const res = await fetch(input, init); console.log(init.method, new URL(input).pathname, res.status, `${Date.now() - started}ms`); return res;};
export const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY, fetch: loggingFetch });Log the method, path and status only. Request bodies hold phone numbers and message text, and the headers hold your key.
Low-level requests
Section titled “Low-level requests”sms.http.request calls any endpoint with the client’s credentials, retries and error handling. Use it for an endpoint the SDK has no helper for yet.
import { SMSFabric } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
const tags = await sms.http.request<{ data: Array<{ tag: string; contacts: number }> }>({ method: 'GET', path: '/v1/contacts/tags', query: { q: 'vip' },});console.log(tags.data);request takes method, path, query, body (sent as JSON), idempotencyKey and responseText (return the body as text instead of parsing JSON).
ESM and CommonJS
Section titled “ESM and CommonJS”The package ships both builds. Use whichever your project uses:
import { SMSFabric, SMSFabricError } from '@smsfabric/sdk';const { SMSFabric, SMSFabricError } = require('@smsfabric/sdk');TypeScript
Section titled “TypeScript”Types ship with the package; you don’t need a separate @types package. Every response shape and parameter object is exported, so you can annotate your own functions:
import { SMSFabric, type Message, type SendMessageParams } from '@smsfabric/sdk';
const sms = new SMSFabric({ apiKey: process.env.SMSFABRIC_API_KEY });
export async function notify(params: SendMessageParams): Promise<Message[]> { return sms.messages.send(params);}The resource classes (Messages, Verifications, Devices and so on) are exported too, for typing a dependency that receives one resource. The package version is exported as VERSION and sent in the User-Agent header as smsfabric-node/<version>.