Frequently Asked Questions
Create a NestJS service that utilizes the Infobip Node.js SDK. This service should handle constructing the SMS message payload, including recipient number, message text, and optional sender ID. Then, use the SDK's 'send' method to dispatch the message through the Infobip API. Ensure your project includes necessary dependencies like '@infobip-api/sdk' and environment variables for your Infobip API key and base URL.
The Infobip SMS API is a cloud-based communication platform service that allows you to send and receive SMS messages programmatically. It provides various features, including sending single and bulk messages, managing contacts, and receiving delivery reports. The API is accessible through different SDKs, including Node.js, making integration into NestJS applications straightforward.
NestJS provides a robust and structured framework for building server-side applications, making it well-suited for integrating with external APIs like Infobip's SMS API. Its modular architecture, dependency injection, and TypeScript support enhance code organization, testability, and maintainability when handling complex messaging logic. This allows for building scalable and reliable SMS services.
Install the Infobip Node.js SDK (`npm install @infobip-api/sdk`), configure the SDK with your API key and base URL from your Infobip account, then create a dedicated NestJS service to encapsulate the Infobip client and sending logic. Ensure to manage your API keys securely in a `.env` file and load them using `@nestjs/config`.
The article recommends PostgreSQL, a robust open-source relational database, for storing SMS message logs. It's used to store details about each message, such as the sender, recipient, message content, and delivery status, ensuring a comprehensive record of communication activities.
Set up a webhook endpoint in your NestJS application that Infobip can call to deliver incoming SMS messages. Configure this webhook URL in your Infobip account. Use a dedicated controller and DTO to parse the incoming webhook data, validate it, and store it in your database.
Prisma is used as an Object-Relational Mapper (ORM) in the article. It simplifies database interactions by providing a type-safe and convenient way to query and manipulate data in the PostgreSQL database, which is where the application's message logs are stored.
Use alphanumeric sender IDs (e.g., 'InfoSMS') for one-way communication, like sending alerts or notifications. These IDs cannot receive replies. For two-way messaging, you'll need a purchased or verified phone number through your Infobip account.
No, you cannot receive replies to messages sent from an alphanumeric sender ID. Alphanumeric sender IDs are for one-way communication only. To receive replies, you must use a dedicated phone number purchased through Infobip.
Create a dedicated controller in your NestJS application with a route that corresponds to the webhook URL you configured in your Infobip account. This controller should parse and validate the incoming webhook payload, which contains information about incoming messages. Store the processed message data in your PostgreSQL database using Prisma.
Docker and Docker Compose are used for containerizing the NestJS application and its PostgreSQL database dependency. This simplifies deployment and ensures a consistent environment across different stages of development and production.
The article suggests saving an initial message record to the database before sending it via Infobip, marked with 'PENDING_SEND' status. After sending, update this record with the Infobip message ID and updated status. Alternatively, save to the database only after a successful send.
Log in to your Infobip account, navigate to the settings for SMS, and locate the webhook configuration section. Add the public URL of your NestJS webhook endpoint, ensuring it's accessible from the internet. This URL is where Infobip will send its POST requests for incoming messages.
The `@nestjs/config` module is used to manage environment variables securely. It allows you to store sensitive information, like API keys and database credentials, in a `.env` file, which should be excluded from version control, and access these variables within your NestJS application.
Implementing Two-Way SMS Messaging with Infobip and NestJS
This guide provides a comprehensive walkthrough for building a production-ready NestJS application capable of both sending outbound SMS messages and receiving inbound SMS messages via Infobip. We will cover project setup, Infobip integration, database interaction using Prisma, webhook handling for incoming messages, error handling, security considerations, and deployment using Docker.
Project Goal: To create a robust NestJS service that:
Technologies Used:
System Architecture:
Prerequisites:
curl
or Postman).1. Setting up the Project
First_ we'll initialize a new NestJS project and install necessary dependencies.
1.1. Initialize NestJS Project:
Open your terminal and run the NestJS CLI command to create a new project:
This command scaffolds a new project with a standard structure.
1.2. Install Dependencies:
We need several packages for configuration_ Infobip integration_ database access_ and validation.
1.3. Initialize Prisma:
Initialize Prisma in your project_ specifying PostgreSQL as the database provider.
This command creates:
prisma
directory.schema.prisma
file for defining your database schema..env
file for environment variables (including the defaultDATABASE_URL
).1.4. Project Structure Overview:
Your initial
src
directory will look something like this:We will add modules_ services_ controllers_ DTOs_ and configuration files as we build the application.
2. Environment Configuration
Securely managing configuration_ especially API keys_ is critical. We'll use NestJS's
ConfigModule
and a.env
file.2.1. Configure
.env
File:Open the
.env
file created by Prisma and add your Infobip credentials and other necessary variables. Remember to add.env
to your.gitignore
file to avoid committing secrets.Create a
.env.example
file mirroring.env
but with placeholder values_ and commit this example file to your repository.2.2. Integrate
ConfigModule
:Import and configure
ConfigModule
in your main application module (src/app.module.ts
) to make environment variables accessible throughout the application.Explanation:
ConfigModule.forRoot()
loads variables from the.env
file.isGlobal: true
makes theConfigService
available application-wide without needing to importConfigModule
into every feature module.3. Creating a Database Schema and Data Layer (Prisma)
We need a database table to log the SMS messages we send and receive.
3.1. Define the Prisma Schema:
Open
prisma/schema.prisma
and define theMessage
model.Explanation:
Message
model stores relevant details about each SMS.externalId
: Stores the uniquemessageId
provided by Infobip. It's optional initially (?
) because we might save the outbound message before getting the ID_ and nullable because inbound messages might not always have one initially in certain error states. Marked@unique
as Infobip IDs should be unique.direction
: Uses anenum
for clarity.rawResponse
: Useful for debugging_ stores the full JSON payload from Infobip.3.2. Run Database Migration:
Apply the schema changes to your database using Prisma Migrate. This command generates SQL and executes it.
Prisma will prompt you to name the migration (e.g._
init-message-model
) and then create the necessary SQL migration file in theprisma/migrations
directory and apply it to the database specified in yourDATABASE_URL
. Ensure your PostgreSQL server is running. If running via Docker Compose (shown later)_ you'll run migrations after the container starts.3.3. Create Prisma Service:
Create a reusable Prisma service following NestJS best practices.
Finally_ import
PrismaModule
intoAppModule
:4. Integrating with Infobip (Sending SMS)
Now_ let's set up the Infobip SDK to send SMS messages.
4.1. Create Infobip Module and Service:
We'll encapsulate Infobip logic within its own module.
4.2. Implement Infobip Service:
This service will initialize the Infobip client and provide a method for sending SMS.
Explanation:
ConfigService
to retrieve API Key and Base URL.Infobip
client inonModuleInit
. Includes basic error handling for configuration issues.sendSms
method constructs the payload and usesinfobipClient.channels.sms.send
.from
address (Sender ID) with strong emphasis that alphanumeric IDs cannot receive replies and a purchased/verified number must be used for two-way communication.4.3. Implement Infobip Module:
4.4. Import Infobip Module:
Add
InfobipModule
to theimports
array insrc/app.module.ts
.5. Implementing Core Functionality (Messaging Service)
Create a central service to orchestrate sending messages and saving records to the database.
5.1. Create Messaging Module and Service:
5.2. Define Data Transfer Objects (DTOs):
5.3. Implement Messaging Service:
Explanation:
PrismaService
andInfobipService
.handleOutgoingSms
:SendSmsDto
.PENDING_SEND
.InfobipService.sendSms
.externalId
(InfobipmessageId
) and status from the response. Includes comment aboutas any
usage.handleIncomingSms
:InfobipIncomingSmsDto
.externalId
(InfobipmessageId
).direction: INBOUND
. Includes comment aboutas any
usage.5.4. Implement Messaging Module:
5.5. Import Messaging Module:
Add
MessagingModule
tosrc/app.module.ts
.6. Building the API Layer (Sending SMS)
Expose an HTTP endpoint to trigger sending SMS messages.
6.1. Create API Controller:
We can modify the default
AppController
or create a new one (e.g.,MessagingController
). Let's modifyAppController
.Explanation:
MessagingService
.POST /api/v1/messaging/sms/send
endpoint.@UsePipes(new ValidationPipe(...))
to automatically validate the incoming request body against theSendSmsDto
.transform: true
attempts to convert plain JS objects to DTO instances.whitelist: true
strips any properties not defined in the DTO.MessagingService.handleOutgoingSms
.HttpStatus.ACCEPTED
(202) because the SMS isn't instantly delivered, just accepted for processing.6.2. Testing the API Endpoint:
Once the application is running, you can test this endpoint using
curl
:Remember: If using an Infobip free trial, you can likely only send SMS to the phone number you registered with.
7. Handling Inbound Messages (Webhook)
Infobip notifies your application about incoming SMS messages by sending an HTTP POST request to a predefined URL (webhook).
7.1. Create Web