Developer Quick-Start: A guide on setting up a NestJS application to send SMS via AWS SNS and receive real-time delivery status callbacks using an SNS topic and HTTPS endpoint. 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.
Tracking the delivery status of SMS messages is crucial for applications relying on timely communication. Simply sending a message isn't enough; knowing whether it reached the recipient's handset successfully, failed, or encountered an issue is vital for reliable workflows, user experience, and troubleshooting.
This guide provides a complete walkthrough for building a production-ready system within a Node.js NestJS application to send SMS messages via AWS Simple Notification Service (SNS) and receive real-time delivery status callbacks directly from SNS. We will configure AWS SNS to push status updates to a dedicated SNS topic, which will then notify a secure HTTPS endpoint in our NestJS application.
Project Goals:
- Send SMS: Implement a service in NestJS to send SMS messages using the AWS SDK v3 for SNS.
- Configure SNS for Callbacks: Set up AWS SNS SMS preferences to publish delivery status notifications (successes and failures) to a designated SNS topic.
- Receive Callbacks: Create a secure NestJS controller endpoint (the ""callback endpoint"") to receive HTTPS notifications from the SNS topic.
- Process Status Updates: Validate incoming SNS messages, parse the delivery status, and update the application's state (e.g., log the status or update a database).
- Production Readiness: Incorporate essential practices like configuration management, error handling, security (signature verification), logging, and deployment considerations.
Technologies Used:
- Node.js: JavaScript runtime environment.
- NestJS: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications.
- TypeScript: Superset of JavaScript adding static types.
- AWS SNS: Managed messaging service for sending SMS and managing notifications.
- AWS SDK for JavaScript v3: To interact with AWS services.
- AWS IAM: For managing permissions required by SNS.
- (Optional) Database: Such as PostgreSQL or MongoDB via TypeORM/Prisma to persist message status.
- (Optional) Docker: For containerization and deployment consistency.
System Architecture:
sequenceDiagram
participant Client
participant NestJS API
participant AWS SNS
participant SMS Recipient
participant Status SNS Topic
participant (Optional) Database
Client->>+NestJS API: POST /sms/send (phone, message)
NestJS API->>+AWS SNS: PublishCommand(PhoneNumber, Message)
AWS SNS-->>-NestJS API: { MessageId: '...' }
NestJS API-->>Client: { success: true, messageId: '...' }
Note over NestJS API, (Optional) Database: Record message details (messageId, status='SUBMITTED')
AWS SNS->>+SMS Recipient: Deliver SMS
SMS Recipient-->>-AWS SNS: Delivery Acknowledgment/Failure
AWS SNS->>+Status SNS Topic: Publish Delivery Status Notification
Status SNS Topic->>+NestJS API: POST /sms/status/callback (SNS Notification)
NestJS API->>NestJS API: Verify SNS Message Signature
NestJS API->>NestJS API: Parse Status (DELIVERED/FAILED)
Note over NestJS API, (Optional) Database: Update message status (messageId, newStatus)
NestJS API-->>-Status SNS Topic: HTTP 200 OK
Note: Ensure the Mermaid diagram renders correctly on your publishing platform. Verification may be required.
Prerequisites:
- An AWS account with IAM user credentials configured locally (via AWS profiles or environment variables) or via instance roles if deploying to EC2/ECS.
- Node.js (LTS version recommended) and npm/yarn installed.
- NestJS CLI installed (npm install -g @nestjs/cli).
- Basic familiarity with NestJS concepts (modules, controllers, services).
- Access to the AWS Management Console or AWS CLI for setup.
- A publicly accessible HTTPS endpoint for the callback receiver. Why? AWS SNS requires a public HTTPS URL to send notifications (callbacks) to. During development, Ngrok is a useful tool to create a secure tunnel from a public URL to your local machine. Important: Ngrok's free tier provides temporary URLs and has limitations; it is suitable only for development and testing, not for production environments. For production, you'll need a deployed application with a stable public HTTPS domain.
By the end of this guide, you'll have a robust NestJS application capable of sending SMS messages and reliably tracking their delivery status through direct callbacks from AWS SNS.
1. Setting up the NestJS Project
Let's initialize a new NestJS project and install the necessary dependencies.
1. Create NestJS Project:
Open your terminal and run:
nest new nestjs-sns-callbacks
cd nestjs-sns-callbacks
Choose your preferred package manager (npm or yarn) when prompted.
2. Install Dependencies:
We need the AWS SDK v3 for SNS, configuration management, validation, and the SNS message validator.
npm install @aws-sdk/client-sns @nestjs/config class-validator class-transformer sns-validator
npm install --save-dev @types/sns-validator
yarn add @aws-sdk/client-sns @nestjs/config class-validator class-transformer sns-validator
yarn add --dev @types/sns-validator
- @aws-sdk/client-sns: AWS SDK v3 client for SNS.
- @nestjs/config: For managing environment variables.
- class-validator, class-transformer: For request payload validation (DTOs).
- sns-validator: To verify the authenticity of incoming SNS messages (crucial for security).
3. Configure Environment Variables:
Create a .env file in the project root:
ini
AWS_REGION=us-east-1
DELIVERY_STATUS_TOPIC_ARN=arn:aws:sns:us-east-1:123456789012:sms-delivery-status-topic
APP_BASE_URL=https://your-public-domain-or-ngrok-url.com
Security Best Practice - AWS Credentials: While listing AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY directly in .env works for local development, it's
strongly discouraged for security reasons, especially if the file could be accidentally
committed. Never commit files containing credentials to version control. Add
.env to your .gitignore immediately. Preferred Alternatives:
- AWS Profiles: Configure named profiles in ~/.aws/credentials and ~/.aws/config. The SDK can use these automatically (set AWS\_PROFILE environment variable).
- IAM Roles (Recommended for Production): When deployed on AWS services like EC2, ECS, or Lambda, assign an IAM role to the resource. The SDK automatically retrieves temporary credentials from the instance metadata service. This avoids storing long-lived keys entirely.
- Secure Secret Management: Use services like AWS Secrets Manager or HashiCorp Vault, especially in production.
4. Setup Configuration Module:
Modify src/app.module.ts to load the environment variables using @nestjs/config.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { SmsModule } from './sms/sms.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
SmsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
5. Project Structure:
We'll organize our SMS-related logic into a dedicated sms module.
src/
βββ app.controller.ts
βββ app.module.ts
βββ app.service.ts
βββ main.ts
βββ sms/
β βββ dto/
β β βββ send-sms.dto.ts # DTO for sending SMS requests
β βββ entities/ # (Optional) For database entities
β β βββ sms-message.entity.ts
β βββ interfaces/
β β βββ sns-notification.interface.ts # Type definition for SNS notifications
β βββ sms.controller.ts # Handles incoming API requests (send & callback)
β βββ sms.module.ts # SMS module definition
β βββ sms.service.ts # Contains business logic (sending SMS, processing callbacks)
βββ config/ # (Optional) Configuration setup if needed beyond basic .env
Create the sms directory and its subdirectories. We will populate the files in the following
steps.
2. Implementing Core Functionality: Sending SMS
Let's create the service responsible for interacting with AWS SNS to send messages.
1. Create AWS SNS Client Provider (Optional but Recommended):
For better organization and testability, we can create a provider for the SNS client.
import { Module, Provider } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { SNSClient } from '@aws-sdk/client-sns';
import { SmsController } from './sms.controller';
import { SmsService } from './sms.service';
export const AWS_SNS_CLIENT = Symbol('AWS_SNS_CLIENT');
const snsClientProvider: Provider = {
provide: AWS_SNS_CLIENT,
useFactory: (configService: ConfigService): SNSClient => {
const region = configService.get<string>('AWS_REGION');
return new SNSClient({ region });
},
inject: [ConfigService],
};
@Module({
imports: [ConfigModule],
controllers: [SmsController],
providers: [snsClientProvider, SmsService],
exports: [SmsService],
})
export class SmsModule {}
2. Create SmsService:
This service will encapsulate the logic for sending SMS messages and processing status updates.
import { Injectable, Inject, Logger, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
SNSClient,
PublishCommand,
PublishCommandInput,
PublishCommandOutput,
SetSMSAttributesCommand,
SetSMSAttributesCommandInput,
} from '@aws-sdk/client-sns';
import { AWS_SNS_CLIENT } from './sms.module';
@Injectable()
export class SmsService {
private readonly logger = new Logger(SmsService.name);
constructor(
@Inject(AWS_SNS_CLIENT) private readonly snsClient: SNSClient,
private readonly configService: ConfigService,
) {}
async sendSms(phoneNumber: string, message: string): Promise<string> {
if (!phoneNumber || !message) {
throw new BadRequestException('Phone number and message are required.');
}
if (!/^\+[1-9]\d{1,14}$/.test(phoneNumber)) {
throw new BadRequestException(`Invalid phone number format: ${phoneNumber}. Must use E.164 format (e.g., +12223334444).`);
}
const params: PublishCommandInput = {
PhoneNumber: phoneNumber,
Message: message,
};
try {
this.logger.log(`Attempting to send SMS to ${phoneNumber}`);
const command = new PublishCommand(params);
const result: PublishCommandOutput = await this.snsClient.send(command);
if (!result.MessageId) {
throw new Error('SNS did not return a MessageId.');
}
this.logger.log(`SMS initiated successfully to ${phoneNumber}. MessageId: ${result.MessageId}`);
return result.MessageId;
} catch (error) {
this.logger.error(`Failed to send SMS to ${phoneNumber}: ${error.message}`, error.stack);
if (error instanceof BadRequestException) throw error;
throw new Error(`Failed to send SMS via SNS: ${error.message}`);
}
}
async processDeliveryStatus(payload: any): Promise<void> {
this.logger.log(`Received raw delivery status payload: ${JSON.stringify(payload)}`);
}
async configureSmsDeliveryStatusAttributes(): Promise<void> {
const deliveryStatusTopicArn = this.configService.get<string>('DELIVERY_STATUS_TOPIC_ARN');
if (!deliveryStatusTopicArn) {
this.logger.error('DELIVERY_STATUS_TOPIC_ARN is not configured in .env. Cannot set SMS attributes.');
return;
}
const params: SetSMSAttributesCommandInput = {
attributes: {
'DeliveryStatusSuccessSamplingRate': '100',
'SuccessfulFeedbackRoleArn': deliveryStatusTopicArn,
'FailureFeedbackRoleArn': deliveryStatusTopicArn,
'DefaultSMSType': 'Transactional',
},
};
try {
this.logger.log(`Attempting to set SMS delivery status attributes to publish to Topic: ${deliveryStatusTopicArn}`);
const command = new SetSMSAttributesCommand(params);
await this.snsClient.send(command);
this.logger.log(`Successfully set SMS delivery status attributes.`);
} catch (error) {
this.logger.error(`Failed to set SMS attributes: ${error.message}`, error.stack);
throw new Error(`Failed to configure SNS SMS attributes: ${error.message}`);
}
}
}
Explanation:
- Injection: Injects SNSClient and ConfigService.
sendSmsMethod:
- Takes phoneNumber and message.
- Validates E.164 format strictly using regex and throws BadRequestException if invalid.
- Creates PublishCommandInput.
- Calls this.snsClient.send().
- Logs success/error. Returns MessageId. Includes placeholder for DB persistence.
processDeliveryStatusMethod: A preliminary placeholder. It currently just logs the raw payload received. This method will be significantly updated in Section 6 (Database Integration) to parse the specific fields (messageId, status, etc.) and interact with the database repository.configureSmsDeliveryStatusAttributesMethod: Utility to set SNS attributes for delivery status. Requires DELIVERY\_STATUS\_TOPIC\_ARN from .env. Sets sampling rate and specifies the target Topic ARN for success/failure notifications using the SuccessfulFeedbackRoleArn and FailureFeedbackRoleArn parameters (despite their confusing names). Requires sns:SetSMSAttributes permission.
3. Building the API Layer (Sending SMS & Receiving Callbacks)
Now, let's create the controller to expose an endpoint for sending SMS and another for receiving the status callbacks from SNS.
1. Create SendSmsDto:
Define a Data Transfer Object (DTO) for validating the incoming request payload when sending an SMS.
import { IsNotEmpty, IsString, IsPhoneNumber, MaxLength } from 'class-validator';
export class SendSmsDto {
@IsNotEmpty()
@IsPhoneNumber(null, { message: 'Phone number must be a valid E.164 format phone number (e.g., +12223334444).' })
phoneNumber: string;
@IsNotEmpty()
@IsString()
@MaxLength(1600)
message: string;
}
2. Define SNS Notification Interface:
Create an interface for better type safety when handling incoming SNS notifications. The structure can be
complex; this covers the key parts. Refer to AWS SNS documentation for the definitive structure. Note the
ambiguity in messageId location within the Message field, which the code needs to
handle.
export interface SnsNotificationRequest {
Type: 'SubscriptionConfirmation' | 'Notification' | 'UnsubscribeConfirmation';
MessageId: string;
Token?: string;
TopicArn: string;
Subject?: string;
Message: string;
Timestamp: string;
SignatureVersion: string;
Signature: string;
SigningCertURL: string;
SubscribeURL?: string;
UnsubscribeURL?: string;
}
export interface SnsDeliveryStatusMessage {
notification?: {
messageId: string;
timestamp: string;
};
delivery: {
phoneCarrier: string;
mnc: number;
destination: string;
priceInUSD: number;
smsType: 'Promotional' | 'Transactional';
mcc: number;
providerResponse: string;
dwellTimeMs: number;
dwellTimeMsUntilDeviceAck?: number;
};
status: 'SUCCESS' | 'FAILURE' | string;
messageId?: string;
}
3. Create SmsController:
This controller will handle both sending SMS messages and receiving status callbacks.
import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
UsePipes,
ValidationPipe,
Headers,
Logger,
RawBodyRequest,
Req,
Inject,
} from '@nestjs/common';
import { Request } from 'express';
import { SmsService } from './sms.service';
import { SendSmsDto } from './dto/send-sms.dto';
import { ConfigService } from '@nestjs/config';
import MessageValidator = require('sns-validator');
import { SnsNotificationRequest, SnsDeliveryStatusMessage } from './interfaces/sns-notification.interface';
@Controller('sms')
export class SmsController {
private readonly logger = new Logger(SmsController.name);
private readonly validator = new MessageValidator();
private readonly deliveryStatusTopicArn: string;
constructor(
private readonly smsService: SmsService,
private readonly configService: ConfigService,
) {
this.deliveryStatusTopicArn = this.configService.get<string>('DELIVERY_STATUS_TOPIC_ARN');
if (!this.deliveryStatusTopicArn) {
this.logger.warn('DELIVERY_STATUS_TOPIC_ARN is not set in environment variables. Callback Topic ARN validation cannot be performed.');
}
}
@Post('send')
@HttpCode(HttpStatus.ACCEPTED)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
async sendSms(@Body() sendSmsDto: SendSmsDto): Promise<{ messageId: string; status: string }> {
this.logger.log(`Received request to send SMS to ${sendSmsDto.phoneNumber}`);
const messageId = await this.smsService.sendSms(sendSmsDto.phoneNumber, sendSmsDto.message);
return { messageId, status: 'Message submission accepted by SNS.' };
}
@Post('status/callback')
@HttpCode(HttpStatus.OK)
async handleSnsCallback(@Req() req: RawBodyRequest<Request>, @Headers('x-amz-sns-message-type') messageType: string): Promise<string> {
const rawBody = req.rawBody?.toString('utf8');
if (!rawBody) {
this.logger.error('Raw body is missing from the request. Ensure rawBody:true is set for NestFactory.create in main.ts.');
return 'Error: Internal configuration error (missing raw body).';
}
let parsedBody: SnsNotificationRequest;
try {
parsedBody = JSON.parse(rawBody);
} catch (e) {
this.logger.error(`Failed to parse incoming SNS raw body: ${e.message}`, rawBody);
return 'Error: Invalid JSON format in request body.';
}
this.logger.log(`Received SNS callback of type: ${messageType || parsedBody.Type}`);
this.logger.debug(`Parsed SNS callback body: ${JSON.stringify(parsedBody)}`);
try {
const valid = await new Promise<boolean>((resolve, reject) => {
this.validator.validate(parsedBody, (err) => {
if (err) {
this.logger.error('SNS Message Validation Error:', err);
return reject(err);
}
this.logger.log('SNS message signature validated successfully.');
resolve(true);
});
});
if (!valid) {
throw new Error('SNS Message validation failed silently (unexpected state).');
}
if (this.deliveryStatusTopicArn && parsedBody.TopicArn !== this.deliveryStatusTopicArn) {
this.logger.warn(`Received message from unexpected Topic ARN: ${parsedBody.TopicArn}. Expected: ${this.deliveryStatusTopicArn}. Processing anyway (configurable behavior).`);
}
} catch (error) {
this.logger.error(`SNS Message Signature Validation Failed: ${error.message}`, error.stack);
return 'Error: Invalid SNS message signature.';
}
switch (parsedBody.Type) {
case 'SubscriptionConfirmation':
this.logger.log(`Received SubscriptionConfirmation from SNS for Topic: ${parsedBody.TopicArn}.`);
this.logger.warn(`**ACTION REQUIRED:** You MUST visit this URL to confirm the SNS subscription: ${parsedBody.SubscribeURL}`);
return 'SubscriptionConfirmation received. Please visit the SubscribeURL logged by the server to confirm.';
case 'Notification':
this.logger.log(`Received Notification from SNS. SNS MessageId: ${parsedBody.MessageId}`);
try {
const deliveryStatus: SnsDeliveryStatusMessage = JSON.parse(parsedBody.Message);
this.logger.debug(`Parsed Notification Message content: ${JSON.stringify(deliveryStatus)}`);
const originalMessageId = deliveryStatus.messageId || deliveryStatus.notification?.messageId;
const status = deliveryStatus.status;
const destination = deliveryStatus.delivery?.destination;
if (!originalMessageId || !status) {
this.logger.warn('Notification message content is incomplete (missing original messageId or status).', deliveryStatus);
return 'Warning: Incomplete notification data received.';
}
await this.smsService.processDeliveryStatus({
messageId: originalMessageId,
status: status.toUpperCase(),
destination: destination,
providerResponse: deliveryStatus.delivery?.providerResponse,
fullPayload: deliveryStatus,
});
return 'Notification processed successfully.';
} catch (parseError) {
this.logger.error(`Error parsing SNS Notification 'Message' field: ${parseError.message}`, parseError.stack);
return 'Error: Could not parse notification message content.';
}
case 'UnsubscribeConfirmation':
this.logger.log(`Received UnsubscribeConfirmation for TopicArn: ${parsedBody.TopicArn}. MessageId: ${parsedBody.MessageId}`);
return 'UnsubscribeConfirmation received.';
default:
this.logger.warn(`Received unknown SNS message type: '${parsedBody.Type}'. Body: ${JSON.stringify(parsedBody)}`);
return 'Unknown message type received.';
}
}
}
4. Enable Raw Body Parsing:
The sns-validator requires the raw, unparsed request body to verify the signature. Modify
src/main.ts to enable this globally.
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, {
rawBody: true,
});
const configService = app.get(ConfigService);
const port = configService.get<number>('PORT') || 3000;
const logger = new Logger('Bootstrap');
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
transform: true,
}));
await app.listen(port);
logger.log(`Application listening on port ${port}`);
logger.log(`Callback endpoint expected at: /sms/status/callback`);
}
bootstrap();
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 β