Official JavaScript/TypeScript SDK for the CastBrick API.
npm install castbrick-js- Node.js 18+ (uses native
fetch) - Any modern browser, Next.js, SvelteKit, or Vite project
import { CastBrick } from "castbrick-js";
const cb = new CastBrick({ apiKey: "your_api_key_here" });
// Send an SMS
await cb.sms.send({
recipients: ["+244923000000"],
content: "Hello from CastBrick!",
});Get your API key from the CastBrick dashboard.
const result = await cb.sms.send({
recipients: ["+244923000000", "+244912000000"],
content: "Your verification code is 1234",
senderId: "MyApp", // optional β your approved Sender ID
scheduledAt: "2026-04-01T10:00:00Z", // optional β schedule for later
fallback: true, // optional β fall back to CastBrick sender if senderId unavailable
});
console.log(result.messageId, result.recipientCount);await cb.sms.send({
recipients: [],
content: "Promo: 50% off this weekend!",
contactListId: "list-uuid-here",
});// Simple
const { items, totalCount } = await cb.sms.list();
// With filters
const { items } = await cb.sms.list({
page: 1,
pageSize: 20,
status: "delivered", // pending | sent | delivered | failed | scheduled
phone: "+244923000000",
from: "2026-01-01T00:00:00Z",
to: "2026-06-01T00:00:00Z",
});await cb.sms.cancelScheduled("message-id");const { items } = await cb.contacts.list(1, 20, "search term");// Comma or newline-separated phone numbers
await cb.contacts.create({
phoneNumbers: "+244923000000\n+244912000000",
});await cb.contacts.delete("contact-id");// List all contact lists
const { items } = await cb.contacts.listLists();
// Create a list β returns the new list ID
const listId = await cb.contacts.createList("VIP Customers");
// Add / remove a contact from a list
await cb.contacts.addToList(listId, "contact-id");
await cb.contacts.removeFromList(listId, "contact-id");const id = await cb.broadcasts.create({
name: "Weekend Promo",
message: "50% off this weekend!",
contactListId: "list-uuid-here", // optional
senderId: "MyApp", // optional
});
await cb.broadcasts.send(id);await cb.broadcasts.update(id, {
name: "Weekend Promo",
message: "50% off this weekend!",
scheduleAt: "2026-04-05T08:00:00Z",
});
await cb.broadcasts.send(id);await cb.broadcasts.cancel(id);
await cb.broadcasts.duplicate(id);
await cb.broadcasts.delete(id);
const { items } = await cb.broadcasts.list();
const broadcast = await cb.broadcasts.get(id);CastBrick Push & Realtime API lets you deliver Web & Mobile push notifications and stream realtime events via SSE channels.
// Issue a short-lived channel token for the client
const { token } = await cb.push.issueToken({
channels: ["orders", "user-42"],
userId: "user-123", // optional
ttlSeconds: 3600, // optional, default 3600
});
// Publish an event to a channel
const result = await cb.push.publish({
channel: "orders",
event: "order.created",
data: { orderId: "abc123", total: 5000 },
});
console.log(result.delivered, result.creditsUsed);import { CastBrickPushClient } from "castbrick-js";
// token comes from your backend (via the issueToken call above)
const push = new CastBrickPushClient(token, {
onConnected: (channels) => console.log("connected to", channels),
onStatusChange: (status) => console.log("status:", status),
});
// Listen to events on a specific channel
const unsubscribe = push.on("orders", (event) => {
console.log(event.event, event.data); // "order.created" { orderId: "abc123" }
});
// Later
unsubscribe(); // stop receiving events on this channel
push.disconnect(); // close the SSE connectionBetter than OneSignal: unlimited free subscribers, 5,000 free pushes every month, with zero manual Service Worker configuration.
One line handles browser permission, service worker registration, and device subscription:
import { CastBrickWebPush } from "castbrick-js";
const result = await CastBrickWebPush.subscribe({
appId: "app_7a8b9c",
externalUserId: "user_42", // optional
tags: { plan: "pro", lang: "pt" } // optional
});
if (result.success) {
console.log("Subscribed device ID:", result.subscriptionId);
}const response = await cb.push.send({
appId: "app_7a8b9c",
title: "Flash Sale π",
body: "Get 30% off today only!",
iconUrl: "https://yourapp.com/icon.png",
actionUrl: "https://yourapp.com/sale",
target: {
all: true, // or subscriptionIds: ["sub_..."], or externalUserIds: ["user_42"]
}
});
console.log(`Delivered: ${response.deliveredCount}, Remaining Free: ${response.freePushesRemaining}`);// Get current credit balance
const balance = await cb.billing.getBalance();
// List available credit packages
const packages = await cb.billing.listPackages();
// List credit consumption/transaction history
const { items } = await cb.billing.listTransactions();The SDK also provides native access to cb.segments, cb.templates, and cb.webhooks.
// Example: Create a Webhook
await cb.webhooks.create({
endpoint: "https://yourapp.com/webhooks/castbrick",
eventType: "sms.delivered"
});import { CastBrick, CastBrickApiError } from "castbrick-js";
try {
await cb.sms.send({ recipients: ["+244923000000"], content: "Hello!" });
} catch (err) {
if (err instanceof CastBrickApiError) {
console.error(`API error ${err.status}:`, err.message);
// 401 β invalid or revoked API key
// 402 β insufficient credits
// 422 β validation error
}
}The SDK is written in TypeScript and exports all types:
import type {
SendSmsRequest,
SmsListParams,
SmsMessage,
Broadcast,
Contact,
ContactList,
PagedResult,
IssuePushTokenRequest,
IssuePushTokenResponse,
PublishEventRequest,
PublishEventResponse,
PushEvent,
PushClientStatus,
} from "castbrick-js";Releases are published by GitHub Actions when a v* tag is pushed.
The workflow uses npm Trusted Publishing through OIDC, so no NPM_TOKEN secret is required.
In npmjs.com package settings for castbrick-js, add a trusted publisher with:
- Publisher: GitHub Actions
- Owner:
IldySilva - Repository:
castbrick-js - Workflow:
.github/workflows/publish.yml
MIT