Developer Quick-Start: A guide on integrating AWS Simple Notification Service (SNS) with a NestJS application to build a scalable system for publishing marketing messages. 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.
Unlock the power of asynchronous communication and massive scalability for your marketing campaigns by integrating AWS Simple Notification Service (SNS) with your NestJS application. This guide provides a complete, step-by-step walkthrough for building a robust system capable of publishing marketing messages efficiently to a large number of subscribers.
We will build a NestJS backend service with an API endpoint that accepts campaign details and publishes them to an AWS SNS topic. Subscribers to this topic (e.g., email endpoints, SMS numbers, SQS queues connected to other microservices) will then receive the campaign message. This decouples your core application from the delivery mechanism, enabling high throughput and resilience.
Technologies Used:
- Node.js: Runtime environment.
- NestJS: Progressive Node.js framework for building efficient, reliable server-side applications.
- TypeScript: Superset of JavaScript adding static types.
- AWS SNS: Fully managed pub/sub messaging service for decoupling microservices, distributed systems, and serverless applications.
- AWS SDK for JavaScript v3: Modern AWS SDK for interacting with services like SNS.
- Dotenv &
@nestjs/config: For managing environment variables securely.
System Architecture:
+-----------------+ +-------------------+ +-----------------+ +----------------------+
| Client (e.g., |----->| NestJS API |----->| AWS SNS Topic |----->| Subscribers (Email, |
| Admin UI, CLI) | POST | (Campaign Service)| pub | (Marketing | sub | SMS, SQS, Lambda, etc)|
+-----------------+ +-------------------+ +-----------------+ +----------------------+
| - Validate Request |
| - Use AWS SDK |
| - Publish to SNS |
+-------------------+
Prerequisites:
- Node.js (LTS version recommended) and npm/yarn installed.
- An AWS account with permissions to manage SNS and IAM.
- AWS CLI installed and configured locally (for initial setup/testing is helpful).
- Basic understanding of NestJS concepts (modules, controllers, services, dependency injection).
- Familiarity with basic terminal/command-line operations.
- curl or a tool like Postman for testing API endpoints.
Final Outcome:
By the end of this guide, you will have a functional NestJS application capable of receiving marketing campaign requests via a REST API endpoint and publishing those campaigns as messages to an AWS SNS topic for broad distribution.
1. Setting Up the NestJS Project
Let's start by creating a new NestJS project and installing the necessary dependencies.
- Create a New NestJS Project: Open your terminal and run the NestJS CLI command:
npx @nestjs/cli new nestjs-sns-marketing
cd nestjs-sns-marketing
Choose your preferred package manager (npm or yarn) when prompted.
- Install Dependencies: We need the AWS SDK v3 client for SNS and NestJS configuration module.
npm install @aws-sdk/client-sns @nestjs/config dotenv class-validator class-transformer
yarn add @aws-sdk/client-sns @nestjs/config dotenv class-validator class-transformer
- @aws-sdk/client-sns: The AWS SDK for JavaScript v3 module specifically for interacting with SNS.
- @nestjs/config: For loading and accessing environment variables (like AWS credentials and SNS topic ARN).
- dotenv: To load environment variables from a .env file during development.
- class-validator & class-transformer: For request data validation using DTOs.
- Configure Environment Variables: Create a
.envfile in the root directory of your project (nestjs-sns-marketing/.env). This file will store sensitive information and configuration details. Never commit this file to version control.
.env
# .env
# AWS Credentials (Ensure the IAM user/role has sns:Publish permissions)
AWS_ACCESS_KEY_ID=YOUR_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=YOUR_AWS_SECRET_ACCESS_KEY
AWS_REGION=us-east-1 # Replace with your desired AWS region
# AWS SNS Configuration
SNS_MARKETING_TOPIC_ARN=YOUR_SNS_TOPIC_ARN # ARN of the SNS topic you'll create
# Application Port (Optional)
PORT=3000
# Database Path (Optional, if using Section 6)
# DATABASE_PATH=marketing_campaigns.sqlite
AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY: Obtain these by creating an IAM user in your AWS account with programmatic access and the necessary SNS permissions (specifically sns:Publish for the target topic). Follow AWS best practices for managing credentials securely. For production deployments in AWS environments (like EC2, ECS, Lambda, Fargate), always prefer using IAM roles attached to the compute resource over storing long-livedAWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEYas environment variables. IAM roles provide temporary, automatically rotated credentials, significantly improving security.AWS_REGION: The AWS region where your SNS topic resides (e.g., us-west-2, eu-central-1).SNS_MARKETING_TOPIC_ARN: The Amazon Resource Name (ARN) of the SNS topic you will create in the next step. It uniquely identifies the topic.PORT: The port your NestJS application will listen on.
- Load Environment Variables Globally: Modify
src/app.module.tsto import and configureConfigModuleglobally. This makes environment variables accessible throughout the application viaConfigService.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CampaignModule } from './campaign/campaign.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
CampaignModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- Project Structure: NestJS CLI generates a standard structure. We will add a
campaignmodule to encapsulate our marketing campaign functionality.
nestjs-sns-marketing/
βββ src/
β βββ campaign/ # Module for campaign features
β β βββ campaign.module.ts
β β βββ campaign.controller.ts
β β βββ campaign.service.ts
β β βββ dto/ # Data Transfer Objects for validation
β β β βββ send-campaign.dto.ts
β β βββ entities/ # (Optional) Database entities
β β βββ campaign.entity.ts
β βββ app.controller.ts
β βββ app.module.ts
β βββ app.service.ts
β βββ main.ts
βββ .env # Environment variables (DO NOT COMMIT)
βββ .gitignore
βββ nest-cli.json
βββ package.json
βββ tsconfig.build.json
βββ tsconfig.json
βββ # other config files...
2. Setting Up AWS SNS Topic
Before implementing the NestJS code, you need an SNS topic to publish messages to.
- Log in to AWS Management Console: Navigate to the AWS Management Console.
- Navigate to SNS: Find and select Simple Notification Service (SNS) under Application Integration services.
- Go to Topics: In the SNS dashboard navigation pane, click ""Topics"".
- Create Topic:
- Click the ""Create topic"" button.
- Type: Choose ""Standard"". Standard topics offer higher throughput and best-effort ordering, suitable for marketing campaigns where strict order isn't usually critical. FIFO topics guarantee order and exactly-once delivery but have lower throughput limits.
- Name: Enter a descriptive name, e.g., marketing-campaigns.
- Display name (optional): A shorter name used in SMS messages.
- Leave other settings as default for now (Access policy, Encryption, etc.) unless you have specific security requirements. You can refine the access policy later to restrict who can publish/subscribe.
- Click ""Create topic"".
- Copy Topic ARN: Once created, find your topic in the list. Click on its name to view details. Copy the ARN (Amazon Resource Name) displayed prominently. It will look something like: arn:aws:sns:us-east-1:123456789012:marketing-campaigns.
- Update
.envFile: Paste the copied ARN into your .env file for the SNS\_MARKETING\_TOPIC\_ARN variable.
Important IAM Permissions: Ensure the AWS credentials (access key/secret or IAM role) used
by your application have at least the sns:Publish permission for the specific Topic ARN you just
created. You can attach a policy like this to the user/role:
{
""Version"": ""2012-10-17"",
""Statement"": [
{
""Effect"": ""Allow"",
""Action"": ""sns:Publish"",
""Resource"": ""YOUR_SNS_TOPIC_ARN""
}
]
}
(Replace YOUR_SNS_TOPIC_ARN with your actual Topic ARN)
3. Implementing Core Functionality (SNS Publisher Service)
Now, let's create the service responsible for interacting with AWS SNS.
- Generate the Campaign Module, Controller, and Service: Use the NestJS CLI to scaffold the necessary components:
npx nest g module campaign
npx nest g controller campaign --no-spec
npx nest g service campaign --no-spec
This creates the src/campaign directory and its basic files. Remember to add
CampaignModule to the imports array in src/app.module.ts (as shown in
Step 1.4).
- Create the SNS Publisher Service (
campaign.service.ts): This service will encapsulate the logic for publishing messages to SNS using the AWS SDK v3.
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
SNSClient,
PublishCommand,
PublishCommandInput,
PublishCommandOutput,
} from '@aws-sdk/client-sns';
@Injectable()
export class CampaignService {
private readonly logger = new Logger(CampaignService.name);
private readonly snsClient: SNSClient;
private readonly topicArn: string;
constructor(private configService: ConfigService) {
this.snsClient = new SNSClient({
region: this.configService.getOrThrow<string>('AWS_REGION'),
});
this.topicArn = this.configService.getOrThrow<string>('SNS_MARKETING_TOPIC_ARN');
this.logger.log(`SNS Publisher initialized for topic: ${this.topicArn}`);
}
async publishCampaign(subject: string, messageBody: string): Promise<PublishCommandOutput> {
const params: PublishCommandInput = {
TopicArn: this.topicArn,
Subject: subject,
Message: messageBody,
};
this.logger.log(`Publishing campaign "${subject}" to ${this.topicArn}`);
try {
const command = new PublishCommand(params);
const response = await this.snsClient.send(command);
this.logger.log(`Message published successfully: ${response.MessageId}`);
return response;
} catch (error) {
this.logger.error(`Failed to publish message to SNS: ${error.message}`, error.stack);
throw new Error(`Failed to publish campaign: ${error.message}`);
}
}
}
Explanation:
- Dependencies: We inject ConfigService to access environment variables.
- Logger: A NestJS Logger instance for logging informative messages and errors.
- SNS Client Initialization: The SNSClient from @aws-sdk/client-sns is instantiated in the constructor. It automatically picks up credentials from standard sources (environment variables, shared files, IAM roles). The AWS\_REGION is explicitly set from ConfigService. getOrThrow ensures the application fails fast if essential variables like AWS\_REGION or SNS\_MARKETING\_TOPIC\_ARN are missing.
- Topic ARN: The target SNS\_MARKETING\_TOPIC\_ARN is also fetched and stored.
publishCampaignMethod:- Takes subject and messageBody as input.
- Constructs the PublishCommandInput object required by the AWS SDK. TopicArn and Message are mandatory. Subject is particularly useful for email subscribers.
- Uses SNSClient.send() with a PublishCommand to send the message. This is the modern asynchronous way to interact with the SDK v3.
- Logs success with the returned MessageId or logs and throws an error on failure.
- Why this approach? Encapsulating SNS logic in a dedicated service follows the principle of separation of concerns, making the code modular and testable. Using the AWS SDK v3 aligns with current AWS best practices.
4. Building the API Layer (Campaign Controller)
Now, create the API endpoint that will receive requests to send campaigns and utilize the
CampaignService.
- Create Data Transfer Object (DTO) for Validation: It's crucial to validate incoming
request data. We'll use NestJS's built-in validation pipes along with the
class-validatorlibrary (installed in Step 1.2).
Create the DTO file: src/campaign/dto/send-campaign.dto.ts
import { IsNotEmpty, IsString, MaxLength } from 'class-validator';
export class SendCampaignDto {
@IsString()
@IsNotEmpty()
@MaxLength(100)
subject: string;
@IsString()
@IsNotEmpty()
@MaxLength(262144)
messageBody: string;
}
- This DTO defines the expected shape of the request body (subject and messageBody).
- Decorators (@IsString, @IsNotEmpty, @MaxLength) provide validation rules.
- Enable Validation Pipe Globally: Enable automatic request validation by configuring
ValidationPipeinsrc/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.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
await app.listen(port);
logger.log(`Application listening on port ${port} - ${new Date().toISOString()}`);
}
bootstrap();
- Implement the Campaign Controller (
campaign.controller.ts): This controller defines the/campaignsroute and handles incoming POST requests.
import { Controller, Post, Body, HttpCode, HttpStatus, Logger, HttpException } from '@nestjs/common';
import { CampaignService } from './campaign.service';
import { SendCampaignDto } from './dto/send-campaign.dto';
@Controller('campaigns')
export class CampaignController {
private readonly logger = new Logger(CampaignController.name);
constructor(private readonly campaignService: CampaignService) {}
@Post('send')
@HttpCode(HttpStatus.ACCEPTED)
async sendCampaign(@Body() sendCampaignDto: SendCampaignDto) {
this.logger.log(
`Received request to send campaign: Subject - ""${sendCampaignDto.subject}""`,
);
try {
const result = await this.campaignService.publishCampaign(
sendCampaignDto.subject,
sendCampaignDto.messageBody,
);
return {
status: 'Campaign submitted for publishing',
messageId: result.MessageId,
};
} catch (error) {
this.logger.error(`Error processing send campaign request: ${error.message}`, error.stack);
if (error instanceof Error) {
throw new HttpException(
`Failed to process campaign: ${error.message}`,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
throw new HttpException(
'An unexpected error occurred while processing the campaign.',
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
}
Explanation:
@Controller('campaigns'): Defines the base route for this controller.constructor: Injects the CampaignService.@Post('send'): Defines a handler for POST requests to /campaigns/send.@Body(): Decorator that extracts the request body. Combined with the ValidationPipe (enabled globally in main.ts), it automatically validates the incoming data against SendCampaignDto.@HttpCode(HttpStatus.ACCEPTED): Sets the default success status code to 202 Accepted. This is appropriate because publishing to SNS is asynchronous; we've accepted the request for processing, but delivery isn't guaranteed synchronously.- Logic: Calls the campaignService.publishCampaign method with data from the validated DTO.
- Response: Returns a success message including the MessageId received from SNS (or potentially the database campaignId if using Section 6).
- Error Handling: Catches errors from the service call. The example now uses HttpException to return a 500 status code with a more informative message, but a custom Exception Filter is recommended for production to handle different error types gracefully.
5. Error Handling, Logging, and Retry Mechanisms
- Error Handling Strategy:
- Validation Errors: Handled automatically by ValidationPipe, returning 400 Bad Request responses with details.
- SNS Publishing Errors: Caught within CampaignService, logged with details (including stack trace), and re-thrown. The controller catches this and can return an appropriate HTTP error (e.g., 500 Internal Server Error via HttpException or a custom filter). For production, implement a custom Exception Filter (@Catch()) to map specific errors (e.g., AWS SDK throttling errors like ThrottlingException) to appropriate HTTP status codes (like 429 Too Many Requests or 503 Service Unavailable) and provide user-friendly error messages.
- Configuration Errors: ConfigService.getOrThrow in CampaignService ensures the app fails on startup if essential environment variables are missing.
- Logging:
- NestJS's built-in Logger is used in the service, controller, and main.ts.
- Logs provide context (e.g., "Received request", "Publishing campaign", "Message published successfully", error details). Include correlation IDs (like campaignId if using Section 6, or a generated request ID) for easier tracing.
- In production, configure logging levels (e.g., only log INFO and above) and consider structured logging (JSON format) for easier parsing by log aggregation tools (like CloudWatch Logs, Datadog, Splunk). NestJS allows custom logger implementations.
- Retry Mechanisms (SNS):
- Client-Side: The AWS SDK v3 has built-in retry mechanisms with exponential backoff for transient network errors or throttled requests (like ProvisionedThroughputExceededException or ThrottlingException). This is configurable when creating the SNSClient but defaults are usually reasonable.
- Server-Side (SNS): SNS itself provides delivery retries for certain destination types (like HTTP/S endpoints) if they fail to acknowledge receipt. This doesn't apply directly to publishing to SNS but is relevant for subscribers.
- Application-Level Retries: For critical campaigns, if the initial snsClient.send() fails with a potentially retryable error (e.g., temporary service unavailability not handled by the SDK's retries), you could implement a custom retry loop within your CampaignService using libraries like async-retry, but rely on the SDK's built-in retries first.
Example: Testing an Error Scenario
- Temporarily change SNS\_MARKETING\_TOPIC\_ARN in your .env to an invalid ARN (e.g., append -invalid).
- Restart the application (npm run start:dev).
- Send a valid POST request to /campaigns/send.
- Observe the application logs β you should see the "Failed to publish message to SNS" error logged by CampaignService.
- Observe the API response β you should receive a 500 Internal Server Error (or the response defined by your controller's error handling/exception filter).
6. Database Schema and Data Layer (Optional)
While not strictly required for publishing campaigns, you might want to store campaign metadata or track publishing status. Here's a minimal example using TypeORM and SQLite.
- Install Database Dependencies:
npm install @nestjs/typeorm typeorm sqlite3
yarn add @nestjs/typeorm typeorm sqlite3
- Create Campaign Entity (
src/campaign/entities/campaign.entity.ts):
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from 'typeorm';
export enum CampaignStatus {
PENDING = 'PENDING',
SUBMITTED = 'SUBMITTED',
FAILED = 'FAILED',
}
@Entity('campaigns')
export class Campaign {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ length: 100 })
subject: string;
@Column('text')
messageBody: string;
@Index()
@Column({
type: 'varchar',
enum: CampaignStatus,
default: CampaignStatus.PENDING,
})
status: CampaignStatus;
@Index()
@Column({ nullable: true })
snsMessageId?: string;
@CreateDateColumn()
createdAt: Date;
@Column({ type: 'text', nullable: true })
failureReason?: string;
}
- Configure TypeORM in
AppModule(src/app.module.ts):
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CampaignModule } from './campaign/campaign.module';
import { Campaign } from './campaign/entities/campaign.entity';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env' }),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'sqlite',
database: configService.get<string>('DATABASE_PATH', 'marketing_campaigns.sqlite'),
entities: [Campaign],
synchronize: configService.get<string>('NODE_ENV') !== 'production',
logging: false,
}),
inject: [ConfigService],
}),
CampaignModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- Add DATABASE\_PATH=marketing\_campaigns.sqlite to your .env (or choose another path/DB).
synchronize: true: Disable this in production and use TypeORM Migrations for controlled schema changes.
- Inject Repository and Update Service (
src/campaign/campaign.module.ts&src/campaign/campaign.service.ts):
- Module:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CampaignController } from './campaign.controller';
import { CampaignService } from './campaign.service';
import { Campaign } from './entities/campaign.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Campaign]),
],
controllers: [CampaignController],
providers: [CampaignService],
})
export class CampaignModule {}
- Service:
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SNSClient, PublishCommand, PublishCommandInput } from '@aws-sdk/client-sns';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Campaign, CampaignStatus } from './entities/campaign.entity';
@Injectable()
export class CampaignService {
private readonly logger = new Logger(CampaignService.name);
private readonly snsClient: SNSClient;
private readonly topicArn: string;
constructor(
private configService: ConfigService,
@InjectRepository(Campaign)
private campaignRepository: Repository<Campaign>,
) {
this.snsClient = new SNSClient({
region: this.configService.getOrThrow<string>('AWS_REGION'),
});
this.topicArn = this.configService.getOrThrow<string>('SNS_MARKETING_TOPIC_ARN');
this.logger.log(`SNS Publisher initialized for topic: ${this.topicArn}`);
}
async publishCampaign(subject: string, messageBody: string): Promise<{ campaignId: string; messageId?: string }> {
let campaign = this.campaignRepository.create({
subject,
messageBody,
status: CampaignStatus.PENDING,
});
campaign = await this.campaignRepository.save(campaign);
this.logger.log(`Created campaign record ${campaign.id}`);
const params: PublishCommandInput = {
TopicArn: this.topicArn,
Subject: subject,
Message: messageBody,
};
this.logger.log(`Publishing campaign ""${subject}"" (ID: ${campaign.id}) to ${this.topicArn}`);
try {
const command = new PublishCommand(params);
const response = await this.snsClient.send(command);
campaign.status = CampaignStatus.SUBMITTED;
campaign.snsMessageId = response.MessageId;
await this.campaignRepository.save(campaign);
this.logger.log(`Message published successfully: ${response.MessageId} for campaign ${campaign.id}`);
return { campaignId: campaign.id, messageId: response.MessageId };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
this.logger.error(`Failed to publish message to SNS for campaign ${campaign.id}: ${errorMessage}`, error instanceof Error ? error.stack : undefined);
campaign.status = CampaignStatus.FAILED;
campaign.failureReason = errorMessage.substring(0, 500);
await this.campaignRepository.save(campaign);
throw new Error(`Failed to publish campaign ${campaign.id}: ${errorMessage}`);
}
}
}
- Controller Update: If using the database approach, the service now returns
{ campaignId: string; messageId?: string }. You would update the controller's success response accordingly (as commented out in the controller example).
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 β