Developer Guide: Sending WhatsApp Messages via AWS SNS with Fastify - code-examples -

Frequently Asked Questions

You can send WhatsApp messages using AWS SNS by publishing message details to an SNS topic, which then triggers a Lambda function to interact with the WhatsApp Business API. This decouples your main application from the WhatsApp API, enhancing scalability and resilience. Your application publishes messages to SNS, while a separate process handles the actual WhatsApp interaction.
Fastify acts as a high-performance web framework to create an API endpoint that receives WhatsApp message requests. It validates incoming requests for required parameters like phone number and message content before securely publishing to AWS SNS. This setup maintains a decoupled architecture.
AWS SNS provides a managed pub/sub service for decoupling and scaling message delivery. By using SNS, your core application doesn't need to directly interact with the WhatsApp Business API. This improves resilience and allows for easier management of message workflows.
This architecture is ideal for applications requiring scalable and reliable WhatsApp messaging. Decoupling with SNS becomes particularly beneficial with higher message volumes and complex workflows where direct WhatsApp API integration within the core app would introduce overhead and complexity.
This guide focuses on using SNS as an intermediary; the Fastify application doesn't interact with the WhatsApp API directly. A downstream service, typically an AWS Lambda function, subscribes to the SNS topic and handles direct communication with the WhatsApp Business API.
You'll need an IAM user with programmatic access, specifically the Access Key ID and Secret Access Key. These credentials are used by the AWS SDK to authorize your Fastify application to publish messages to the SNS topic. It's recommended to create a user with least privilege access - permissions only to publish to the relevant SNS topic.
A typical structure includes 'src/routes/whatsapp.js' for API routes, 'src/server.js' for the Fastify server, '.env' for environment variables, and '.gitignore' to exclude sensitive data. The 'routes/whatsapp.js' file contains the core logic for handling incoming requests and publishing to SNS.
Secure your setup by using environment variables for sensitive data, implementing robust authentication beyond the example API key (e.g., JWT), using HTTPS, and leveraging tools like Helmet. Regularly audit dependencies for vulnerabilities using 'npm audit'.
Fastify's built-in schema validation is used to ensure 'to' (phone number in E.164 format) and 'message' fields are present and valid. This prevents invalid requests from reaching the SNS publish stage and helps maintain data integrity.
The AWS SDK v3 for JavaScript, specifically the '@aws-sdk/client-sns' module, is used. Initialize the SNSClient and use the PublishCommand with the SNS topic ARN and the message payload (JSON stringified) to publish messages to the SNS topic.
The message payload sent to SNS should be a JSON object containing at least 'recipientPhoneNumber' and 'messageBody'. Additional metadata can be included as needed for downstream processing by the Lambda function or other consumer.
The Fastify app uses Pino logging by default. For development, use pino-pretty for readable logs. In production, set NODE_ENV=production for JSON formatted logs suitable for log aggregation systems. Log levels are controlled with LOG_LEVEL.
Common errors include incorrect AWS credentials (InvalidClientTokenId, SignatureDoesNotMatch), insufficient IAM permissions (AccessDenied), invalid topic ARN (TopicNotFound), and throttling from SNS if publishing rates are too high (ThrottlingException).
Containerization with Docker is recommended. Build a Docker image with your application code and deploy to platforms like AWS App Runner, AWS Fargate, or other container services. For serverless deployments (for infrequent usage), consider Fastify on AWS Lambda with '@fastify/aws-lambda'.
Remember, SNS only queues the messages. Verify the downstream service (e.g., AWS Lambda) is correctly subscribed to the SNS topic and functioning as expected. Check Lambda logs for errors related to WhatsApp Business API integration.