Developer Quick-Start: A guide to creating an SMS scheduling application using Fastify, AWS SNS, EventBridge, and the Vonage API for reliable message delivery. 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 details how to build a robust SMS scheduling application using Node.js with the Fastify framework, AWS Simple Notification Service (SNS), AWS EventBridge for scheduling, and the Vonage Communications API for sending SMS messages.
You will learn how to create an API endpoint that accepts SMS scheduling requests, leverages AWS services for reliable time-based triggering, and uses Vonage to deliver the messages. This solves the common need for sending timely notifications, reminders, or alerts without maintaining complex internal cron jobs or schedulers.
Project Overview and Goals
Goal: Create a Fastify application with two main API endpoints:
- /schedule: Accepts POST requests to schedule an SMS message for a future time.
- /webhook/sns: Receives notifications from AWS SNS (triggered by EventBridge) and sends the SMS via Vonage.
Problem Solved: Provides a scalable and reliable mechanism for scheduling SMS messages without managing stateful timers or cron jobs within the application itself. Leverages managed cloud services for scheduling and notifications.
Technologies Used:
- Node.js: JavaScript runtime environment.
- Fastify: High-performance Node.js web framework.
- AWS SDK for JavaScript v3: To interact with AWS services (EventBridge, SNS).
- AWS EventBridge (Scheduler): Managed service to schedule events that trigger AWS resources.
- AWS SNS (Simple Notification Service): Managed pub/sub messaging service used to decouple the scheduler from the SMS sending logic.
- Vonage SMS API: Used via @vonage/server-sdk to send SMS messages.
- dotenv: To manage environment variables locally.
- pino-pretty: (Development Only) To format logs for readability.
System Architecture:
The system follows this flow: A user sends a request to the Fastify /schedule endpoint. Fastify
creates a one-time rule in AWS EventBridge. At the scheduled time, EventBridge triggers an AWS SNS topic. SNS
sends a notification message to the Fastify /webhook/sns endpoint. Fastify receives the
notification, extracts the SMS details, and uses the Vonage API to send the SMS to the end user's phone
number.
Prerequisites:
- Node.js: Version 18.x or later recommended.
- npm or yarn: Package manager for Node.js.
- AWS Account: With access to create IAM users/roles, EventBridge rules, and SNS topics. AWS Free Tier is sufficient for initial testing.
- AWS Credentials: An IAM user with programmatic access (Access Key ID and Secret Access Key) configured locally (e.g., via ~/.aws/credentials or environment variables). See IAM Permissions section below.
- Vonage Account: Sign up for a Vonage API account. You'll need your API Key, API Secret, and a purchased Vonage phone number capable of sending SMS.
- Publicly Accessible URL: Required for the Fastify server to receive SNS webhook notifications. Services like ngrok are excellent for local development and testing.
1. Setting up the Project
Let's initialize the project, install dependencies, and set up the basic structure.
1. Create Project Directory:
mkdir fastify-sms-scheduler
cd fastify-sms-scheduler
2. Initialize Node.js Project:
npm init -y
3. Install Dependencies:
Install production dependencies:
npm install fastify @fastify/env @aws-sdk/client-eventbridge @aws-sdk/client-sns @vonage/server-sdk dotenv
Install development dependencies:
npm install --save-dev pino-pretty
- fastify: The web framework.
- @fastify/env: For loading and validating environment variables.
- @aws-sdk/client-eventbridge: AWS SDK v3 client for EventBridge.
- @aws-sdk/client-sns: AWS SDK v3 client for SNS.
- @vonage/server-sdk: Vonage Node.js SDK.
- dotenv: Loads environment variables from a .env file for local development.
- pino-pretty: (Dev Dependency) Makes Fastify's logs more readable during development.
4. Configure package.json Scripts:
Add the following scripts to your package.json for easier development:
{
""scripts"": {
""start"": ""node server.js"",
""dev"": ""node server.js | npx pino-pretty""
}
}
- npm start: Runs the server normally (suitable for production).
- npm run dev: Runs the server with logs piped through pino-pretty for better readability during development. Requires pino-pretty to be installed (as a dev dependency).
5. Create Project Structure:
fastify-sms-scheduler/
βββ node_modules/
βββ routes/
β βββ schedule.js # Handles /schedule endpoint
β βββ webhook.js # Handles /webhook/sns endpoint
βββ .env # Environment variables (DO NOT COMMIT)
βββ .gitignore
βββ package.json
βββ package-lock.json
βββ server.js # Main Fastify application setup
6. Create .gitignore:
Add node_modules and .env to your .gitignore file to prevent
committing them.
# .gitignore
node_modules
.env
7. Setup Environment Variables (.env):
Create a .env file in the project root. Remember to replace placeholders with your
actual credentials and ARNs.
ini
AWS_REGION=us-east-1
SNS_TOPIC_ARN=arn:aws:sns:us-east-1:123456789012:MySmsSchedulerTopic
EVENTBRIDGE_ROLE_ARN=arn:aws:iam::123456789012:role/MyEventBridgeSnsRole
VONAGE_API_KEY=YOUR_VONAGE_API_KEY
VONAGE_API_SECRET=YOUR_VONAGE_API_SECRET
VONAGE_FROM_NUMBER=+12015550123
HOST=0.0.0.0
PORT=3000
LOG_LEVEL=info
PUBLIC_WEBHOOK_URL=https://your-publicly-accessible-url.com
Explanation of Environment Variables:
- AWS\_REGION: The AWS region where your SNS topic and EventBridge rules will reside.
- SNS\_TOPIC\_ARN: The unique identifier for the SNS topic that EventBridge will publish to.
- EVENTBRIDGE\_ROLE\_ARN: The ARN of the IAM role that grants EventBridge permission to publish messages to your SNS topic.
- VONAGE\_API\_KEY, VONAGE\_API\_SECRET: Your Vonage API credentials found on the Vonage API Dashboard.
- VONAGE\_FROM\_NUMBER: The Vonage virtual number you purchased, used as the sender ID for SMS messages. Ensure it's in E.164 format (e.g., +14155552671). Note: For US numbers, ensure you comply with 10DLC regulations.
- HOST, PORT: Network configuration for the Fastify server.
- LOG\_LEVEL: Controls the verbosity of logs (info, debug, warn, error).
- PUBLIC\_WEBHOOK\_URL: The base URL where your /webhook/sns endpoint is publicly accessible. Crucial for SNS to send notifications.
8. Basic Fastify Server Setup (server.js):
This file initializes Fastify, loads environment variables, registers routes, and starts the server.
'use strict';
const path = require('path');
const Fastify = require('fastify');
const fastifyEnv = require('@fastify/env');
const scheduleRoutes = require('./routes/schedule');
const webhookRoutes = require('./routes/webhook');
const envSchema = {
type: 'object',
required: [
'AWS_REGION',
'SNS_TOPIC_ARN',
'EVENTBRIDGE_ROLE_ARN',
'VONAGE_API_KEY',
'VONAGE_API_SECRET',
'VONAGE_FROM_NUMBER',
'PUBLIC_WEBHOOK_URL',
],
properties: {
AWS_REGION: { type: 'string' },
SNS_TOPIC_ARN: { type: 'string', pattern: '^arn:aws:sns:[^:]+:[^:]+:[^:]+' },
EVENTBRIDGE_ROLE_ARN: { type: 'string', pattern: '^arn:aws:iam::[^:]+:role/.+' },
VONAGE_API_KEY: { type: 'string' },
VONAGE_API_SECRET: { type: 'string' },
VONAGE_FROM_NUMBER: { type: 'string', pattern: '^\\+[1-9]\\d{1,14}' },
HOST: { type: 'string', default: '0.0.0.0' },
PORT: { type: 'number', default: 3000 },
LOG_LEVEL: { type: 'string', default: 'info' },
PUBLIC_WEBHOOK_URL: { type: 'string', format: 'uri' },
},
};
const envOptions = {
confKey: 'config',
schema: envSchema,
dotenv: true,
};
const fastify = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production'
? { target: 'pino-pretty' }
: undefined,
},
});
fastify
.register(fastifyEnv, envOptions)
.after(err => {
if (err) {
fastify.log.error('Environment variable validation failed:', err);
process.exit(1);
}
fastify.log.info('Environment variables loaded successfully.');
try {
const { EventBridgeClient } = require('@aws-sdk/client-eventbridge');
const { SNSClient } = require('@aws-sdk/client-sns');
fastify.decorate('eventBridge', new EventBridgeClient({ region: fastify.config.AWS_REGION }));
fastify.decorate('snsClient', new SNSClient({ region: fastify.config.AWS_REGION }));
fastify.log.info('AWS SDK clients initialized.');
const { Vonage } = require('@vonage/server-sdk');
const vonage = new Vonage({
apiKey: fastify.config.VONAGE_API_KEY,
apiSecret: fastify.config.VONAGE_API_SECRET,
});
fastify.decorate('vonage', vonage);
fastify.log.info('Vonage SDK client initialized.');
} catch (sdkError) {
fastify.log.error('Failed to initialize SDK clients:', sdkError);
process.exit(1);
}
fastify.register(scheduleRoutes, { prefix: '/schedule' });
fastify.register(webhookRoutes, { prefix: '/webhook' });
fastify.log.info('Routes registered.');
});
fastify.get('/health', async (request, reply) => {
return { status: 'ok', timestamp: new Date().toISOString() };
});
const start = async () => {
try {
await fastify.ready();
await fastify.listen({ port: fastify.config.PORT, host: fastify.config.HOST });
fastify.log.info(`Server listening on port ${fastify.server.address().port}`);
fastify.log.info(`Webhook base URL configured as: ${fastify.config.PUBLIC_WEBHOOK_URL}`);
fastify.log.warn('Ensure the /webhook/sns endpoint is publicly accessible and matches the PUBLIC_WEBHOOK_URL for SNS notifications.');
} catch (err) {
fastify.log.error('Error starting server:', err);
process.exit(1);
}
};
start();
This sets up the core server, loads configuration securely, initializes necessary SDK clients, and registers route handlers (which we'll create next).
2. AWS Setup (SNS, EventBridge, IAM)
Before writing the API logic, configure the necessary AWS resources. You can do this via the AWS Management Console or AWS CLI.
1. Create an SNS Topic:
- Navigate to the SNS service in the AWS Console.
- Go to ""Topics"" and click ""Create topic"".
- Choose ""Standard"" type.
- Give it a name (e.g., MySmsSchedulerTopic).
- Keep default settings for Access policy, Encryption, etc., for now.
- Click ""Create topic"".
- Important: Copy the Topic ARN and update the SNS\_TOPIC\_ARN value in your .env file.
2. Create an IAM Role for EventBridge:
EventBridge needs permission to publish messages to your SNS topic.
- Navigate to the IAM service in the AWS Console.
- Go to ""Roles"" and click ""Create role"".
- For ""Trusted entity type"", select ""AWS service"".
- For ""Use case"", find and select ""EventBridge (CloudWatch Events)"". (EventBridge uses the CloudWatch Events service role). Click ""Next"".
- On the ""Add permissions"" page, click ""Create policy"". This opens a new tab.
- In the policy editor, switch to the ""JSON"" tab.
- Paste the following policy, replacing <YOUR\_SNS\_TOPIC\_ARN> with the ARN you copied earlier:
{
""Version"": ""2012-10-17"",
""Statement"": [
{
""Effect"": ""Allow"",
""Action"": ""sns:Publish"",
""Resource"": ""<YOUR_SNS_TOPIC_ARN>""
}
]
}
- Click ""Next: Tags"", then ""Next: Review"".
- Give the policy a name (e.g., EventBridgePublishToMySmsSchedulerTopicPolicy).
- Click ""Create policy"".
- Switch back to the ""Create role"" tab. Refresh the policies list and search for the policy you just created. Select it.
- Click ""Next"".
- Give the role a name (e.g., MyEventBridgeSnsRole).
- Review and click ""Create role"".
- Important: Find the role you just created, click on it, and copy the Role ARN. Update the EVENTBRIDGE\_ROLE\_ARN value in your .env file.
3. Configure IAM Permissions for Your Fastify Application:
The AWS credentials used by your Fastify application (configured via environment variables or
~/.aws/credentials) need permissions to create EventBridge rules and targets.
- Create an IAM policy (or add to an existing one used by your application's IAM user/role) with the following permissions. Replace <YOUR\_EVENTBRIDGE\_ROLE\_ARN> with the Role ARN from the previous step.
{
""Version"": ""2012-10-17"",
""Statement"": [
{
""Sid"": ""AllowEventBridgeManageRules"",
""Effect"": ""Allow"",
""Action"": [
""events:PutRule"",
""events:PutTargets"",
""events:DeleteRule"",
""events:RemoveTargets""
],
""Resource"": ""*""
},
{
""Sid"": ""AllowPassRoleToEventBridge"",
""Effect"": ""Allow"",
""Action"": ""iam:PassRole"",
""Resource"": ""<YOUR_EVENTBRIDGE_ROLE_ARN>"",
""Condition"": {
""StringEquals"": {
""iam:PassedToService"": ""events.amazonaws.com""
}
}
}
]
}
- Attach this policy to the IAM user or role whose credentials your Fastify application uses. The iam:PassRole permission is crucial for allowing EventBridge to assume the role you created.
- Security Best Practice: The Resource: ""\*"" for AllowEventBridgeManageRules is permissive. In production, it's highly recommended to restrict this to ARNs matching your rule naming convention (e.g., arn:aws:events:us-east-1:123456789012:rule/sms-schedule-\*) to prevent the application from managing unrelated EventBridge rules.
4. Create SNS Subscription (Manual Step Later):
We will create the subscription after the webhook endpoint is running and publicly accessible. SNS needs to send a confirmation request to the endpoint URL.
3. Implementing the Scheduling API (/schedule)
This endpoint receives the scheduling request and creates the one-time EventBridge rule.
Create routes/schedule.js:
'use strict';
const { PutRuleCommand, PutTargetsCommand } = require('@aws-sdk/client-eventbridge');
const { randomUUID } = require('crypto');
const scheduleBodySchema = {
type: 'object',
required: ['phoneNumber', 'message', 'sendAt'],
properties: {
phoneNumber: {
type: 'string',
description: 'Recipient phone number in E.164 format (e.g., +14155552671)',
pattern: '^\\+[1-9]\\d{1,14}',
},
message: {
type: 'string',
description: 'The SMS message content',
minLength: 1,
maxLength: 1600,
},
sendAt: {
type: 'string',
description: 'ISO 8601 timestamp for when to send the message (e.g., 2025-12-31T23:59:00Z). Must be in the future.',
format: 'date-time',
},
},
};
async function scheduleRoutes(fastify, options) {
fastify.post('/', { schema: { body: scheduleBodySchema } }, async (request, reply) => {
const { phoneNumber, message, sendAt } = request.body;
const { eventBridge, config, log } = fastify;
const scheduleTimestamp = new Date(sendAt);
const now = new Date();
if (scheduleTimestamp <= now) {
log.warn({ body: request.body }, 'Scheduled time is not in the future');
return reply.code(400).send({ error: 'Scheduled time must be in the future.' });
}
const ruleName = `sms-schedule-${randomUUID()}`;
const scheduleExpression = `at(${scheduleTimestamp.toISOString().substring(0, 19)})`;
const snsInputPayload = JSON.stringify({
phoneNumber: phoneNumber,
message: message,
scheduledRuleName: ruleName,
originalSendAt: sendAt,
});
log.info({ ruleName, scheduleExpression, phoneNumber }, 'Attempting to create EventBridge rule');
try {
const putRuleParams = {
Name: ruleName,
ScheduleExpression: scheduleExpression,
State: 'ENABLED',
Description: `One-time schedule to send SMS to ${phoneNumber}`,
};
const ruleCommand = new PutRuleCommand(putRuleParams);
const ruleResponse = await eventBridge.send(ruleCommand);
log.info({ ruleName, ruleArn: ruleResponse.RuleArn }, 'EventBridge rule created successfully');
const putTargetsParams = {
Rule: ruleName,
Targets: [
{
Id: `target-${ruleName}`,
Arn: config.SNS_TOPIC_ARN,
Input: snsInputPayload,
RoleArn: config.EVENTBRIDGE_ROLE_ARN,
},
],
};
const targetCommand = new PutTargetsCommand(putTargetsParams);
await eventBridge.send(targetCommand);
log.info({ ruleName, targetId: `target-${ruleName}` }, 'EventBridge target set successfully');
reply.code(202).send({
message: 'SMS scheduled successfully.',
ruleName: ruleName,
scheduledTime: scheduleTimestamp.toISOString(),
});
} catch (error) {
log.error({ err: error, ruleName }, 'Error creating EventBridge rule or target');
reply.code(500).send({ error: 'Failed to schedule SMS due to an internal error.' });
}
});
}
module.exports = scheduleRoutes;
Explanation:
- Schema Validation: Uses Fastify's built-in schema validation to ensure phoneNumber, message, and sendAt are provided and correctly formatted (E.164 pattern, ISO 8601 date).
- Time Validation: Checks if the requested sendAt time is actually in the future.
- Rule Naming: Generates a unique name for the EventBridge rule using randomUUID.
- Schedule Expression: Creates an at() schedule expression required by EventBridge for one-time events. Crucially, this uses UTC time (toISOString).
- SNS Payload: Defines the JSON payload containing the phone number and message that EventBridge will send to SNS when the schedule triggers. Includes metadata like ruleName.
PutRuleCommand: Creates the EventBridge rule with the specific schedule time. State: 'ENABLED' ensures it's active. One-time at() schedules are auto-deleted by EventBridge after execution.PutTargetsCommand: Links the created rule to the SNS Topic ARN specified in the environment variables. It passes the snsInputPayload and specifies the EVENTBRIDGE\_ROLE\_ARN needed for permissions.- Response: Returns a 202 Accepted status, indicating the request was successful and the SMS is scheduled for future delivery.
- Error Handling: Includes a try-catch block to log errors during AWS SDK calls and return a 500 status.
4. Implementing the SNS Webhook Handler (/webhook/sns)
This endpoint is crucial. It needs to handle two types of incoming POST requests from AWS SNS:
- Subscription Confirmation: When you first subscribe this endpoint to the SNS topic.
- Notification: When EventBridge triggers the SNS topic at the scheduled time, containing the SMS details.
Create routes/webhook.js:
'use strict';
const https = require('https');
const { Buffer } = require('buffer');
function httpsGet(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve({ statusCode: res.statusCode, data: data });
} else {
reject(new Error(`HTTPS GET failed for ${url} with status ${res.statusCode}`));
}
});
}).on('error', (err) => {
reject(err);
});
});
}
async function webhookRoutes(fastify, options) {
const { vonage, config, log, snsClient } = fastify;
fastify.post('/sns', {
config: {
rawBody: true
}
}, async (request, reply) => {
const messageType = request.headers['x-amz-sns-message-type'];
let snsMessage;
log.debug({ headers: request.headers, rawBody: request.rawBody?.toString() }, 'Received SNS webhook request');
try {
if (!request.rawBody) {
throw new Error('Request body is missing');
}
snsMessage = JSON.parse(request.rawBody.toString());
log.info({ messageType, messageId: snsMessage.MessageId || 'N/A' }, 'Parsed SNS message');
} catch (parseError) {
log.error({ err: parseError, rawBody: request.rawBody?.toString() }, 'Failed to parse SNS message JSON');
return reply.code(400).send({ error: 'Invalid SNS message format' });
}
if (messageType === 'SubscriptionConfirmation') {
log.info({ subscribeURL: snsMessage.SubscribeURL }, 'Received SNS Subscription Confirmation request');
try {
const subscribeUrl = new URL(snsMessage.SubscribeURL);
if (subscribeUrl.protocol !== 'https:' || !subscribeUrl.hostname.endsWith('.amazonaws.com')) {
log.error({ subscribeURL: snsMessage.SubscribeURL }, 'Invalid SubscribeURL domain or protocol');
return reply.code(400).send({ error: 'Invalid subscription URL' });
}
log.info(`Attempting to confirm subscription by visiting: ${snsMessage.SubscribeURL}`);
const confirmationResponse = await httpsGet(snsMessage.SubscribeURL);
log.info({ url: snsMessage.SubscribeURL, statusCode: confirmationResponse.statusCode }, 'Successfully confirmed SNS subscription');
return reply.code(200).send({ message: 'Subscription confirmed' });
} catch (confirmError) {
log.error({ err: confirmError, subscribeURL: snsMessage.SubscribeURL }, 'Failed to confirm SNS subscription via SubscribeURL');
return reply.code(500).send({ error: 'Failed to confirm subscription' });
}
}
else if (messageType === 'Notification') {
log.info({ messageId: snsMessage.MessageId, subject: snsMessage.Subject }, 'Received SNS Notification');
try {
const payload = JSON.parse(snsMessage.Message);
const { phoneNumber, message, scheduledRuleName } = payload;
if (!phoneNumber || !message) {
log.error({ payload, messageId: snsMessage.MessageId }, 'Missing phoneNumber or message in SNS notification payload');
return reply.code(400).send({ error: 'Invalid notification payload content' });
}
log.info({ phoneNumber, scheduledRuleName, messageId: snsMessage.MessageId }, 'Processing scheduled SMS via Vonage');
await vonage.sms.send({
to: phoneNumber,
from: config.VONAGE_FROM_NUMBER,
text: message,
});
log.info({ phoneNumber, scheduledRuleName, messageId: snsMessage.MessageId }, 'SMS sent successfully via Vonage.');
return reply.code(200).send({ message: 'Notification processed and SMS sent' });
} catch (processError) {
log.error({ err: processError, messageId: snsMessage.MessageId }, 'Error processing SNS notification or sending SMS');
return reply.code(500).send({ error: 'Failed to process notification' });
}
}
else {
log.warn({ messageType, messageId: snsMessage.MessageId || 'N/A' }, 'Received unknown SNS message type');
return reply.code(400).send({ error: `Unsupported message type: ${messageType}` });
}
});
}
module.exports = webhookRoutes;
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 β