Developer Quick-Start: Complete guide to building an Infobip SMS integration with Node.js and NestJS. Learn API authentication, phone number validation, error handling, and deployment best practices for production messaging services. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
This comprehensive guide walks you through building a production-ready SMS service using Node.js, the NestJS framework, and the Infobip API. You'll learn how to implement secure API authentication, robust phone number validation using E.164 standards, comprehensive error handling, and deployment strategies for reliable SMS delivery—essential for marketing campaigns, transactional messaging, and two-factor authentication systems.
We'll use the official Infobip Node.js SDK (@infobip-api/sdk) for seamless integration. By the
end, you'll have a fully deployable NestJS module with logging, validation, configuration management, and best
practices for production environments.
Project Overview: Building a Scalable SMS Microservice
This guide provides a complete walkthrough for building a robust service using Node.js and the NestJS framework to send SMS messages via the Infobip API. We'll cover everything from project setup and core implementation to error handling, security, deployment, and monitoring, enabling you to integrate reliable SMS functionality into your applications, often a key component of marketing campaigns.
We'll focus on using the official Infobip Node.js SDK for seamless integration. By the end, you'll have a deployable NestJS module capable of sending SMS messages, complete with logging, validation, and configuration management.
Project Overview and Goals
What We'll Build:
A NestJS microservice or module with a dedicated API endpoint (/infobip/sms/send) that accepts
requests to send SMS messages. This service will securely interact with the Infobip API using their official
Node.js SDK.
Problem Solved:
Provides a centralized, scalable, and maintainable way to handle SMS sending logic within a larger application ecosystem. Decouples SMS functionality from other business logic, making the system easier to manage and test. Enables programmatic sending of SMS for notifications, alerts, 2FA, or as part of marketing campaign execution flows.
Technologies Used:
- Node.js: The underlying JavaScript runtime environment.
- NestJS: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications using TypeScript. Chosen for its modular architecture, dependency injection, and built-in support for best practices.
- TypeScript: Superset of JavaScript adding static types for better code quality and maintainability.
- Infobip API & Node.js SDK (
@infobip-api/sdk): The official library for interacting with Infobip's communication platform APIs. Simplifies authentication and API calls. - Docker (Optional): For containerizing the application for consistent deployment.
System Architecture:
Diagram Placeholder: Client -> NestJS App -> Infobip Service -> Infobip API, with optional logging to a Database
Prerequisites:
- A free or paid Infobip account.
- Node.js (v14 or higher, minimum version required by @infobip-api/sdk as of January 2025).
- npm or yarn package manager.
- NestJS CLI installed globally (npm install -g @nestjs/cli).
- Basic understanding of TypeScript, Node.js, and REST APIs.
- Access to a terminal or command prompt.
- Git (recommended for version control).
- Docker (optional, for containerized deployment).
Expected Outcome:
A functional NestJS application with an endpoint to send SMS messages via Infobip, incorporating best practices for configuration, error handling, validation, and logging.
1. Setting up the Project
Let's initialize our NestJS project and install the necessary dependencies.
- Create NestJS Project: Open your terminal and run the NestJS CLI command:
nest new infobip-sms-service
cd infobip-sms-service
Choose your preferred package manager (npm or yarn) when prompted.
- Install Dependencies: We need the Infobip SDK, a configuration module, and validation libraries.
npm install @infobip-api/sdk @nestjs/config class-validator class-transformer
yarn add @infobip-api/sdk @nestjs/config class-validator class-transformer
- @infobip-api/sdk: The official Infobip SDK.
- @nestjs/config: For managing environment variables securely.
- class-validator & class-transformer: For validating incoming request data (DTOs).
- Configure Environment Variables: NestJS promotes using environment variables for
configuration. Create a
.envfile in the project root:
.env
# .env
# Infobip Credentials
INFOBIP_API_KEY=YOUR_INFOBIP_API_KEY
INFOBIP_BASE_URL=YOUR_INFOBIP_BASE_URL
# Application Port (Optional)
PORT=3000
# Database Credentials (Optional - Add if implementing logging to DB)
# DB_HOST=localhost
# DB_PORT=5432
# DB_USERNAME=user
# DB_PASSWORD=password
# DB_DATABASE=infobip_logs
INFOBIP_API_KEY: Obtain this from your Infobip account dashboard (usually under API Keys).INFOBIP_BASE_URL: Find this on your Infobip account dashboard (it's specific to your account, usually displayed prominently on the main dashboard page after login, e.g., xxxxx.api.infobip.com).- Important: Add .env to your .gitignore file to prevent committing sensitive credentials.
# .gitignore (ensure this line exists or add it)
.env
- Load Environment Variables: Modify
src/app.module.tsto load the.envfile using@nestjs/config.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { InfobipModule } from './infobip/infobip.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
InfobipModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- Create the Infobip Module: Organize Infobip-related logic into its own module.
nest generate module infobip
nest generate service infobip --no-spec
nest generate controller infobip --no-spec
This creates src/infobip/infobip.module.ts, src/infobip/infobip.service.ts, and
src/infobip/infobip.controller.ts. Ensure InfobipModule is imported in
AppModule as shown above.
2. Implementing Core Functionality (Infobip Service)
The InfobipService will encapsulate the logic for interacting with the Infobip SDK.
- Initialize Infobip Client: Inject
ConfigServiceto access environment variables and initialize the Infobip client instance.
import { Injectable, Logger, InternalServerErrorException, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Infobip, AuthType } from '@infobip-api/sdk';
@Injectable()
export class InfobipService {
private readonly logger = new Logger(InfobipService.name);
private infobipClient: Infobip;
constructor(private configService: ConfigService) {
const apiKey = this.configService.get<string>('INFOBIP_API_KEY');
const baseUrl = this.configService.get<string>('INFOBIP_BASE_URL');
if (!apiKey || !baseUrl) {
this.logger.error('Infobip API Key or Base URL not configured in environment variables.');
throw new InternalServerErrorException('Infobip configuration missing.');
}
this.infobipClient = new Infobip({
baseUrl: baseUrl,
apiKey: apiKey,
authType: AuthType.ApiKey,
});
this.logger.log('Infobip client initialized successfully.');
}
}
- Implement SMS Sending Logic: Create a method to handle sending SMS messages. This method takes the destination number, message text, and optionally the sender ID.
export class InfobipService {
async sendSms(to: string, text: string, from?: string) {
this.logger.log(`Attempting to send SMS to: ${to}`);
if (!to || !text) {
throw new BadRequestException('Destination number (to) and text message are required.');
}
if (!/^\d{10,15}$/.test(to.replace(/^\+/, ''))) {
this.logger.warn(`Potentially invalid phone number format detected by basic check for 'to': ${to}. Consider using a validation library.`);
}
const payload = {
messages: [
{
destinations: [{ to }],
text,
...(from && { from }),
},
],
};
try {
const response = await this.infobipClient.channels.sms.send({
type: 'text',
messages: payload.messages,
});
this.logger.log(`Infobip SMS API Response: ${JSON.stringify(response.data)}`);
const messageStatus = response.data?.messages?.[0]?.status;
if (messageStatus?.groupId === 5) {
this.logger.error(`SMS to ${to} rejected by Infobip: ${messageStatus.description}`);
throw new BadRequestException(`SMS rejected: ${messageStatus.description}`);
}
this.logger.log(`Successfully requested SMS send to ${to}. Message ID: ${response.data?.messages?.[0]?.messageId}`);
return response.data;
} catch (error) {
this.logger.error(`Failed to send SMS to ${to}: ${error.message}`, error.stack);
if (error.response?.data?.requestError?.serviceException) {
const infobipError = error.response.data.requestError.serviceException;
this.logger.error(`Infobip API Error: ${infobipError.messageId} - ${infobipError.text}`);
throw new InternalServerErrorException(`Infobip API Error: ${infobipError.text}`);
}
throw new InternalServerErrorException('Failed to send SMS due to an internal error.');
}
}
}
- Error Handling: Includes basic validation, SDK call within try...catch, logging success/errors, and parsing potential Infobip-specific errors from the response.
- Sender ID (
from): This is often subject to regulations and pre-registration depending on the country. If omitted, Infobip might use a shared number or a pre-configured default for your account. - Phone Number Format: Emphasizes the need for international format (e.g., 447123456789). Real-world apps should use a robust library like libphonenumber-js for validation.
3. Building the API Layer
Expose the SMS sending functionality via a REST API endpoint using the InfobipController.
- Create Data Transfer Object (DTO): Define a class to represent the expected request body,
using
class-validatordecorators for validation. Create thedtofolder if it doesn't exist:mkdir src/infobip/dto.
import { IsString, IsNotEmpty, IsOptional, Matches, MaxLength } from 'class-validator';
export class SendSmsDto {
@IsString()
@IsNotEmpty()
@Matches(/^\+?\d{10,15}$/, { message: 'Phone number must be in international format (e.g., +447123456789). Basic validation only.'})
to: string;
@IsString()
@IsNotEmpty()
@MaxLength(1600)
text: string;
@IsString()
@IsOptional()
@MaxLength(11)
from?: string;
}
- Define Controller Endpoint: Create a POST endpoint that accepts the
SendSmsDtoand calls theInfobipService.
import { Controller, Post, Body, UsePipes, ValidationPipe, HttpCode, HttpStatus } from '@nestjs/common';
import { InfobipService } from './infobip.service';
import { SendSmsDto } from './dto/send-sms.dto';
@Controller('infobip')
export class InfobipController {
constructor(private readonly infobipService: InfobipService) {}
@Post('sms/send')
@HttpCode(HttpStatus.ACCEPTED)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
async sendSms(@Body() sendSmsDto: SendSmsDto) {
const { to, text, from } = sendSmsDto;
const result = await this.infobipService.sendSms(to, text, from);
return {
message: 'SMS request accepted successfully.',
details: result,
};
}
}
@UsePipes(new ValidationPipe(...)): Automatically validates the incoming request body against the SendSmsDto.- transform: true: Attempts to transform plain JavaScript object to DTO instance.
- whitelist: true: Strips any properties not defined in the DTO.
@HttpCode(HttpStatus.ACCEPTED): Sets the default success status code to 202, indicating the request was accepted for processing, which is suitable for asynchronous operations like sending SMS.
- Enable Global Validation Pipe (Recommended): Instead of applying
@UsePipesto every controller method, enable it globally insrc/main.ts.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>('PORT', 3000);
const logger = new Logger('Bootstrap');
app.enableCors();
app.useGlobalPipes(new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
}));
await app.listen(port);
logger.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
(Remove the @UsePipes decorator from the controller method if you enable it globally).
- Testing the Endpoint: Run the application:
npm run start:dev
Use curl or a tool like Postman: Curl Example:
curl -X POST http://localhost:3000/infobip/sms/send \
-H "Content-Type: application/json" \
-d '{
"to": "+15551234567",
"text": "Hello from NestJS and Infobip!",
"from": "MyApp"
}'
(Replace +15551234567 with your registered test number if using a trial account. Replace
MyApp with your alphanumeric sender ID if configured and allowed). Example JSON
Request:
{
"to": "+15551234567",
"text": "Test Message via API",
"from": "TestSender"
}
Example JSON Success Response (202 Accepted):
{
"message": "SMS request accepted successfully.",
"details": {
"bulkId": "some-bulk-id-from-infobip",
"messages": [
{
"to": "+15551234567",
"status": {
"groupId": 1,
"groupName": "PENDING",
"id": 7,
"name": "PENDING_ENROUTE",
"description": "Message sent to next instance"
},
"messageId": "some-message-id-from-infobip"
}
]
}
}
Example JSON Validation Error Response (400 Bad Request):
{
"statusCode": 400,
"message": [
"Phone number must be in international format (e.g., +447123456789). Basic validation only.",
"text should not be empty"
],
"error": "Bad Request"
}
4. Integrating with Third-Party Services (Infobip Details)
We've already integrated the SDK, but let's reiterate the crucial configuration steps.
- Obtain Credentials:
- Log in to your Infobip Portal.
- API Key: Navigate to the API Keys section (often accessible from the homepage or account settings). Generate a new API key if you don't have one. Copy the key securely.
- Base URL: Your unique Base URL is typically displayed prominently on the Infobip Portal homepage after logging in (e.g., xxxxx.api.infobip.com). Copy this URL.
- Configure Environment Variables:
- As done in Step 1.3, place INFOBIP\_API\_KEY and INFOBIP\_BASE\_URL in your .env file.
- Purpose:
- INFOBIP\_API\_KEY: Authenticates your application with the Infobip API. Treat it like a password.
- INFOBIP\_BASE\_URL: Tells the SDK which regional Infobip endpoint to communicate with.
- Format: These are typically strings provided directly by Infobip.
- Secure Handling:
- Never commit API keys or sensitive credentials directly into your code or version control (Git).
- Use the .env file and ensure it's listed in .gitignore.
- In production environments, manage secrets using secure methods provided by your cloud provider (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) or environment variable injection in your deployment platform.
- Fallback Mechanisms (Conceptual): While full implementation is complex, consider these for production:
- Retries: Implement retries with exponential backoff (covered briefly in the next section) for transient network errors or temporary Infobip API unavailability (e.g., 5xx errors).
- Queuing: For high-volume sending or increased resilience, place SMS requests into a message queue (like RabbitMQ or AWS SQS). A separate worker process can then consume from the queue and attempt to send via Infobip, handling retries independently.
- Monitoring: Monitor Infobip's status page and your application's error rates to detect outages quickly.
5. Error Handling, Logging, and Retry Mechanisms
Robust error handling and logging are essential for production.
- Consistent Error Strategy:
- We've used NestJS's built-in HttpException and its derivatives (InternalServerErrorException, BadRequestException). This provides standardized HTTP error responses.
- The ValidationPipe handles input validation errors automatically, returning 400 Bad Request.
- The InfobipService catches errors during SDK interaction, logs details, and throws appropriate HttpExceptions.
- Logging:
- NestJS's built-in Logger is used.
- Levels: Use appropriate levels (log for general info, warn for potential issues, error for failures).
- Format: The default logger provides timestamps, context (class name), and messages. For production, consider structured logging libraries (like pino with nestjs-pino) to output JSON logs, which are easier for log aggregation tools (Datadog, Splunk, ELK stack) to parse.
- What to Log: Log key events (incoming requests, SMS send attempts), errors (including stack traces and Infobip API error details), and successful outcomes (like the returned messageId).
- Retry Strategy (Conceptual):
- When to Retry: Network issues, rate limiting errors (e.g., HTTP 429), transient server errors from Infobip (HTTP 5xx).
- When NOT to Retry: Validation errors (400), authentication errors (401), permanent rejections (like invalid number formats if Infobip returns a specific error code), configuration errors.
- Implementation: Use a library like async-retry or p-retry.
- Example Idea (using
async-retry- requiresnpm i async-retry):
import * as retry from 'async-retry';
async sendSmsWithRetry(to: string, text: string, from?: string) {
return retry(async (bail, attempt) => {
this.logger.log(`Attempt ${attempt} to send SMS to ${to}`);
try {
const response = await this.infobipClient.channels.sms.send({
type: 'text',
messages: [{ destinations: [{ to }], text, ...(from && { from }) }]
});
const messageStatus = response.data?.messages?.[0]?.status;
if (messageStatus?.groupId === 5) {
this.logger.error(`SMS rejected permanently, not retrying: ${messageStatus.description}`);
bail(new Error(`SMS Rejected: ${messageStatus.description}`));
return;
}
return response.data;
} catch (error) {
this.logger.warn(`Attempt ${attempt} failed: ${error.message}`);
if (error.response?.status >= 400 && error.response?.status !== 429 && error.response?.status < 500) {
this.logger.error(`Non-retryable client error (${error.response.status}), stopping retries.`);
bail(error);
return;
}
throw error;
}
}, {
retries: 3,
factor: 2,
minTimeout: 1000,
onRetry: (error, attempt) => {
this.logger.warn(`Retrying SMS send (attempt ${attempt}) due to error: ${error.message}`);
}
});
}
- Testing Error Scenarios:
- Send requests with invalid data (missing fields, bad phone format) to test ValidationPipe.
- Temporarily modify the API key/Base URL in .env to test authentication/configuration errors.
- Mock the infobipClient.channels.sms.send method in unit tests (using Jest mocks) to throw specific errors and verify your service handles them correctly.
6. Creating a Database Schema and Data Layer (Optional Logging)
Storing logs of sent messages can be useful for tracking and auditing. We'll use TypeORM and PostgreSQL as an example.
- Install Dependencies:
npm install @nestjs/typeorm typeorm pg
yarn add @nestjs/typeorm typeorm pg
- @nestjs/typeorm: NestJS integration for TypeORM.
- typeorm: The ORM itself.
- pg: PostgreSQL driver.
- Configure Database Connection: Add DB credentials to your
.envfile (as shown in Step 1.3). Then, configureTypeOrmModuleinsrc/app.module.ts.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { InfobipModule } from './infobip/infobip.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { SmsLog } from './infobip/entities/sms-log.entity';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get<string>('DB_HOST', 'localhost'),
port: configService.get<number>('DB_PORT', 5432),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_DATABASE'),
entities: [SmsLog],
synchronize: configService.get<string>('NODE_ENV') !== 'production',
}),
}),
InfobipModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
synchronize: true(DEV ONLY): Automatically creates/updates database tables based on entities. Never use this in production. Use migrations instead.
- Create Entity: Define the structure of the log table. Create the
entitiesfolder:mkdir src/infobip/entities.
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index } from 'typeorm';
@Entity('sms_logs')
export class SmsLog {
@PrimaryGeneratedColumn('uuid')
id: string;
@Index()
@Column({ nullable: true })
messageId?: string;
@Column({ nullable: true })
bulkId?: string;
@Column()
recipient: string;
@Column({ nullable: true })
sender?: string;
@Column({ type: 'text' })
messageText: string;
@Index()
@Column()
statusName: string;
@Column({ nullable: true })
statusDescription?: string;
@Column({ nullable: true })
statusGroupId?: number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
- Register Entity and Inject Repository: Make the
SmsLogentity available within theInfobipModuleand inject its repository into theInfobipService.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { InfobipService } from './infobip.service';
import { InfobipController } from './infobip.controller';
import { SmsLog } from './entities/sms-log.entity';
@Module({
imports: [
TypeOrmModule.forFeature([SmsLog]),
],
controllers: [InfobipController],
providers: [InfobipService],
})
export class InfobipModule {}
import { Injectable, Logger, InternalServerErrorException, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Infobip, AuthType } from '@infobip-api/sdk';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SmsLog } from './entities/sms-log.entity';
@Injectable()
export class InfobipService {
private readonly logger = new Logger(InfobipService.name);
private infobipClient: Infobip;
constructor(
private configService: ConfigService,
@InjectRepository(SmsLog)
private smsLogRepository: Repository<SmsLog>,
) {
const apiKey = this.configService.get<string>('INFOBIP_API_KEY');
const baseUrl = this.configService.get<string>('INFOBIP_BASE_URL');
if (!apiKey || !baseUrl) {
this.logger.error('Infobip API Key or Base URL not configured in environment variables.');
throw new InternalServerErrorException('Infobip configuration missing.');
}
this.infobipClient = new Infobip({
baseUrl: baseUrl,
apiKey: apiKey,
authType: AuthType.ApiKey,
});
this.logger.log('Infobip client initialized successfully.');
}
async sendSms(to: string, text: string, from?: string) {
this.logger.log(`Attempting to send SMS to: ${to}`);
if (!to || !text) {
throw new BadRequestException('Destination number (to) and text message are required.');
}
if (!/^\d{10,15}$/.test(to.replace(/^\+/, ''))) {
this.logger.warn(`Potentially invalid phone number format detected by basic check for 'to': ${to}. Consider using a validation library.`);
}
const payload = {
messages: [{ destinations: [{ to }], text, ...(from && { from }) }],
};
let infobipResponseData;
let errorOccurred = false;
let errorMessage: string | null = null;
try {
const response = await this.infobipClient.channels.sms.send({
type: 'text',
messages: payload.messages,
});
infobipResponseData = response.data;
this.logger.log(`Infobip SMS API Response: ${JSON.stringify(infobipResponseData)}`);
const messageStatus = infobipResponseData?.messages?.[0]?.status;
if (messageStatus?.groupId === 5) {
this.logger.error(`SMS to ${to} rejected by Infobip: ${messageStatus.description}`);
errorOccurred = true;
errorMessage = `SMS rejected: ${messageStatus.description}`;
throw new BadRequestException(errorMessage);
}
this.logger.log(`Successfully requested SMS send to ${to}.`);
} catch (error) {
errorOccurred = true;
errorMessage = errorMessage || error.message;
this.logger.error(`Failed to send SMS to ${to}: ${errorMessage}`, error.stack);
if (error instanceof BadRequestException) {
throw error;
} else if (error.response?.data?.requestError?.serviceException) {
const infobipError = error.response.data.requestError.serviceException;
errorMessage = `Infobip API Error: ${infobipError.messageId} - ${infobipError.text}`;
throw new InternalServerErrorException(errorMessage);
}
throw new InternalServerErrorException(errorMessage || 'Failed to send SMS due to an internal error.');
} finally {
try {
const logEntry = this.smsLogRepository.create({
recipient: to,
sender: from,
messageText: text,
bulkId: infobipResponseData?.bulkId,
messageId: infobipResponseData?.messages?.[0]?.messageId,
statusName: errorOccurred ? 'FAILED_TO_SEND' : (infobipResponseData?.messages?.[0]?.status?.name || 'UNKNOWN'),
statusDescription: errorOccurred ? errorMessage : (infobipResponseData?.messages?.[0]?.status?.description),
statusGroupId: errorOccurred ? -1 : (infobipResponseData?.messages?.[0]?.status?.groupId),
});
await this.smsLogRepository.save(logEntry);
this.logger.log(`Logged SMS attempt for ${to} with status ${logEntry.statusName}`);
} catch (logError) {
this.logger.error(`Failed to save SMS log for ${to}: ${logError.message}`, logError.stack);
}
}
if (!errorOccurred) {
return infobipResponseData;
}
}
}
Frequently Asked Questions (FAQ)
What is the Infobip Node.js SDK and why use it?
The @infobip-api/sdk is the official Infobip library for Node.js that simplifies API
authentication and provides type-safe methods for sending SMS, WhatsApp, and email messages. It requires
Node.js v14+ and handles API request formatting, authentication headers, and error responses automatically.
How do I validate phone numbers in E.164 format?
E.164 is the ITU-T international standard for phone numbers, specifying a maximum of 15 digits starting with
a + sign, followed by the country code (1-3 digits) and subscriber number. For production
validation, use the libphonenumber-js library which provides parsePhoneNumber(),
isPossible(), and isValid() methods with comprehensive country-specific rules.
What are SMS character limits for GSM-7 vs Unicode encoding?
According to GSM 03.38 (3GPP 23.038) specification:
- GSM-7 encoding: 160 characters per message segment (standard 7-bit alphabet for English and Western European languages)
- UCS-2/UTF-16 encoding: 70 characters per message segment (for Unicode characters including emoji, Arabic, Chinese, etc.) Messages exceeding these limits are automatically split into concatenated segments with slight overhead.
How do I handle Infobip API errors in production?
Implement comprehensive error handling by:
- Wrapping SDK calls in try-catch blocks
- Parsing Infobip-specific error responses (check error.response.data.requestError.serviceException)
- Checking message status codes (Group ID 5 indicates REJECTED status)
- Implementing retry logic with exponential backoff for transient errors (5xx, 429 rate limits)
- Logging all errors with context for debugging
For production systems, implement:
- Database logging of all SMS attempts with status tracking (use TypeORM with PostgreSQL)
- Store recipient, sender, message text, Infobip message ID, bulk ID, and status codes
- Index frequently queried fields (messageId, recipient, createdAt)
- Monitor delivery rates and error patterns
- Set up alerts for high failure rates or API connectivity issues
Can I use this with other Infobip channels like WhatsApp or Email?
Yes, the Infobip Node.js SDK supports multiple channels through infobip.channels.* methods:
- infobip.channels.sms.send() for SMS
- infobip.channels.whatsapp.send() for WhatsApp
- infobip.channels.email.send() for Email The same authentication and error handling patterns apply across all channels.
Summary and Next Steps
You've now built a production-ready Infobip SMS service with Node.js and NestJS featuring:
- ✅ Secure API authentication with environment variable management
- ✅ Type-safe TypeScript implementation with NestJS dependency injection
- ✅ Input validation using DTOs and class-validator
- ✅ E.164 phone number format validation guidelines
- ✅ Comprehensive error handling and retry strategies
- ✅ Optional database logging for SMS tracking
- ✅ Production deployment considerations
Next steps to enhance your SMS service:
- Implement phone number validation: Install and integrate libphonenumber-js for production-grade validation
- Add rate limiting: Protect your API with @nestjs/throttler to prevent abuse
- Set up monitoring: Use tools like Datadog, New Relic, or custom metrics to track delivery rates
- Implement queuing: For high-volume scenarios, add RabbitMQ or AWS SQS for reliable message processing
- Add webhook handling: Create endpoints to receive Infobip delivery reports for status updates
- Expand to other channels: Leverage the same patterns for WhatsApp and Email messaging
For more information, consult the Infobip API documentation and the NestJS documentation.
This guide reflects current best practices as of January 2025. Always refer to official documentation for the latest API changes and recommendations.
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues — grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers →