Tutorials

Build Production-Ready Two-Way SMS with NestJS and AWS

A step-by-step guide to building a system for receiving and processing inbound SMS messages using NestJS, AWS SNS, SQS, Lambda, and Amazon Pinpoint SMS/Voice.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 7, 2026 β€’ 13 min read

Developer Quick-Start: A step-by-step guide to building a system for receiving and processing inbound SMS messages using NestJS, AWS SNS, SQS, Lambda, and Amazon Pinpoint SMS/Voice. 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 guide provides a step-by-step walkthrough for building a robust system capable of receiving and processing inbound SMS messages using NestJS, AWS Simple Notification Service (SNS), AWS Simple Queue Service (SQS), AWS Lambda, and Amazon Pinpoint (specifically its SMS and Voice capabilities).

We will construct a NestJS application triggered by incoming SMS messages, allowing you to build interactive experiences, automate responses, or process SMS data effectively.

Project Goals:

  • Receive inbound SMS messages sent to a dedicated AWS phone number.
  • Route these messages reliably via SNS and SQS to a Lambda function.
  • Process the incoming messages using a NestJS application running within the Lambda function.
  • Enable the NestJS application to potentially send outbound replies.
  • Establish a scalable, decoupled, and production-ready architecture.

Core Technologies:

  • NestJS: A progressive Node.js framework for building efficient, reliable server-side applications. Chosen for its modularity, testability, and microservice capabilities.
  • Amazon Pinpoint (SMS and Voice): The AWS service for acquiring phone numbers and managing SMS/MMS communications, including two-way messaging configuration via its ""SMS and Voice"" console section.
  • AWS SNS (Simple Notification Service): A fully managed messaging service. Used here to receive notifications when an SMS is sent to the AWS phone number.
  • AWS SQS (Simple Queue Service): A fully managed message queuing service. Used to decouple the SNS notification from the processing logic, providing resilience and buffering.
  • AWS Lambda: A serverless compute service. Used to host and execute the NestJS application code in response to messages arriving in the SQS queue.
  • AWS SDK for JavaScript v3: Used within the NestJS application for potential interactions with AWS services (e.g., sending replies via the Pinpoint SMS/Voice v2 API).
  • Serverless Framework (or AWS CDK): Infrastructure-as-Code tools recommended for deploying and managing the required AWS resources (SNS, SQS, Lambda, IAM Roles).

System Architecture:

graph LR
    subgraph User
        A[Mobile Phone]
    end

    subgraph AWS Cloud
        B(Amazon Pinpoint SMS/Voice) -- Inbound SMS --> C(SNS Topic);
        C -- Publishes --> D(SQS Queue);
        D -- Triggers --> E(Lambda Function);
        subgraph Lambda Function / NestJS App
            E -- Executes --> F{NestJS App};
            F -- Processes --> G[Message Handler Logic];
            G -- Optional Reply --> H(AWS SDK);
        end
        H -- Send SMS API Call --> B;
    end

    A -- Sends SMS --> B;
    B -- Sends Reply --> A;

    style F fill:#f9f,stroke:#333,stroke-width:2px

Prerequisites:

  • An AWS account with appropriate permissions to create/manage SNS, SQS, Lambda, IAM, and Amazon Pinpoint (SMS/Voice) resources.
  • Node.js (LTS version recommended) and npm/yarn installed locally.
  • NestJS CLI installed globally: npm install -g @nestjs/cli
  • AWS CLI installed and configured locally.
  • A provisioned phone number within Amazon Pinpoint capable of two-way SMS in your desired region(s). Refer to SMS and MMS country capabilities and limitations.
  • Basic understanding of TypeScript and NestJS concepts.
  • (Optional but Recommended) Familiarity with the Serverless Framework or AWS CDK.

Final Outcome:

By the end of this guide, you will have a deployed AWS Lambda function running a NestJS application. This application will automatically process incoming SMS messages sent to your configured AWS phone number, with logs visible in CloudWatch and a clear structure for adding custom business logic and replies.


1. Setting Up the Local NestJS Project

Let's initialize our NestJS project and install necessary dependencies.

  1. Create NestJS Project: Open your terminal and run:
   nest new nestjs-sms-handler
   cd nestjs-sms-handler

Choose your preferred package manager (npm or yarn) when prompted.

  1. Project Structure: NestJS creates a standard project structure:
   /
   β”œβ”€β”€ src/
   β”‚   β”œβ”€β”€ app.controller.ts
   β”‚   β”œβ”€β”€ app.module.ts
   β”‚   β”œβ”€β”€ app.service.ts
   β”‚   └── main.ts         # Standard entry point (we'll adapt this for Lambda)
   β”œβ”€β”€ test/
   β”œβ”€β”€ node_modules/
   β”œβ”€β”€ .eslintrc.js
   β”œβ”€β”€ .gitignore
   β”œβ”€β”€ .prettierrc
   β”œβ”€β”€ nest-cli.json
   β”œβ”€β”€ package.json
   β”œβ”€β”€ README.md
   β”œβ”€β”€ tsconfig.build.json
   └── tsconfig.json

This structure promotes modularity and separation of concerns.

  1. Install AWS SDK v3: We need the AWS SDK to interact with AWS services, specifically for potentially sending replies via the Pinpoint SMS/Voice v2 API.
   npm install @aws-sdk/client-pinpoint-sms-voice-v2

   yarn add @aws-sdk/client-pinpoint-sms-voice-v2

Why SDK v3? It offers modularity (smaller bundles) and improved TypeScript support compared to v2.

  1. Environment Variables: Create a .env file in the project root for local development configuration. Important: Never commit .env files containing secrets (like AWS keys) to your source code repository. Use a .env.example file to track required variables without their values. Use secure methods like CI/CD secrets or AWS Secrets Manager for production deployments.

.env

   # .env
   AWS_REGION=us-east-1 # Your AWS region
   AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID # For local testing only - use IAM Roles in Lambda
   AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY # For local testing only
   SNS_TOPIC_ARN=arn:aws:sns:us-east-1:123456789012:YourSmsTopic # ARN of your SNS topic
   SQS_QUEUE_URL=https://sqs.us-east-1.amazonaws.com/123456789012/YourSmsQueue # URL of your SQS queue
   PINPOINT_PHONE_NUMBER=+1XXXXXXXXXX # Your AWS provisioned phone number
   PINPOINT_APP_ID=YOUR_PINPOINT_PROJECT_ID # Optional: If using Pinpoint project features

   # Add any other config needed by your app
   LOG_LEVEL=debug
  • Obtaining Values:
  • AWS\_REGION: The AWS region where you'll deploy resources (e.g., us-east-1, eu-west-2).
  • AWS\_ACCESS\_KEY\_ID/AWS\_SECRET\_ACCESS\_KEY: Generate these from the AWS IAM console for a dedicated user only for local development. In production Lambda, rely on execution roles for permissions.
  • SNS\_TOPIC\_ARN, SQS\_QUEUE\_URL: You will create these in the next step. Note their ARNs/URLs.
  • PINPOINT\_PHONE\_NUMBER: The number obtained from Amazon Pinpoint (SMS and Voice section).
  • PINPOINT\_APP\_ID: If you created an Amazon Pinpoint project for analytics or campaigns, find its ID in the Pinpoint console. Often not strictly required just for basic two-way SMS configuration.
  1. Configuration Module (Optional but Recommended): Use NestJS's @nestjs/config module for managing environment variables.
   npm install @nestjs/config

   yarn add @nestjs/config

Update src/app.module.ts:

   import { Module } from '@nestjs/common';
   import { ConfigModule } from '@nestjs/config';
   import { AppController } from './app.controller';
   import { AppService } from './app.service';

   @Module({
     imports: [
       ConfigModule.forRoot({
         isGlobal: true,
         envFilePath: '.env',
       }),

     ],
     controllers: [AppController],
     providers: [AppService],
   })
   export class AppModule {}

2. Setting Up AWS Resources (SNS, SQS, Two-Way SMS)

Now, configure the necessary AWS infrastructure to route SMS messages to where our future Lambda function can process them. We recommend using Infrastructure as Code (IaC) like the Serverless Framework or AWS CDK for managing these resources in production, but we'll outline the manual console steps here for clarity.

  1. Create an SNS Topic: This topic will receive notifications when an SMS arrives at your AWS phone number.
  • Navigate to the SNS service in the AWS Management Console.
  • Go to Topics and click Create topic.
  • Choose Standard type (FIFO is not typically needed for SMS).
  • Enter a Name (e.g., InboundSmsNotifications).
  • Keep default settings for Access policy, Encryption, etc., unless you have specific requirements.
  • Click Create topic.
  • Note down the ARN (Amazon Resource Name) of the created topic (e.g., arn:aws:sns:us-east-1:123456789012:InboundSmsNotifications). You'll need this for .env and the phone number configuration.
  1. Create an SQS Queue: This queue will subscribe to the SNS topic and hold messages until the Lambda function processes them. This provides decoupling and automatic retries.
  • Navigate to the SQS service in the AWS Management Console.
  • Click Create queue.
  • Choose Standard queue type.
  • Enter a Name (e.g., InboundSmsProcessingQueue).
  • Configure Access policy:
  • Choose Advanced.
  • You need to grant the SNS topic permission to send messages to this queue. Replace YOUR\_REGION, YOUR\_ACCOUNT\_ID, YOUR\_SNS\_TOPIC\_ARN, and YOUR\_SQS\_QUEUE\_ARN with your actual values.
     {
       ""Version"": ""2012-10-17"",
       ""Statement"": [
         {
           ""Effect"": ""Allow"",
           ""Principal"": {
             ""Service"": ""sns.amazonaws.com""
           },
           ""Action"": ""sqs:SendMessage"",
           ""Resource"": ""YOUR_SQS_QUEUE_ARN"",
           ""Condition"": {
             ""ArnEquals"": {
               ""aws:SourceArn"": ""YOUR_SNS_TOPIC_ARN""
             }
           }
         }
       ]
     }
  • Dead-letter queue (Recommended): Configure a DLQ to capture messages that fail processing repeatedly. Create another standard queue (e.g., InboundSmsDeadLetterQueue) and configure it here with a Maximum receives count (e.g., 3).
  • Click Create queue.
  • Note down the URL and ARN of the created queue.
  1. Subscribe SQS Queue to SNS Topic:
  • Go back to the SNS service and select the topic you created (InboundSmsNotifications).
  • Go to the Subscriptions tab and click Create subscription.
  • Protocol: Select Amazon SQS.
  • Endpoint: Paste the ARN of the SQS queue (InboundSmsProcessingQueue) you created.
  • Enable raw message delivery (Recommended): Check this box. It prevents SNS from adding extra metadata, simplifying parsing in your Lambda function. If unchecked, the original SMS payload will be nested inside an SNS message structure within the SQS message body. Your Lambda parsing logic must match this setting.
  • Click Create subscription.
  1. Configure Two-Way SMS for Your Phone Number: Link your AWS-provisioned phone number to the SNS topic.
  • Navigate to the Amazon Pinpoint service in the AWS Management Console.
  • In the navigation pane, find the SMS and Voice section (this might be top-level or nested under Settings/Channels).
  • Under Number settings (or similar, e.g., ""Phone numbers""), choose Phone numbers.
  • Select the phone number you want to use for inbound messages.
  • Go to the Two-way SMS tab (or section) and choose Edit (or ""Manage"").
  • Enable two-way SMS: Check the box.
  • Incoming messages destination: Select SNS topic.
  • SNS topic: Choose the SNS topic (InboundSmsNotifications) you created from the dropdown.
  • IAM role for SNS publishing: This defines permissions for the Amazon Pinpoint service to publish to your SNS topic.
  • You can let AWS manage this via Use Amazon SNS topic policies (simplest if your topic policy allows sms-voice.amazonaws.com or is broadly permissive).
  • Alternatively, choose Choose an existing IAM role and select/create an IAM role with a policy like this (replace YOUR\_SNS\_TOPIC\_ARN):
       {
           ""Version"": ""2012-10-17"",
           ""Statement"": [
               {
                   ""Effect"": ""Allow"",
                   ""Action"": ""sns:Publish"",
                   ""Resource"": ""YOUR_SNS_TOPIC_ARN""
               }
           ]
       }

The role's trust policy must allow the sms-voice.amazonaws.com service principal.

  • Click Save changes.

Message Flow Recap: SMS Sent to AWS Number -> Amazon Pinpoint Service -> SNS Topic (InboundSmsNotifications) -> SQS Queue (InboundSmsProcessingQueue) -> (Next Step: Lambda Trigger)


3. Implementing Core Functionality in NestJS

Now we adapt the NestJS application to run in Lambda and process messages from the SQS queue. We'll use a custom strategy pattern similar to the one described in the research for handling microservice-like events triggered by Lambda.

  1. Create a Custom Transport Strategy: This strategy won't actively listen like traditional NestJS microservice transports; instead, it provides a way for our Lambda handler to find the correct NestJS method based on the incoming message content.
   import { CustomTransportStrategy, Server, Transport } from '@nestjs/microservices';
   import { Logger } from '@nestjs/common';

   export class SnsSqsStrategy extends Server implements CustomTransportStrategy {
     private readonly logger = new Logger(SnsSqsStrategy.name);
     transportId?: Transport;


     listen(callback: () => void) {
       this.logger.log('SNS/SQS Strategy initialized. Waiting for Lambda trigger.');
       callback();
     }


     close() {
       this.logger.log('SNS/SQS Strategy closing.');
     }


     public getHandlerByPattern(pattern: string) {


       return this.messageHandlers.get(pattern);
     }
   }
  1. Adapt main.ts for Lambda: Modify the main entry point to bootstrap NestJS once per Lambda container instance and handle incoming SQSEvent records. We use ReplaySubject from RxJS to manage the bootstrapping process efficiently, reducing cold start impact on subsequent invocations within the same container.
   import { NestFactory } from '@nestjs/core';
   import { Logger } from '@nestjs/common';
   import { MicroserviceOptions } from '@nestjs/microservices';
   import { Context, Handler, SQSEvent, SQSRecord } from 'aws-lambda';
   import { ReplaySubject, firstValueFrom } from 'rxjs';
   import { AppModule } from './app.module';
   import { SnsSqsStrategy } from './sns-sqs.strategy';

   const logger = new Logger('LambdaHandler');

   const strategySubject = new ReplaySubject<SnsSqsStrategy>();

   async function bootstrap(): Promise<SnsSqsStrategy> {
     logger.log('COLD START: Initializing NestJS Microservice...');
     const strategy = new SnsSqsStrategy();
     const app = await NestFactory.createMicroservice<MicroserviceOptions>(
       AppModule,
       {
         strategy: strategy,


       },
     );


     app.useLogger(app.get(Logger));

     await app.init();


     logger.log('NestJS Microservice Initialized.');
     return strategy;
   }

   bootstrap().then((strategy) => strategySubject.next(strategy));

   export const handler: Handler = async (
     event: SQSEvent,
     context: Context,
   ): Promise<void> => {
     logger.log(`Received event: ${JSON.stringify(event)}`);


     const strategy = await firstValueFrom(strategySubject);
     if (!strategy) {
       logger.error('FATAL: Strategy not initialized!');
       return;
     }


     for (const record of event.Records) {
       try {
         await processRecord(record, strategy, context);
       } catch (error) {
         logger.error(`Error processing record ${record.messageId}: ${error}`, error.stack);




       }
     }
     logger.log('Finished processing batch.');
   };

   async function processRecord(
     record: SQSRecord,
     strategy: SnsSqsStrategy,
     context: Context,
   ): Promise<void> {
     logger.log(`Processing SQS message ID: ${record.messageId}`);
















     let smsPayload: {
       originationNumber: string;
       destinationNumber: string;
       messageKeyword: string;
       messageBody: string;
       previousPublishedMessageId?: string;
       inboundMessageId: string;
     };

     try {

       smsPayload = JSON.parse(record.body);







       if (
         !smsPayload ||
         !smsPayload.messageBody ||
         !smsPayload.originationNumber
       ) {
         logger.warn(
           `Skipping message: Missing essential fields in payload: ${JSON.stringify(smsPayload)}`,
         );
         return;
       }

     } catch (error) {
       logger.error(`Failed to parse SMS payload from SQS record body. Raw Delivery Enabled? Body: ${record.body}`, error.stack);
       return;
     }

     logger.log(`Processing SMS from ${smsPayload.originationNumber}: "${smsPayload.messageBody}"`);





     const messagePattern = 'process_incoming_sms';

     const handler = strategy.getHandlerByPattern(messagePattern);

     if (!handler) {
       logger.warn(`No handler found for pattern: ${messagePattern}`);
       return;
     }


     logger.debug(`Invoking handler for pattern: ${messagePattern}`);



     await handler(smsPayload, context);

     logger.debug(`Handler executed successfully for message ID: ${record.messageId}`);
   }

Key Points:

  • bootstrap() initializes NestJS and returns the strategy instance.
  • strategySubject.next(strategy) stores the instance in a ReplaySubject.
  • The handler function retrieves the strategy using firstValueFrom(strategySubject), ensuring Nest is ready.
  • It iterates through SQSEvent.Records.
  • processRecord parses the record.body. Crucially, this logic assumes SNS raw message delivery is enabled. A prominent comment explains how to adjust if it's disabled.
  • It determines a messagePattern (e.g., based on keywords in the messageBody, or a default pattern).
  • strategy.getHandlerByPattern(messagePattern) retrieves the corresponding NestJS handler function.
  • handler(smsPayload, context) executes the NestJS function.
  1. Create an SMS Handling Module and Controller: Organize the SMS processing logic within a dedicated NestJS module.
   nest generate module sms
   nest generate controller sms --no-spec
   nest generate service sms --no-spec

Update src/sms/sms.module.ts:

   import { Module, Logger } from '@nestjs/common';
   import { SmsController } from './sms.controller';
   import { SmsService } from './sms.service';
   import { ConfigModule } from '@nestjs/config';

   @Module({
     imports: [ConfigModule],
     controllers: [SmsController],
     providers: [SmsService, Logger],
   })
   export class SmsModule {}

Import SmsModule into src/app.module.ts:

   import { Module } from '@nestjs/common';
   import { ConfigModule } from '@nestjs/config';
   import { SmsModule } from './sms/sms.module';

   @Module({
     imports: [
       ConfigModule.forRoot({
         isGlobal: true,
         envFilePath: '.env',
       }),
       SmsModule,
     ],

     controllers: [],
     providers: [],
   })
   export class AppModule {}

Implement the controller with an @EventPattern decorator matching the pattern used in main.ts.

   import { Controller, Logger, Inject } from '@nestjs/common';
   import { EventPattern, Payload, Ctx } from '@nestjs/microservices';
   import { Context } from 'aws-lambda';
   import { SmsService } from './sms.service';

   interface InboundSmsPayload {
     originationNumber: string;
     destinationNumber: string;
     messageKeyword: string;
     messageBody: string;
     previousPublishedMessageId?: string;
     inboundMessageId: string;
   }

   @Controller()
   export class SmsController {

     constructor(
       private readonly logger: Logger,
       private readonly smsService: SmsService,
     ) {}


     @EventPattern('process_incoming_sms')
     async handleIncomingSms(
       @Payload() data: InboundSmsPayload,
       @Ctx() context?: Context,
     ): Promise<void> {
       this.logger.log(
         `Handling incoming SMS via EventPattern: ${JSON.stringify(data)}`,
         SmsController.name,
       );


       if (context) {
         this.logger.debug(`Lambda Context: RequestId: ${context.awsRequestId}`, SmsController.name);
       }



       const messageBodyLower = data.messageBody.toLowerCase().trim();


       if (messageBodyLower === 'help') {
         await this.smsService.sendReply(
           data.originationNumber,
           'Available commands: INFO, STATUS. For help, text HELP.',
         );
       } else if (messageBodyLower === 'stop') {

          this.logger.log(`Received STOP request from ${data.originationNumber}`);

          await this.smsService.handleOptOut(data.originationNumber);
       } else {

         this.logger.log(`Processing default message from ${data.originationNumber}`);

         await this.smsService.storeMessage(data);

          await this.smsService.sendReply(
            data.originationNumber,
            `Received your message: "${data.messageBody.substring(0, 20)}..."`,
          );
       }

       this.logger.log(`Finished processing SMS from ${data.originationNumber}`, SmsController.name);

     }



   }
  1. Implement the SMS Service (Optional Reply Logic): Create methods for business logic, like sending replies using the AWS SDK.
   import { Injectable, Logger } from '@nestjs/common';
   import { ConfigService } from '@nestjs/config';
   import {
     PinpointSMSVoiceV2Client,
     SendTextMessageCommand,
     SendTextMessageCommandInput,
   } from '@aws-sdk/client-pinpoint-sms-voice-v2';

   @Injectable()
   export class SmsService {
     private readonly logger = new Logger(SmsService.name);
     private readonly awsSmsClient: PinpointSMSVoiceV2Client;
     private readonly senderPhoneNumber: string;

     constructor(private configService: ConfigService) {
       this.awsSmsClient = new PinpointSMSVoiceV2Client({
         region: this.configService.get<string>('AWS_REGION'),


       });
       this.senderPhoneNumber = this.configService.get<string>('PINPOINT_PHONE_NUMBER');
       if (!this.senderPhoneNumber) {
           this.logger.error('PINPOINT_PHONE_NUMBER environment variable is not set!');
       }
     }

     async sendReply(recipientNumber: string, message: string): Promise<void> {
        if (!this.senderPhoneNumber) {
            this.logger.error('Cannot send reply: Sender phone number is not configured.');
            return;
        }

       this.logger.log(`Attempting to send reply to ${recipientNumber}: "${message}"`);
       const params: SendTextMessageCommandInput = {
         DestinationPhoneNumber: recipientNumber,



         OriginationIdentity: this.senderPhoneNumber,
         MessageBody: message,


       };

       try {
         const command = new SendTextMessageCommand(params);
         const result = await this.awsSmsClient.send(command);
         this.logger.log(`Successfully sent message. Message ID: ${result.MessageId}`);
       } catch (error) {
         this.logger.error(`Failed to send SMS to ${recipientNumber}: ${error}`, error.stack);

       }
     }

     async storeMessage(payload: any): Promise<void> {

       this.logger.log(`Storing message from ${payload.originationNumber}: ${JSON.stringify(payload)}`);

     }

     async handleOptOut(phoneNumber: string): Promise<void> {


        this.logger.log(`Processing opt-out for ${phoneNumber}`);



     }
   }

4. Troubleshooting and Caveats

  • Permissions: The most common issue. Ensure:
  • The IAM role/policy used in the Pinpoint phone number's two-way configuration can sns:Publish to your SNS topic.
  • SNS topic policy allows the Pinpoint SMS/Voice service (sms-voice.amazonaws.com) or the specific role ARN.
  • SQS queue policy allows sqs:SendMessage from the SNS topic ARN (aws:SourceArn condition).
  • Lambda Execution Role has permissions for:
  • sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes for the SQS queue.
  • logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents for CloudWatch Logs.
  • cloudwatch:PutMetricData (often included in basic execution role).
  • pinpoint-sms-voice:SendTextMessage (or broader sms-voice:\*) if sending replies, using the pinpoint-sms-voice-v2 API.
  • Any database permissions (DynamoDB, RDS).
  • Message Parsing (Raw Delivery): Your Lambda parsing logic must match the ""Enable raw message delivery"" setting on the SNS->SQS subscription. This guide's code assumes it's enabled. If disabled, you need to parse the outer SNS structure first (JSON.parse(record.body).Message). Log the raw record.body in CloudWatch to verify the structure you receive.
  • Region Consistency: Keep your Phone Number, SNS Topic, SQS Queue, and Lambda Function in the same AWS Region for simplicity and lower latency, unless you have specific cross-region requirements.
  • Delays: There can sometimes be minor delays in the AWS pipeline (SMS -> Pinpoint -> SNS -> SQS -> Lambda). Design your application to be tolerant of potential latency.
  • Error Handling & Retries: Configure SQS Dead Letter Queues (DLQs) to handle messages that consistently fail processing. Implement robust error handling within your Lambda function and decide whether failed messages should be retried (by throwing an error from the Lambda handler) or discarded/logged.
  • Concurrency: Understand Lambda concurrency limits and how they interact with SQS batching and processing time. Adjust Lambda reserved concurrency if needed.
  • Cost: Be mindful of the costs associated with each AWS service (Pinpoint phone number rental/usage, SNS messages, SQS requests, Lambda execution time, CloudWatch logs).
  • Opt-Out Handling: Ensure compliance with regulations regarding SMS opt-out requests (e.g., STOP keyword). AWS Pinpoint might handle some standard keywords automatically depending on the region and number type, but you may need custom logic to update your own systems.
  • SDK Initialization: The AWS SDK v3 clients are initialized in the service constructor (SmsService). This means the client is created once per Lambda container instance, which is efficient. Ensure the Lambda execution role provides the necessary credentials.

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 β†’