Tutorials

Fastify & AWS SNS: Implementing Message Delivery Status Callbacks

A guide on building a Fastify application to publish messages via AWS SNS and handle delivery status callbacks securely using HTTP/S.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 3, 2026 β€’ 12 min read

Developer Quick-Start: A guide on building a Fastify application to publish messages via AWS SNS and handle delivery status callbacks securely using HTTP/S. 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 Fastify application that not only publishes messages using AWS Simple Notification Service (SNS) but also reliably receives and processes delivery status notifications from SNS via HTTP/S callbacks.

We'll cover everything from initial project setup and AWS configuration to building the callback endpoint, handling SNS message types (including subscription confirmation and notifications), ensuring security through signature verification, and best practices for logging, error handling, and deployment.

Project Goal:

To create a robust Fastify application capable of:

  1. Sending messages (e.g., SMS, push notifications) through an AWS SNS topic or directly.
  2. Receiving delivery status updates (e.g., DELIVERED, FAILED) for those messages via an HTTP/S endpoint exposed by the Fastify application.
  3. Securely handling SNS subscription confirmation requests.
  4. Logging message statuses for tracking and debugging.

Problem Solved:

By default, when you publish a message to SNS, you get confirmation that SNS accepted the message, but not necessarily that the message reached the end recipient (like a specific phone number or mobile app). Implementing delivery status callbacks provides crucial visibility into the final delivery outcome, enabling applications to track message success rates, retry failed messages intelligently, or update internal records based on delivery status.

Technologies Used:

  • Fastify: A high-performance, low-overhead Node.js web framework. Chosen for its speed, extensibility, and developer-friendly API.
  • AWS SNS: A fully managed messaging service for both application-to-application (A2A) and application-to-person (A2P) communication. Essential for sending messages at scale.
  • AWS SDK for JavaScript v3: The official AWS SDK for interacting with AWS services like SNS from Node.js applications.
  • @aws-sdk/client-sns: Specific AWS SDK v3 package for SNS.
  • sns-validator: A utility library to validate the authenticity of incoming messages from AWS SNS, crucial for security.
  • dotenv: Module to load environment variables from a .env file into process.env.
  • Node.js: The JavaScript runtime environment.

System Architecture:

graph LR
    A[Client/Trigger] -- Sends Request --> B(Fastify App);
    B -- 1. Publish Message (with Delivery Status Attributes) --> C(AWS SNS Topic/Direct);
    C -- 2. Sends Message --> D(End Recipient e.g., SMS, Mobile App);
    C -- 3. Sends Delivery Status Notification (HTTP/S POST) --> B;
    B -- 4. Handles SNS Callback (Confirms Subscription / Processes Status) --> E{Callback Logic};
    E -- (Optional) Update Status --> F[(Database)];
    E -- Log Status --> G[/Logs/];

    style B fill:#f9f,stroke:#333,stroke-width:2px
    style C fill:#ff9,stroke:#333,stroke-width:2px

Prerequisites:

  • Node.js (LTS version recommended) and npm/yarn installed.
  • An AWS Account with permissions to manage SNS and IAM.
  • Basic familiarity with Fastify and JavaScript/TypeScript.
  • AWS Credentials (Access Key ID and Secret Access Key) configured for programmatic access.
  • A publicly accessible URL for your Fastify application (required for SNS HTTP/S callbacks). Tools like ngrok can be used during development.

1. Setting up the Project

Let's initialize our Node.js project and install the necessary dependencies.

1.1. Create Project Directory & Initialize

Open your terminal and run the following commands:

mkdir fastify-sns-callbacks
cd fastify-sns-callbacks
npm init -y

1.2. Install Dependencies

npm install fastify

npm install @aws-sdk/client-sns

npm install sns-validator

npm install dotenv

npm install -D pino-pretty

npm install node-fetch

1.3. Project Structure

Create the following basic file structure:

fastify-sns-callbacks/
β”œβ”€β”€ .env             # Environment variables (DO NOT COMMIT)
β”œβ”€β”€ .gitignore       # Git ignore file
β”œβ”€β”€ package.json
β”œβ”€β”€ config.js        # Application configuration
└── server.js        # Main Fastify application entry point

1.4. Configure .gitignore

Create a .gitignore file and add node_modules and .env to prevent committing sensitive information and dependencies:

# .gitignore
node_modules
.env
*.log

1.5. Environment Variables (.env)

Create a .env file to store sensitive configuration and credentials.

.env

# .env
# IMPORTANT: Fill in the placeholder values below with your actual AWS credentials and configuration.
# Do NOT commit this file to version control.

# --- PLACEHOLDERS - Replace with your actual values ---
# AWS Credentials & Configuration
AWS_ACCESS_KEY_ID=YOUR_AWS_ACCESS_KEY_ID          # Replace with your IAM User Access Key ID
AWS_SECRET_ACCESS_KEY=YOUR_AWS_SECRET_ACCESS_KEY  # Replace with your IAM User Secret Access Key
AWS_REGION=us-east-1                              # Replace with your desired AWS region (e.g., us-west-2)
SNS_TOPIC_ARN=YOUR_SNS_TOPIC_ARN                  # Replace with the ARN of the SNS Topic you create (Section 4.2)
SNS_CALLBACK_ENDPOINT=YOUR_PUBLICLY_ACCESSIBLE_URL/sns-callbacks # Replace with your app's public URL + path (e.g., https://myapp.com/sns-callbacks or ngrok URL)

# Application Configuration
PORT=3000
LOG_LEVEL=info # e.g., trace, debug, info, warn, error, fatal

Explanation:

  • Storing credentials and environment-specific settings in .env keeps them separate from the codebase, enhancing security and portability.
  • dotenv loads these variables into process.env when the application starts.
  • Crucially, the placeholder values (YOUR_...) must be replaced with your real configuration details obtained from AWS and your deployment environment.

1.6. Configuration File (config.js)

This file centralizes access to environment variables with potential defaults.

require('dotenv').config();

const config = {
  aws: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION || 'us-east-1',
    snsTopicArn: process.env.SNS_TOPIC_ARN,
    snsCallbackEndpoint: process.env.SNS_CALLBACK_ENDPOINT,
  },
  server: {
    port: parseInt(process.env.PORT, 10) || 3000,
    logLevel: process.env.LOG_LEVEL || 'info',
  },
};

if (!config.aws.accessKeyId || config.aws.accessKeyId === 'YOUR_AWS_ACCESS_KEY_ID' ||
    !config.aws.secretAccessKey || config.aws.secretAccessKey === 'YOUR_AWS_SECRET_ACCESS_KEY' ||
    !config.aws.snsTopicArn || config.aws.snsTopicArn === 'YOUR_SNS_TOPIC_ARN' ||
    !config.aws.snsCallbackEndpoint || config.aws.snsCallbackEndpoint === 'YOUR_PUBLICLY_ACCESSIBLE_URL/sns-callbacks') {
  console.error('FATAL ERROR: Missing or placeholder AWS configuration in environment variables (.env). Please replace placeholders like YOUR_AWS_ACCESS_KEY_ID with actual values.');
  process.exit(1);
}

module.exports = config;

Explanation:

  • We load dotenv first.
  • We structure the configuration logically.
  • We include validation to ensure critical AWS variables are set and are not still the default placeholder values, preventing runtime errors later.

2. Implementing Core Functionality: Sending & Receiving

Now, let's build the core Fastify server and implement the logic for sending messages and handling the incoming SNS callbacks.

2.1. Basic Fastify Server (server.js)

const Fastify = require('fastify');
const config = require('./config');
const { SnsClient, PublishCommand } = require('@aws-sdk/client-sns');
const MessageValidator = require('sns-validator');
const { promisify } = require('util');

const isProduction = process.env.NODE_ENV === 'production';

const fastify = Fastify({
  logger: {
    level: config.server.logLevel,

    transport: !isProduction ? {
      target: 'pino-pretty',
      options: {
        translateTime: 'HH:MM:ss Z',
        ignore: 'pid,hostname',
      },
    } : undefined,
  },
});

const snsClient = new SnsClient({
  region: config.aws.region,
  credentials: {
    accessKeyId: config.aws.accessKeyId,
    secretAccessKey: config.aws.secretAccessKey,
  },
});

const validator = new MessageValidator();
const validateSnsMessage = promisify(validator.validate).bind(validator);

const start = async () => {
  try {
    await fastify.listen({ port: config.server.port, host: '0.0.0.0' });
    fastify.log.info(`Server listening on port ${fastify.server.address().port}`);
    fastify.log.info(`SNS Callback Endpoint configured at: ${config.aws.snsCallbackEndpoint}`);
    fastify.log.info(`Ensure this endpoint is publicly accessible and matches the SNS Subscription endpoint.`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

Explanation:

  • We initialize Fastify with logging configured based on config.js. pino-pretty is conditionally used for better readability during development. Production uses standard JSON logging.
  • We create an instance of the AWS SDK v3 SnsClient, providing the region and credentials from our configuration.
  • We instantiate the sns-validator. Since its validate method uses callbacks, we promisify it for easier use with async/await.
  • The start function launches the server, listening on the configured port and 0.0.0.0 (important for containerized environments or VMs). Crucially, it logs the expected callback endpoint URL for verification.

2.2. Sending Messages with Delivery Status

To receive delivery status notifications, you must configure SNS to send them when publishing the message. This is done via MessageAttributes in the PublishCommand.

Add the following route to server.js (before the start() call):

fastify.post('/send-sms', async (request, reply) => {

  const { phoneNumber, messageBody } = request.body || {};

  if (!phoneNumber || !messageBody) {
    reply.code(400);
    return { error: 'Missing required fields: phoneNumber, messageBody' };
  }


  if (!/^\+[1-9]\d{1,14}$/.test(phoneNumber)) {
     reply.code(400);
     return { error: 'Invalid phoneNumber format. Use E.164 (e.g., +12125551234)' };
  }

  try {
    fastify.log.info(`Attempting to send SMS to ${phoneNumber}`);

    const command = new PublishCommand({
      PhoneNumber: phoneNumber,
      Message: messageBody,
      MessageAttributes: {

        'AWS.SNS.SMS.SMSType': {
          DataType: 'String',
          StringValue: 'Transactional',
        },















        'AWS.SNS.SMS.SenderID': {
          DataType: 'String',
          StringValue: 'MyApp',
        },





      },
    });

    const response = await snsClient.send(command);
    fastify.log.info({ msg: `SMS published successfully`, messageId: response.MessageId });




    return { success: true, messageId: response.MessageId };

  } catch (error) {
    fastify.log.error({ msg: 'Error publishing SMS to SNS', error: error.message, stack: error.stack });
    reply.code(500);
    return { success: false, error: 'Failed to send SMS', details: error.message };
  }
});

Explanation:

  • We define a /send-sms POST route.
  • Basic validation checks for phoneNumber and messageBody. A simple E.164 format check is included. (Schema validation is added in Section 3).
  • Crucially: Inside the PublishCommand parameters, we set MessageAttributes:
  • AWS.SNS.SMS.SMSType: Setting this to Transactional (or Promotional) tells SNS you want delivery status logging enabled for SMS. Transactional is optimized for reliability, Promotional for cost. This attribute is required for SMS delivery status.
  • AWS.SNS.SMS.SenderID: An optional custom ID displayed on the recipient's device (subject to carrier support and registration requirements).
  • Other optional attributes related to feedback roles and success rates can also be set here if you prefer per-message configuration over topic-level defaults.
  • We use snsClient.send(command) to publish the message.
  • We log the success, including the MessageId returned by SNS, which is essential for correlating status updates later.
  • Robust error handling logs failures and returns a 500 status.

Alternative Approach (Publishing to Topic):

If you prefer publishing to a Topic ARN (config.aws.snsTopicArn) instead of directly to a phone number, the structure is similar, but you use TopicArn instead of PhoneNumber. Ensure the Topic itself has delivery status logging configured (see Section 4.3) OR that the MessageAttributes needed for the specific subscriber type (e.g., SMS, Application) are included in the publish command.

const command = new PublishCommand({
  TopicArn: config.aws.snsTopicArn,
  Message: JSON.stringify({ default: messageBody, sms: messageBody }),
  MessageStructure: 'json',
  MessageAttributes: {


    'AWS.SNS.SMS.SMSType': {
      DataType: 'String',
      StringValue: 'Transactional',
    },

  },
});

2.3. Receiving SNS Callbacks

This is the endpoint SNS will call with subscription confirmations and delivery status notifications.

Add the following route to server.js (before the start() call):

const nodeFetch = import('node-fetch').then(mod => mod.default);

fastify.post('/sns-callbacks', {

  config: {
    rawBody: true
  }


}, async (request, reply) => {
  let message;
  const contentType = request.headers['content-type'] || '';
  const xSnsMessageType = request.headers['x-amz-sns-message-type'];

  fastify.log.trace({ msg: 'Received potential SNS callback', headers: request.headers });


  if (!request.rawBody) {
      fastify.log.error('Raw request body not available. Ensure `rawBody: true` is set in route config.');
      reply.code(500);
      return { error: 'Server configuration error: Raw body missing.' };
  }


  try {


    const rawBodyString = request.rawBody.toString('utf8');
    message = JSON.parse(rawBodyString);

    fastify.log.trace({ msg: 'Successfully parsed SNS message body', type: message.Type });
  } catch (err) {
    fastify.log.error({ msg: 'Failed to parse incoming SNS message JSON', error: err.message, body: request.rawBody?.toString('utf8') });
    reply.code(400);
    return { error: 'Invalid JSON format' };
  }


  try {

    await validateSnsMessage(message);
    fastify.log.debug({ msg: 'SNS message signature validated successfully', type: message.Type, messageId: message.MessageId });


    switch (message.Type) {
      case 'SubscriptionConfirmation':



        fastify.log.info(`Received SubscriptionConfirmation for Topic ${message.TopicArn}. Attempting to confirm...`);
        if (!message.SubscribeURL || !message.SubscribeURL.startsWith('https://sns.')) {
             fastify.log.error('Invalid or missing SubscribeURL in SubscriptionConfirmation');
             reply.code(400).send({ error: 'Invalid SubscriptionConfirmation message' });
             break;
        }
        try {
          const fetch = await nodeFetch;
          const confirmationResponse = await fetch(message.SubscribeURL);
          if (!confirmationResponse.ok) {

              const responseBody = await confirmationResponse.text();
              throw new Error(`Confirmation request failed with status: ${confirmationResponse.status}, Body: ${responseBody}`);
          }
          fastify.log.info(`Successfully confirmed subscription to Topic ${message.TopicArn}`);

          reply.code(200).send({ success: true, message: 'Subscription Confirmed via HTTP GET' });
        } catch (confirmError) {
          fastify.log.error({ msg: 'Failed to auto-confirm SNS subscription via SubscribeURL', url: message.SubscribeURL, error: confirmError.message });


          reply.code(200).send({ success: false, message: 'Acknowledged SubscriptionConfirmation, but failed to automatically confirm via SubscribeURL. Check logs.' });
        }
        break;

      case 'Notification':

        fastify.log.info({ msg: 'Received SNS Notification', messageId: message.MessageId });
        try {

          const notificationData = JSON.parse(message.Message);




          const snsOriginalMessageId = notificationData.notification?.messageId;
          const deliveryStatus = notificationData.status;

          fastify.log.info({
              msg: 'Processing Delivery Status Notification',
              snsCallbackMessageId: message.MessageId,
              snsOriginalMessageId: snsOriginalMessageId,
              deliveryStatus: deliveryStatus,
              timestamp: notificationData.notification?.timestamp,
              providerResponse: notificationData.providerResponse,
              priceInUSD: notificationData.priceInUSD,

          });






          reply.code(200).send({ success: true, message: 'Notification received and acknowledged' });
        } catch (parseError) {
          fastify.log.error({ msg: 'Failed to parse nested JSON in SNS Notification message', error: parseError.message, rawMessageContent: message.Message });

          reply.code(400).send({ error: 'Invalid Notification message content format' });
        }
        break;

      case 'UnsubscribeConfirmation':

        fastify.log.warn({ msg: 'Received UnsubscribeConfirmation', topicArn: message.TopicArn, messageId: message.MessageId });

        reply.code(200).send({ success: true, message: 'Unsubscribe confirmation acknowledged' });
        break;

      default:
        fastify.log.warn({ msg: 'Received unknown SNS message type', type: message.Type, messageId: message.MessageId });
        reply.code(400).send({ error: `Unsupported SNS message type: ${message.Type}` });
    }

  } catch (validationError) {

    fastify.log.error({ msg: 'SNS message signature validation failed!', error: validationError.message, headers: request.headers });

    reply.code(403);
    return { error: 'Invalid SNS message signature' };
  }
});

Explanation:

  1. Endpoint & Raw Body: Defines /sns-callbacks POST route. Configures rawBody: true to access the raw request body needed for signature verification. Includes a check to ensure rawBody is available.
  2. Parsing: Parses the rawBody string into a JavaScript object (message). Handles potential JSON parsing errors.
  3. Validation: Uses the promisified validateSnsMessage(message) to check the signature. This is critical for security. Logs success or failure. Returns 403 Forbidden immediately on validation failure.
  4. Type Handling (switch statement): Uses the Type field from the parsed JSON body (message.Type) to determine the action:
  • SubscriptionConfirmation: Logs receipt, validates SubscribeURL, then makes an HTTP GET request to it using node-fetch (dynamically imported for ESM compatibility). Logs success or failure of the confirmation attempt. Returns 200 OK to SNS to acknowledge the receipt of the confirmation message, regardless of whether the subsequent GET succeeded, to prevent SNS retries of the confirmation message itself.
  • Notification: Logs receipt. Parses the nested JSON string within message.Message to get the actual status details (notificationData). Logs key fields like status and the original messageId. This is the primary integration point for your application logic (e.g., database updates). Returns 200 OK to SNS.
  • UnsubscribeConfirmation: Logs the event. Returns 200 OK.
  • default: Handles unexpected types. Returns 400 Bad Request.
  1. Response Codes: Returns 200 OK promptly after successfully receiving and acknowledging a valid message (Notification, SubscriptionConfirmation, UnsubscribeConfirmation). Internal processing errors (like database failures) should be logged and handled asynchronously (e.g., via a queue) rather than causing the endpoint to return 5xx to SNS, which would trigger SNS retries. Signature validation failures return 403. Parsing errors or unknown types return 400.

3. Building a Complete API Layer (Example)

Let's refine the /send-sms endpoint with validation and authentication.

const authenticate = async (request, reply) => {
  const apiKey = request.headers['x-api-key'];


  const expectedApiKey = process.env.INTERNAL_API_KEY || 'YOUR_SECRET_API_KEY_PLACEHOLDER';

  if (!apiKey || apiKey !== expectedApiKey) {
    fastify.log.warn('Authentication failed: Invalid or missing API key');
    reply.code(401).send({ error: 'Unauthorized' });

    return Promise.reject(new Error('Unauthorized'));
  }
  fastify.log.trace('Authentication successful');
};

fastify.post('/send-sms', {

  preHandler: [authenticate],


  schema: {
    body: {
      type: 'object',
      required: ['phoneNumber', 'messageBody'],
      properties: {
        phoneNumber: {
          type: 'string',
          description: 'Recipient phone number in E.164 format (e.g., +12125551234)',

          pattern: '^\\+[1-9]\\d{1,14}$'
        },
        messageBody: {
          type: 'string',
          description: 'The text message content',
          minLength: 1,
          maxLength: 1600
        }
      },
      additionalProperties: false
    },
    response: {
      200: {
        description: 'Successful message publication to SNS',
        type: 'object',
        properties: {
          success: { type: 'boolean', const: true },
          messageId: { type: 'string', description: 'The unique ID assigned by SNS to the message' }
        }
      },
      '4xx': {
         description: 'Client-side error (validation, authentication)',
         type: 'object',
         properties: {
            statusCode: { type: 'integer' },
            code: { type: 'string' },
            error: { type: 'string' },
            message: { type: 'string' }
         }
      },
       '5xx': {
         description: 'Server-side error during SNS publish attempt',
         type: 'object',
         properties: {
            success: { type: 'boolean', const: false },
            error: { type: 'string' },
            details: { type: 'string', nullable: true }
         }
      }
    }
  }
}, async (request, reply) => {

  const { phoneNumber, messageBody } = request.body;

  try {
    fastify.log.info(`Attempting to send validated SMS to ${phoneNumber}`);

    const command = new PublishCommand({
      PhoneNumber: phoneNumber,
      Message: messageBody,
      MessageAttributes: {
        'AWS.SNS.SMS.SMSType': { DataType: 'String', StringValue: 'Transactional' },
        'AWS.SNS.SMS.SenderID': { DataType: 'String', StringValue: 'MyApp' },

      },
    });

    const response = await snsClient.send(command);
    fastify.log.info({ msg: `SMS published successfully to SNS`, messageId: response.MessageId });

    return { success: true, messageId: response.MessageId };

  } catch (error) {
    fastify.log.error({ msg: 'Error publishing SMS to SNS after validation', phoneNumber: phoneNumber, error: error.message, stack: error.stack });
    reply.code(500);

    return { success: false, error: 'Failed to send SMS via SNS', details: error.message };
  }
});

Explanation of Refinements:

  • Authentication Hook (preHandler): We add a preHandler hook that calls our example authenticate function. This hook is a basic placeholder. Replace it with a robust authentication mechanism (@fastify/jwt, @fastify/auth, OAuth, etc.) and use secure key comparison. Load secrets from environment variables.
  • Schema Validation: We define a schema for the body and response. Fastify automatically validates incoming request bodies against the body schema. If validation fails, it sends a 400 error response automatically. This replaces the manual validation checks. The response schema helps document and potentially validate outgoing responses.
  • Regex Pattern: The E.164 regex pattern ^\\\\+[1-9]\\\\d{1,14}$ is correctly defined as a string within the JSON schema.
  • Error Handling: The catch block now focuses on errors during the snsClient.send call, as input validation is handled by Fastify.

Testing with cURL:

export FASTIFY_URL="http://localhost:3000"
export API_KEY="YOUR_SECRET_API_KEY_PLACEHOLDER"
export PHONE_NUMBER="+12125551234"

curl -X POST "${FASTIFY_URL}/send-sms" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: ${API_KEY}" \
  -d '{
    "phoneNumber": "'"${PHONE_NUMBER}"'",
    "messageBody": "Hello from Fastify SNS Test! (Callback Test)"
  }'

curl -X POST "${FASTIFY_URL}/send-sms" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: WRONG_KEY" \
  -d '{"phoneNumber": "'"${PHONE_NUMBER}"'", "messageBody": "Test"}'

curl -X POST "${FASTIFY_URL}/send-sms" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: ${API_KEY}" \
  -d '{"phoneNumber": "12345", "messageBody": "Test"}'

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