Agents
Follow this file when adding sms-bridge to an application. The pages linked at the end are the reference. When this file and an assumption disagree, follow this file.
Choose the integration
| The application process is | Integration |
|---|---|
| Node.js or Bun | Library. Import SMSBridge from sms-bridge and call send(). |
| Any other runtime | Self Host. Run the container and call POST /v1/sms/send. |
Use one integration. The library does not call the HTTP API. A gateway class constructed in the application exists only in that process. The container image constructs BulkSMSBd, GreenWeb, and sandbox.
Library
npm install sms-bridgepnpm, yarn, and bun install the same package.
Node.js 24 and Bun run the package directly. Node.js 22 runs it when the process is started with --experimental-sqlite. The import is sms-bridge on either runtime.
Create one SMSBridge when the process starts. Call await sms.init() once. Call send() on that instance.
providers is required. Each key is a provider id.
Built-in provider
import { SMSBridge } from "sms-bridge";
const sms = new SMSBridge({
providers: {
bulksmsbd: {
apiKey: process.env.BULKSMSBD_API_KEY,
senderIds: ["BRAND"],
},
},
});
await sms.init();
const result = await sms.send({
recipient: "01700000000",
body: "Your code is 123456",
});type defaults to the provider id. Set type when the id and the vendor differ.
type | Credentials |
|---|---|
bulksmsbd | apiKey is required. apiSecret is optional. baseUrl defaults to https://api.bulksmsbd.com/v1. |
greenweb | apiKey is required. baseUrl defaults to https://api.greenweb.com.bd/api.php. |
sandbox | The provider accepts the message locally. apiKey may be any string. |
senderIds contains the sender id passed to the vendor. Include at least one.
Omit database to keep message rows in memory. Use database: { type: "sqlite", path: "./data/sms-bridge.db" } when the rows must survive a restart, and call await sms.migrate() after init().
routing.defaultStrategy is priority_failover, weighted_distribution, health_aware, rule_based, or fixed. The default is priority_failover.
A vendor implemented in the application
The vendor's credential fields and HTTP request belong in a class. Register that class with gateway or with gateways.
import {
SMSBridge,
type GatewaySendContext,
type IProviderGateway,
} from "sms-bridge";
class ExampleGateway implements IProviderGateway {
readonly type = "example";
constructor(private readonly account: { token: string }) {}
async send(ctx: GatewaySendContext) {
// Read this.account, ctx.recipient, ctx.body, ctx.senderId, and ctx.metadata.
return { success: true, messageId: "vendor-id" };
}
async checkBalance() {
return 0;
}
}
const sms = new SMSBridge({
providers: {
example: {
type: "example",
senderIds: ["BRAND"],
gateway: new ExampleGateway({
token: process.env.EXAMPLE_TOKEN ?? "",
}),
},
},
});
await sms.init();apiKey and baseUrl are unused when gateway is set.
Use config when one class serves more than one account. config is passed through unchanged.
const sms = new SMSBridge({
providers: {
example: {
type: "example",
senderIds: ["BRAND"],
config: { token: process.env.EXAMPLE_TOKEN ?? "" },
},
},
gateways: {
example: (entry) =>
new ExampleGateway(entry.config as { token: string }),
},
});entry is { id, type, senderIds, config }. The factory runs once per provider id during init().
During init(), each provider id is resolved in this order:
providers[id].gatewayis used when it is set.gateways[type]is called with that entry.bulksmsbd,greenweb, andsandboxuse the built-in factory.bulksmsbdandgreenwebthrowProvider "<id>" of type "<type>" requires apiKey and baseUrlwhenapiKeyis missing.- Any other type throws
Unknown provider type: <type> (provider "<id>").
A factory whose key is bulksmsbd, greenweb, or sandbox replaces that built-in.
send() on the gateway returns { success: boolean, messageId?: string, error?: string }. Return success: false when the vendor rejects the message. checkBalance() returns a number. The balance job in this repository calls checkBalance() on the built-in gateways only. Call it on the instance the application constructed.
sms.send()
| Field | Required | Meaning |
|---|---|---|
recipient | yes | Destination number. |
body | yes | Message text. |
priority | no | low, normal, high, or critical. Default: normal. |
profileId | no | Default: "default". A profile id with no stored profile uses every enabled provider. |
routingHint | no | Provider id, name, or type to prefer. |
isMasked | no | When true, selection is limited to a masked sender id. Default: false. |
metadata | no | Passed to gateway.send. Copied onto the queue job when delivery is queued. Left out of the message row. |
send() throws SMSBridge is not initialized. Please call await smsBridge.init() first. when init() has not completed.
Direct delivery is the default. Leave redis unset, or leave redis.useQueue unset. The returned object is:
| Field | Meaning |
|---|---|
success | The provider accepted the message. |
messageId | Id of the stored message. |
status | sent or failed. |
providerId | Selected provider id, when a provider ran. |
providerName | Selected provider name, when a provider ran. |
error | Set when success is false. The value No viable providers available means no provider was eligible. |
Queued delivery sets redis to { url: "redis://localhost:6379", useQueue: true }. send() then returns { success: true, messageId, status: "queued" }. success means the job was accepted by the queue.
Call const worker = sms.startWorker() in that same process after init(). The worker delivers with the gateways registered on the instance. startWorker() throws SMSBridge.startWorker() requires redis.url when redis.url is unset. Call worker.close() before the process exits.
Dashboard
createDashboard(sms) returns a Hono application. Mount it and serve it with listen from sms-bridge. Add the dashboard only when the task asks for the management UI.
import { Hono } from "hono";
import { createDashboard, listen, SMSBridge } from "sms-bridge";
const app = new Hono();
app.route("/admin/sms", createDashboard(sms));
await listen({ port: 4000, fetch: app.fetch });Self Host
Run ghcr.io/srejonkhan/sms-bridge:latest from the application's Compose file. Configuration is environment variables. The image listens on port 8080. Set REDIS_URL to redis://redis:6379 on the service network.
BulkSMSBd requires BULKSMSBD_API_KEY and BULKSMSBD_SENDER_IDS. GreenWeb requires GREENWEB_API_KEY and GREENWEB_SENDER_IDS. Read those values from the environment.
The first start prints a profile API key. Send it on every SMS request:
Authorization: Bearer <profile API key>POST /v1/sms/send with Content-Type: application/json:
| Field | Required | Meaning |
|---|---|---|
recipient | yes | String, length 10 to 20. |
body | yes | String, length 1 to 1600. |
priority | no | low, normal, high, or critical. Default: normal. |
routingHint | no | Provider id, name, or type. |
isMasked | no | Boolean. Default: false. |
Status 202 returns { "messageId": string, "status": "queued" }. Status 400 returns { "error": string, "code": "VALIDATION_ERROR" }. Status 401 returns { "error": string, "code": "UNAUTHORIZED" }.
GET /v1/sms/:id/status reads the messageId from that response. Send the same bearer token.
The JSON body has recipient, body, priority, routingHint, and isMasked. The profile is the API key. Per-message vendor fields are a metadata argument to SMSBridge.send() in the library.
A gateway class that exists only in the application is not loaded by the image. Deliver with that gateway by constructing SMSBridge in a Node.js or Bun process.
Better Auth
Better Auth creates the one-time code and checks the code the user submits. sms-bridge sends the SMS.
Implement sendOTP({ phoneNumber, code }) for the phone-number plugin, and otpOptions.sendOTP({ user, otp }) for the two-factor plugin. Throw from sendOTP when success is false or the HTTP response is not ok. Leave verifyOTP unset. Use the library when that process is Node.js or Bun. Use POST /v1/sms/send from any other runtime. When the provider expects a local number, map a leading +880 to 0 before calling send().
For a one-time code, use direct delivery: omit redis.useQueue, and treat result.success as the provider result.
Checklist
- The process runtime selects Library or Self Host from the table at the top.
- The library calls
init()once, thensend()on the same instance. - A vendor other than BulkSMSBd, GreenWeb, and sandbox is registered with
gatewayorgateways. Its credential fields stay in that class or inconfig. senderIdsincludes the sender id the vendor receives.- Queued library delivery calls
startWorker()on that same instance. - An HTTP client posts
recipientandbodywith the profile bearer token and storesmessageIdfrom the202body. metadatais an argument toSMSBridge.send().
Reference
Editing this repository
Code that applications import runs on Node.js and on Bun. Listen with node:http through listen(). Open SQLite through src/infra/db/sqlite.ts.
createContainer() with no library configuration, the container image, and bun run worker load bulksmsbd, greenweb, and sandbox from environment variables. A gateway registered on an SMSBridge instance stays in that process.
POST /v1/sms/send accepts recipient, body, priority, routingHint, and isMasked. The image listens on port 8080. Provider secrets are environment variables.