A JavaScript/TypeScript library for integrating with bulksmsbd.net SMS API.
import { BulkSmsClient, type BulkSmsError } from 'bulk-sms-bd'; try { const smsClient = new BulkSmsClient({ bulkSmsApiKey: 'YOUR_API_KEY', // API key provided by bulksmsbd.net bulkSmsSenderId: 'YOUR_SENDER_ID' // Your registered Sender ID / Mask }); // Send SMS const res = await smsClient.sendSMS('8801XXXXXXXXX', 'Hello, this is a test message!'); console.log('Success:', res.success_message); // "SMS Submitted Successfully" // Check Balance const balance = await smsClient.checkBalance(); console.log('Balance:', balance); } catch (error) { if (error instanceof BulkSmsError) { console.error(`Error Code ${error.code}: ${error.message}`); } }
Caution
This is an unofficial library for integrating with bulksmsbd.net API. Please use it at your own risk. The maintainer has no affiliation with bulksmsbd.net and does not take any responsibility for any issues or losses caused by bulksmsbd.net.
bulk-sms-bd is a lightweight, clean, and type-safe JavaScript/TypeScript library for integrating with the bulksmsbd.net SMS gateway. It supports sending single, bulk, and personalized SMS messages using a promise-based API with comprehensive error handling and complete TypeScript definitions.
- Zero Dependency: No external dependencies required. Utilizes native
fetchAPI. - Multiple API Channels:
- One-to-One: Send a single SMS to a specific number.
- One-to-Many: Send the same SMS to multiple numbers in a single API call.
- Many-to-Many: Send different custom SMS messages to different numbers simultaneously.
- Check Balance: Check the current balance of the bulk SMS account.
- Robust Error Handling: Distinct
BulkSmsErrorinstances (extendedError) mapping all API error codes (1001-1032) from the bulksmsbd.net gateway. - Flexible Package Formats: Includes ESM and CommonJS formats out-of-the-box.
- Strictly Typed: Full TypeScript support with proper type declarations.
- Type Guards: Type guards for runtime type checking.
npm i bulk-sms-bd
pnpm add bulk-sms-bd
yarn add bulk-sms-bd
bun add bulk-sms-bd
deno add npm:bulk-sms-bd
The library is configured to export multiple paths via package.json. You can import the specific module(s) you need:
| Import Path | Description | Example Import |
|---|---|---|
bulk-sms-bd |
Main entrypoint for Client, Errors and Guards. | import { BulkSmsClient } from 'bulk-sms-bd' |
bulk-sms-bd/constants |
Direct access to SDK API constants and error maps. | import { ERROR_CODES } from 'bulk-sms-bd/constants' |
bulk-sms-bd/types |
TypeScript interfaces and types. | import type { Message } from 'bulk-sms-bd/types' |
import { BulkSmsClient } from 'bulk-sms-bd'; const smsClient = new BulkSmsClient({ bulkSmsApiKey: 'YOUR_API_KEY', // API key provided by bulksmsbd.net bulkSmsSenderId: 'YOUR_SENDER_ID' // Your registered Sender ID / Mask // Optional base url if needed, default to 'https://bulksmsbd.net/api' // bulkSmsBaseApi: 'https://custom.bulksmsbd.net/api' });
Send a single message to a phone number.
try { const res = await smsClient.sendSMS('8801XXXXXXXXX', 'Hello, this is a test message!'); console.log('Success:', res.success_message); // "SMS Submitted Successfully" } catch (error) { if (error instanceof BulkSmsError) { console.error(`Error Code ${error.code}: ${error.message}`); } }
Alternative usage using oneToOne alias:
const res = await smsClient.oneToOne('8801XXXXXXXXX', 'Hello, this is a test message!');
Send the exact same message to multiple phone numbers at once.
try { const recipients = ['8801XXXXXXXXX', '88017XXXXXXXX', '88018XXXXXXXX']; const res = await smsClient.sendSMS(recipients, 'Hello everyone, this is a broadcast message!'); console.log('Success:', res.success_message); } catch (error) { console.error('Failed to send bulk SMS:', error); }
Alternative usage using oneToMany alias:
const res = await smsClient.oneToMany(recipients, 'Hello everyone!');
Send personalized messages to different recipients.
import type { Message } from 'bulk-sms-bd/types'; try { const messages: Message[] = [ { to: '8801XXXXXXXXX', message: 'Hello Alice, your otp is 1234.' }, { to: '88017XXXXXXXX', message: 'Hello Bob, your otp is 5678.' } ]; const res = await smsClient.sendSMS(messages); console.log('Success:', res.success_message); } catch (error) { console.error('Failed to send personalized SMS:', error); }
Alternative usage using manyToMany alias:
const res = await smsClient.manyToMany(messages);
Fetch the current balance of the bulk SMS account.
const res = await smsClient.checkBalance(); console.log('Balance:', res.balance);
The primary class used to interact with the bulksmsbd.net API.
constructor(configs: BulkSmsBdConfig)
Creates a new BulkSmsClient instance.
Parameters:
configs:BulkSmsBdConfig(Required)bulkSmsApiKey:string(Required) - API Key from the bulksmsbd.net dashboard.bulkSmsSenderId:string(Required) - Registered Sender ID / Mask.bulkSmsBaseApi:string(Optional) - Override base API URL. Defaults to'https://bulksmsbd.net/api'.
Throws a BulkSmsError with code 1003 if configs are empty or missing bulkSmsApiKey / bulkSmsSenderId.
Flexible method to dispatch SMS based on arguments provided.
async sendSMS(to: string, message: string): Promise<SuccessResponse>; async sendSMS(to: string[], message: string): Promise<SuccessResponse>; async sendSMS(messages: Message[]): Promise<SuccessResponse>;
Wrapper for sendSMS() for single messages.
async oneToOne(to: string, message: string): Promise<SuccessResponse>
Wrapper for sendSMS() for single messages to multiple recipients.
async oneToMany(to: string[], message: string): Promise<SuccessResponse>
Wrapper for sendSMS() for sending multiple distinct messages.
async manyToMany(messages: Message[]): Promise<SuccessResponse>
Fetch the current balance of the bulk SMS account.
Uses the
getBalanceApiendpoint, which requires only theapi_key.
async checkBalance(): Promise<BalanceResponse>
Extends the native Error class to wrap any failures thrown by the SDK or returned by the gateway.
class BulkSmsError extends Error { code: ErrorCode; constructor(message: string, code: ErrorCode); }
Properties:
message:string- Error message details.code:ErrorCode(number) - Code mapping to the gateway issue (e.g.1001-1032) or SDK errors (e.g.1003- validation,1005- fetch failure).
Type guard helper to validate if a value meets the Message structure.
Rule: The
valuemust be an object containing the keystoandmessage, wheremessagemust be a non-empty string andtomust be a valid phone number string.
function isMessageObject(value: unknown): value is Message
Type guard helper to validate if a value is a valid phone number.
function isPhoneNumber(value: unknown): value is string
Rule: The
valuemust be a string consisting of 4 to 17 digits, optionally prefixed with a single+sign (e.g. with'+':'+8801XXXXXXXXX'or without'+':'8801XXXXXXXXX').
Note: All inputs are validated strictly using type guards.
The configuration object passed to the constructor new BulkSmsClient(configs) is validated strictly to ensure all required API parameters are set:
- It cannot be an empty object (validated using
isEmptyObject). - It must contain the keys
bulkSmsApiKeyandbulkSmsSenderId(validated usingisObjectWithKeys), and both must be non-empty strings (isNonEmptyString). - If the optional
bulkSmsBaseApiproperty is provided, it must also be a non-empty string.
Any failure in configuration validation throws a BulkSmsError with code 1003.
Phone numbers must be passed as valid phone number strings. Non-numeric characters (except an optional leading + sign) and lengths outside 4-17 digits are disallowed to prevent malformed API calls:
- For single or bulk recipients (e.g. in
sendSMS,oneToOne,oneToMany), they are validated using theisPhoneNumberhelper. - It allows 4 to 17 digits (excluding the optional
+sign prefix when present, e.g.'+8801XXXXXXXXX'or'8801XXXXXXXXX').
Any text input—including configuration keys, message text, and endpoints—is strictly validated to ensure it is of type string and is not empty (checked via isNonEmptyString). Null, undefined, empty strings, or non-string values will trigger input validation failures and throw BulkSmsError with code 1003.
Personalized message objects (representing custom targets) must conform to the Message interface:
- Verified using the
isMessageObject(internallyisMessage) guard. - Every message object in the list must be an object containing the keys
toandmessage, wheremessagemust be a non-empty string andtomust be a valid phone number string. - Passing other objects or malformed data to any method will result in a validation error (throws
BulkSmsErrorwith code1003).
- Base API URL:
https://bulksmsbd.net/api - Single / Bulk Endpoint:
/smsapi(uses HTTP POST) - Personalized Endpoint:
/smsapimany(uses HTTP POST) - Balance Check Endpoint:
/getBalanceApi(uses HTTP GET)
| Code | Status/Error Description |
|---|---|
202 |
SMS Submitted Successfully |
1001 |
Invalid Phone Number |
1002 |
Sender ID Not Correct/Sender ID is Disabled |
1003 |
All Fields are Required |
1005 |
Internal Error |
1006 |
Balance Validity Not Available |
1007 |
Balance Insufficient |
1011 |
User ID Not Found |
1012 |
Masking SMS Must be Sent in Bengali |
1013 |
Sender ID Has Not Found Gateway by API Key |
1014 |
Sender Type Name Not Found Using this Sender by API Key |
1015 |
Sender ID Has Not Found Any Valid Gateway by API Key |
1016 |
Active Price Info Not Found by this Sender ID |
1017 |
Price Info Not Found by this Sender ID |
1018 |
The Owner of this Account is Disabled |
1019 |
The Price of this Account is Disabled |
1020 |
The Parent of this Account is Not Found |
1021 |
The Parent Active Price of this Account is Not Found |
1031 |
Your Account Not Verified, Please Contact Administrator |
1032 |
IP Not Whitelisted |
Note
No code is invented, all the codes are taken from the official documentation but the descriptions are slightly modified for better readability.
interface Message { to: string; message: string; } interface BulkSmsBdConfig { bulkSmsBaseApi?: string; bulkSmsApiKey: string; bulkSmsSenderId: string; } interface SuccessResponse { response_code: 202; success_message: string; } interface ErrorResponse { response_code: ErrorCode; error_message: string; } type BulkSmsResponse = SuccessResponse | ErrorResponse; interface BalanceResponse { response_code: SuccessCode; balance: number; } type SuccessCode = 202; type ErrorCode = 1001 | 1002 | ... | 1032;
This package is licensed under the MIT License.
Built with ❤️ by Nazmul Hassan