Tutorials

Build Inbound Two-Way SMS with Sinch, Node.js & Fastify: Complete Guide

Step-by-step guide to building production-ready inbound SMS handling with Sinch SMS API, Node.js, and Fastify. Includes webhook security, HMAC verification, retry logic, and deployment strategies.

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

Developer Quick-Start: Step-by-step guide to building production-ready inbound SMS handling with Sinch SMS API, Node.js, and Fastify. Includes webhook security, HMAC verification, retry logic, and deployment strategies. 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.

Build a production-ready Node.js application using Fastify to receive and process inbound SMS messages via the Sinch SMS API. This guide covers project setup, webhook handling, sending replies, security considerations, deployment, and troubleshooting.

You'll build a functional Fastify application capable of:

  • Receiving webhook notifications from Sinch for incoming SMS messages
  • Parsing message content and sender information
  • Logging incoming messages with structured data
  • Sending automated replies back via Sinch
  • Running locally using ngrok for testing
  • Deploying to production with containerization

Target Audience: Developers familiar with Node.js and basic web concepts who want to integrate Sinch SMS capabilities into their applications. Familiarity with Fastify helps but isn't required.

Technologies Used:

  • Node.js: The JavaScript runtime environment. Use LTS versions: Node.js 22 (Jod, LTS until April 2027), Node.js 20 (Iron, LTS until April 2026), or Node.js 18 (Hydrogen, LTS until April 2025). Source: Node.js Release Schedule (2024)
  • Fastify: A high-performance, low-overhead web framework for Node.js. Current version: Fastify v5 (released September 2024). Chosen for its speed, extensibility, and developer experience. Source: Fastify Releases (2024)
  • Sinch SMS API (REST): For sending reply messages and configuring inbound webhooks
  • axios: A promise-based HTTP client for making requests to the Sinch API
  • dotenv: For managing environment variables securely
  • ngrok (for local testing): Exposes your local server to the internet securely

Prerequisites:

  • Node.js (LTS version: 18.x, 20.x, or 22.x) and npm (or yarn) installed. Download Node.js
  • A Sinch account with access to the SMS API. Create a Sinch account if you don't have one. Check Sinch pricing before starting.
  • A provisioned phone number within your Sinch account capable of sending and receiving SMS
  • Your Sinch Service Plan ID and API Token (found in your Sinch Customer Dashboard under SMS β†’ APIs)
  • ngrok installed globally (npm install -g ngrok) or available in your PATH

Verification: Confirm your setup works before proceeding:

node --version

npm --version

ngrok version

System Architecture:

The system follows a simple webhook pattern:

  1. User's Phone: Sends an SMS to your Sinch virtual number
  2. Sinch Platform: Receives the SMS and identifies the configured callback URL (webhook) associated with that number or service plan
  3. Sinch Platform: Sends an HTTP POST request containing the message details (sender, recipient, body, etc.) to your application's webhook endpoint
  4. Fastify Application (Your Server): Listens for incoming POST requests on the designated endpoint (/webhooks/sinch)
  5. Fastify Application: Receives the request, parses the JSON payload, logs the message, and performs other actions (e.g., storing in a database, triggering business logic)
  6. (Optional) Fastify Application: Uses the Sinch REST API (via axios) to send an SMS reply back to the original sender
  7. Sinch Platform: Delivers the reply SMS to the user's phone
[User's Phone] <-- SMS --> [Sinch Platform] --- HTTP POST --> [Your Fastify App]
     ^                                                         |
     |----------------------- SMS Reply ------------------------| (via Sinch API)

1. Setting Up the Project

Initialize your Node.js project and install the necessary dependencies.

1. Create Project Directory:

Open your terminal and create a new directory for the project, then navigate into it.

mkdir sinch-fastify-sms
cd sinch-fastify-sms

2. Initialize Node.js Project:

Create a package.json file to manage dependencies and project metadata.

npm init -y

3. Install Dependencies:

Install Fastify for the web server, axios to make API calls to Sinch for replies, and dotenv to manage environment variables.

npm install fastify axios dotenv

Recommended Versions:

  • fastify: ^5.0.0
  • axios: ^1.6.0
  • dotenv: ^16.0.0

4. Create Project Structure:

Create the basic files and directories.

touch index.js .env .gitignore
  • index.js: The main entry point for your Fastify application
  • .env: Stores sensitive credentials and configuration (API keys, phone numbers). Never commit this file to version control.
  • .gitignore: Specifies intentionally untracked files that Git should ignore

5. Configure .gitignore:

Add node_modules and .env to your .gitignore file to prevent committing them.

# .gitignore
node_modules
.env
*.log

6. Set Up Environment Variables:

Open the .env file and add the following variables. Replace the placeholder values with your actual Sinch credentials and number.

.env

# .env

# Sinch Credentials (REST API for sending)
# Found in your Sinch Customer Dashboard β†’ SMS β†’ APIs
SINCH_SERVICE_PLAN_ID="YOUR_SERVICE_PLAN_ID"
SINCH_API_TOKEN="YOUR_API_TOKEN"

# Your Sinch Virtual Number (E.164 format, e.g., +12075551234)
SINCH_NUMBER="YOUR_SINCH_VIRTUAL_NUMBER"

# Server Configuration
PORT=3000
HOST="0.0.0.0" # Listen on all available network interfaces

# Optional: Set Sinch API region if not default (e.g., us, eu, au, ca)
# See Sinch docs for regional endpoints
SINCH_REGION="us"

Finding Your Credentials:

  1. Log in to your Sinch Customer Dashboard
  2. Navigate to SMS β†’ APIs
  3. Find your Service Plan ID listed in the service plan details
  4. Generate or retrieve your API Token from the same section
  5. Go to Numbers to view your provisioned virtual number

E.164 Format: Use the international phone number format with country code, no spaces or special characters. Examples: +12075551234 (US), +447700900123 (UK).

Why this setup?

Using environment variables (dotenv) keeps sensitive credentials out of your codebase, adhering to security best practices. The .gitignore file ensures these secrets and bulky node_modules aren't accidentally committed. Listening on 0.0.0.0 makes the server accessible within Docker containers or cloud environments.


2. Implementing Core Functionality: The Webhook Handler

Build the Fastify server and the endpoint that receives incoming SMS messages from Sinch.

1. Basic Fastify Server:

Open index.js and set up a minimal Fastify server.

require('dotenv').config();

const fastify = require('fastify')({
  logger: true
});

fastify.get('/', async (request, reply) => {
  return { status: 'ok', timestamp: new Date().toISOString() };
});

const start = async () => {
  try {
    const port = process.env.PORT || 3000;
    const host = process.env.HOST || '0.0.0.0';
    await fastify.listen({ port: parseInt(port, 10), host: host });
    fastify.log.info(`Server listening on port ${port}`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

process.on('SIGINT', async () => {
  fastify.log.info('Received SIGINT – shutting down gracefully');
  await fastify.close();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  fastify.log.info('Received SIGTERM – shutting down gracefully');
  await fastify.close();
  process.exit(0);
});

const sinchInboundSmsSchema = {
  body: {
    type: 'object',
    required: ['from', 'to', 'body', 'id', 'type', 'received_at'],
    properties: {
      id: { type: 'string' },
      from: { type: 'string' },
      to: { type: 'string' },
      body: { type: 'string', maxLength: 2000 },
      type: { type: 'string', const: 'mo_text' },
      received_at: { type: 'string', format: 'date-time' },
      sent_at: { type: 'string', format: 'date-time' },
      operator_id: { type: 'string' },
      client_reference: { type: 'string', maxLength: 2048 }
    }
  }
};

fastify.post('/webhooks/sinch', { schema: sinchInboundSmsSchema }, async (request, reply) => {
  request.log.info('Received Sinch inbound SMS webhook:');
  request.log.info(request.body);

  try {
    const { from, to, body, id, received_at } = request.body;
    const senderNumber = from;
    const recipientNumber = to;
    const messageContent = body;
    const messageId = id;

    request.log.info(`Message ID [${messageId}] from [${senderNumber}] to [${recipientNumber}]: "${messageContent}"`);
    request.log.info(`Received at: ${received_at}`);














    reply.code(200).send({ status: 'received' });

  } catch (error) {
    request.log.error('Error processing Sinch webhook:', error);

    reply.code(500).send({ status: 'error processing message' });
  }
});

start();

Test Your Server:

Start your application and verify it's running correctly:

node index.js

You should see output like:

{"level":30,"time":1234567890,"msg":"Server listening on port 3000",...}

Visit http://localhost:3000/ in your browser. You should see:

{"status":"ok","timestamp":"2025-01-15T10:30:00.000Z"}
  • Schema Validation: Fastify automatically validates incoming request bodies against sinchInboundSmsSchema. If validation fails, Fastify sends a 400 Bad Request response, protecting your handler from invalid data.
  • Logging: Log the entire incoming request.body for easy debugging during development. Also log key extracted information.
  • Data Extraction: Safely extract relevant fields like from (sender), to (your Sinch number), and body (the message text).
  • Business Logic Placeholder: A comment marks where you'd integrate your specific application logic.
  • Acknowledgement: Send a 200 OK response back to Sinch quickly to acknowledge receipt. Failure to respond or sending error codes repeatedly might cause Sinch to disable the webhook.
  • Response Timing: If your processing takes longer than 2–3 seconds, respond immediately with 200 OK and process the message asynchronously. Otherwise, Sinch will retry the webhook, potentially creating duplicate processing.
  • Error Handling: A try…catch block handles unexpected errors during processing, logs them, and sends a generic 500 Internal Server Error response.
  • Graceful Shutdown: The server handles SIGINT and SIGTERM signals to close connections cleanly.

Endpoint Documentation & Testing:

  • Endpoint: POST /webhooks/sinch
  • Description: Receives inbound SMS notifications from the Sinch platform
  • Request Body: application/json
  • Requires fields: from (string), to (string), body (string, max 2000 chars), id (string), type (string, "mo\_text"), received\_at (ISO-8601 date-time)
  • See sinchInboundSmsSchema in the code above for the full expected structure
  • Example Request Payload (Actual Sinch Format):
    {
      "id": "01FC66621XXXXX119Z8PMV1QPA",
      "from": "16051234567",
      "to": "13185551234",
      "body": "This is a test message.",
      "type": "mo_text",
      "received_at": "2022-08-24T14:15:22Z",
      "sent_at": "2022-08-24T14:15:22Z",
      "operator_id": "310260",
      "client_reference": "myReference"
    }
  • Responses:
  • 200 OK: Successfully received and acknowledged the message. Sinch expects response within the 2xx success range.
    { "status": "received" }
  • 400 Bad Request: The incoming request body did not match the expected schema (handled automatically by Fastify). This counts as a permanent failure and will NOT trigger retries.
    {
      "statusCode": 400,
      "error": "Bad Request",
      "message": "body should have required property '…' or body should match pattern \"…\""
    }
  • 429 Too Many Requests: The callback will be retried AND the callback throughput will be lowered by Sinch. Source: Sinch Webhooks Documentation (2024)
  • 500 Internal Server Error: An error occurred while processing the message on the server. A 5xx status code will trigger Sinch's retry mechanism.
    { "status": "error processing message" }
  • Testing with curl:

Simulate a Sinch webhook call using curl once your server is running. Check your running server's console logs to see the output.

  curl -X POST http://localhost:3000/webhooks/sinch \
  -H "Content-Type: application/json" \
  -d '{
    "id": "TEST01",
    "from": "16051234567",
    "to": "13185551234",
    "body": "This is a test message via curl",
    "type": "mo_text",
    "received_at": "2025-04-20T11:00:00Z",
    "operator_id": "SIMULATED"
  }'

Expected Output in Console:

  {"level":30,"time":...,"msg":"Received Sinch inbound SMS webhook:"}
  {"level":30,"time":...,"msg":{"id":"TEST01","from":"16051234567",...}}
  {"level":30,"time":...,"msg":"Message ID [TEST01] from [16051234567] to [13185551234]: \"This is a test message via curl\""}

3. Integrating with Sinch (Sending Replies)

Implement the function to send replies using the Sinch REST API and axios.

1. Add axios:

Already installed in the setup phase.

2. Create the Send Function:

Add this function to your index.js file, replacing the placeholder comment.

const axios = require('axios');

const sinchRegion = process.env.SINCH_REGION || 'us';
const SINCH_API_BASE_URL = `https://${sinchRegion}.sms.api.sinch.com/xms/v1/`;

async function sendSmsReply(recipientNumber, messageBody, log = fastify.log) {
  const servicePlanId = process.env.SINCH_SERVICE_PLAN_ID;
  const apiToken = process.env.SINCH_API_TOKEN;
  const sinchNumber = process.env.SINCH_NUMBER;

  if (!servicePlanId || !apiToken || !sinchNumber) {
    log.error('Sinch API credentials or number not configured in .env file. Cannot send SMS.');
    return;
  }

  const endpoint = `${SINCH_API_BASE_URL}${servicePlanId}/batches`;

  const payload = {
    from: sinchNumber,
    to: [recipientNumber],
    body: messageBody,

  };

  const config = {
    headers: {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json'
    },


    timeout: 10000,
  };

  try {
    log.info(`Sending SMS reply to [${recipientNumber}] via Sinch…`);
    const response = await axios.post(endpoint, payload, config);
    log.info(`Sinch API response status: ${response.status}`);
    log.info(`Sinch API response data: ${JSON.stringify(response.data)}`);

    return response.data;
  } catch (error) {
    log.error(`Error sending SMS via Sinch to [${recipientNumber}]:`);
    if (error.response) {


      log.error(`Status: ${error.response.status}`);
      log.error(`Headers: ${JSON.stringify(error.response.headers)}`);
      log.error(`Data: ${JSON.stringify(error.response.data)}`);


      if (error.response.status === 429) {
        const retryAfter = error.response.headers['retry-after'] || 60;
        log.warn(`Rate limited by Sinch API. Retry after ${retryAfter} seconds.`);

      }
    } else if (error.request) {

      log.error('No response received from Sinch API.');
    } else {

      log.error('Error setting up Sinch API request:', error.message);
    }

  }
}
  • Dynamic Base URL: Construct the API endpoint URL using the SINCH\_REGION environment variable for flexibility
  • Credentials Check: The function first checks if the necessary environment variables are set
  • API Payload: The payload includes your Sinch number (from), the recipient's number (to – as an array), and the message body
  • Authorization Header: The Authorization: Bearer YOUR\_API\_TOKEN header authenticates with the Sinch REST API
  • Timeout Configuration: Set to 10 seconds to prevent hanging on slow connections. Most Sinch API calls respond within 1–2 seconds under normal conditions.
  • Rate Limit Handling: Detects 429 responses and logs the retry-after period for implementing backoff logic
  • Axios Request: Use axios.post to send the request
  • Detailed Error Logging: The catch block provides detailed logging based on the type of error received from axios, helpful for troubleshooting API integration issues
  • Logger Passing: Pass the request.log instance (or the global fastify.log) into sendSmsReply so logs related to sending a reply are associated with the original incoming request context

3. Configure ngrok for Local Testing:

Set up ngrok to expose your local server to the internet so Sinch can send webhooks to it.

Start ngrok:

ngrok http 3000

Expected Output:

Session Status                online
Account                       your_account (Plan: Free)
Version                       3.x.x
Region                        United States (us)
Forwarding                    https://abc123.ngrok.io -> http://localhost:3000

Important: Copy the HTTPS forwarding URL (e.g., https://abc123.ngrok.io). This is your public webhook URL.

ngrok Subdomain Persistence:

  • Free Tier: ngrok generates a new random subdomain each time you restart it
  • Paid Tier: You can reserve a custom subdomain that persists across restarts (e.g., https://yourapp.ngrok.io)
  • For development, the free tier works fine – just update the Sinch dashboard callback URL each time you restart ngrok

4. Sinch Dashboard Configuration:

Tell Sinch where to send incoming SMS notifications.

  1. Log in to your Sinch Customer Dashboard
  2. Navigate to SMS β†’ APIs
  3. Find your Service Plan ID listed there and click on it
  4. Locate the Callback URL section (might be under "Default Settings" or similar)
  5. Click Add Callback URL or Edit
  6. Enter your ngrok HTTPS URL followed by the webhook path: https://abc123.ngrok.io/webhooks/sinch
  7. Important: Ensure the URL starts with https://. Sinch requires secure callbacks.
  8. Save the changes

Environment Variables Summary:

Variable Description Example
SINCH_SERVICE_PLAN_ID Your specific service plan identifier from the Sinch dashboard. Used in the API URL for sending. abc12345def67890
SINCH_API_TOKEN Your secret API token from the Sinch dashboard. Used in the Authorization header for sending. token_xyz789...
SINCH_NUMBER Your provisioned Sinch virtual phone number in E.164 format. Used as the from number when sending replies. +12223334444
PORT The local port your Fastify server listens on. 3000
HOST The network interface to bind to (0.0.0.0 for broad accessibility, 127.0.0.1 for local only). 0.0.0.0
SINCH_REGION The geographical region for your Sinch API endpoint (e.g., us, eu). Affects the base URL for sending SMS. us

4. Error Handling, Logging, and Retries

Error Handling:

Your application handles three categories of errors:

  • Fastify Validation: Handled automatically via the schema defined for the /webhooks/sinch route. Invalid requests get a 400 response.
  • Webhook Processing (Recoverable): Network timeouts, database connection issues, temporary service unavailability. Log the error, return 500 to trigger Sinch retry.
  • Webhook Processing (Non-Recoverable): Invalid phone number format, message violates content policy, authentication failure. Log the error, return 200 to prevent retries.
  • API Call Errors (sendSmsReply): The catch block in sendSmsReply handles network errors, authentication failures (401), authorization issues (403), bad requests (400), or server errors (5xx) from the Sinch API. It logs detailed information.

Logging:

  • Fastify Default Logger (Pino): Enabled via logger: true during Fastify initialization. Provides structured JSON logging by default, excellent for production.
  • Key Events Logged:
  • Server startup (fastify.log.info)
  • Incoming webhook requests (request.log.info)
  • Full webhook payload (request.log.info)
  • Extracted message details including timestamps (request.log.info)
  • Errors during processing (request.log.error)
  • Attempts to send replies (log.info in sendSmsReply)
  • Sinch API responses/errors (log.info/log.error in sendSmsReply)
  • Log Management: In production, forward these structured logs to a log management service (e.g., Datadog, Logz.io, ELK stack) for searching, filtering, and alerting based on error messages or specific log properties. Configure log rotation using tools like logrotate on Linux or your platform's built-in log management. Set retention policies based on compliance requirements – typically 30–90 days for application logs.

Retry Mechanisms:

  • Incoming Webhooks (Sinch Retry Policy): If your endpoint fails to respond with a 2xx status code, Sinch retries the callback using exponential backoff. Official retry schedule: The first retry occurs 5 seconds after the initial attempt, then 10 seconds, 20 seconds, 40 seconds, 80 seconds, doubling on every attempt. The final retry occurs at 81,920 seconds (22 hours 45 minutes) after the initial failed attempt. For 429 responses, the callback will be retried with lowered throughput. Ensure your handler responds quickly (ideally under 2–3 seconds) to avoid triggering retries. Source: Sinch Webhooks Documentation (2024)
  • Outgoing API Calls with Retry Logic:

For production systems, implement retry logic for transient failures:

const asyncRetry = require('async-retry');

async function sendSmsReplyWithRetry(recipientNumber, messageBody, log = fastify.log) {

  return await asyncRetry(
    async (bail) => {
      try {
        return await sendSmsReply(recipientNumber, messageBody, log);
      } catch (error) {

        if (error.response && error.response.status >= 400 && error.response.status < 500) {
          if (error.response.status !== 429) {
            bail(error);
            return;
          }
        }
        throw error;
      }
    },
    {
      retries: 3,
      factor: 2,
      minTimeout: 1000,
      maxTimeout: 5000,
      onRetry: (error, attempt) => {
        log.warn(`Retry attempt ${attempt} for sending SMS to ${recipientNumber}`);
      }
    }
  );
}

Install async-retry:

npm install async-retry

Idempotency: To prevent duplicate message sends during retries, generate a unique idempotency key for each message and store it:

const crypto = require('crypto');

function generateIdempotencyKey(recipientNumber, messageBody, originalMessageId) {
  const data = `${recipientNumber}:${messageBody}:${originalMessageId}`;
  return crypto.createHash('sha256').update(data).digest('hex');
}

const idempotencyKey = generateIdempotencyKey(senderNumber, replyMessage, messageId);

5. Database Schema and Data Layer (Conceptual)

Storing message history is often required. Here's a practical approach:

Entity Relationship Diagram (ERD):

+-----------------+      +-----------------+
|     Contact     |      |     Message     |
+-----------------+      +-----------------+
| contact_id (PK) |      | message_id (PK) |
| phone_number(UQ)|------| sinch_msg_id(UQ)|
| created_at      |      | contact_id (FK) |
| updated_at      |      | direction       | // 'inbound' or 'outbound'
+-----------------+      | body            |
                       | status          | // 'received', 'sent', 'delivered', 'failed'
                       | error_message   |
                       | retry_count     |
                       | metadata        | // JSON field for extensibility
                       | received_at     |
                       | sent_at         |
                       +-----------------+

Prisma Schema Example:

Prisma

// prisma/schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Contact {
  id           String    @id @default(cuid())
  phoneNumber  String    @unique @map("phone_number")
  createdAt    DateTime  @default(now()) @map("created_at")
  updatedAt    DateTime  @updatedAt @map("updated_at")
  messages     Message[]

  @@map("contacts")
}

model Message {
  id            String    @id @default(cuid())
  sinchMsgId    String    @unique @map("sinch_msg_id")
  contactId     String    @map("contact_id")
  direction     String    // 'inbound' or 'outbound'
  body          String
  status        String    // 'received', 'sent', 'delivered', 'failed'
  errorMessage  String?   @map("error_message")
  retryCount    Int       @default(0) @map("retry_count")
  metadata      Json?
  receivedAt    DateTime? @map("received_at")
  sentAt        DateTime? @map("sent_at")
  contact       Contact   @relation(fields: [contactId], references: [id])

  @@index([contactId])
  @@index([sinchMsgId])
  @@map("messages")
}

Implementation Steps (using Prisma + PostgreSQL):

  1. Install ORM and Database Driver:
   npm install @prisma/client pg
   npm install -D prisma
  1. Initialize ORM:
   npx prisma init
  1. Add DATABASE\_URL to .env:

.env

   DATABASE_URL="postgresql://user:password@localhost:5432/sinch_sms?schema=public"
  1. Update Schema: Copy the Prisma schema above into prisma/schema.prisma
  2. Create Migrations:
   npx prisma migrate dev --name initial_setup
  1. Generate Client:
   npx prisma generate
  1. Integrate into Webhook Handler:
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

try {

  const contact = await prisma.contact.upsert({
    where: { phoneNumber: senderNumber },
    update: {},
    create: { phoneNumber: senderNumber }
  });


  await prisma.message.create({
    data: {
      sinchMsgId: messageId,
      contactId: contact.id,
      direction: 'inbound',
      body: messageContent,
      status: 'received',
      receivedAt: new Date(received_at)
    }
  });


} catch (dbError) {
  request.log.error('Database error:', dbError);

}

Connection Pooling: Configure Prisma's connection pool in schema.prisma:

Prisma

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
  // Connection pooling configuration
  // Format: postgresql://user:password@localhost:5432/dbname?connection_limit=10&pool_timeout=20
}

Recommended pool size: 10–20 connections for typical webhook workloads.


6. Security Features

  • Input Validation: Handled by Fastify's schema validation on the /webhooks/sinch route. Protects against malformed payloads.
  • Environment Variables: Securely manage API keys and sensitive data using .env and ensuring it's in .gitignore.
  • HTTPS: Sinch requires HTTPS for callback URLs, ensuring data is encrypted in transit. ngrok provides this locally. In production, use a reverse proxy (like Nginx or Caddy) or a PaaS that terminates SSL.
  • Rate Limiting: Protect against denial-of-service or abuse by implementing rate limiting on the webhook endpoint. Use @fastify/rate-limit:
npm install @fastify/rate-limit
const fastify = require('fastify')({ logger: true });

await fastify.register(require('@fastify/rate-limit'), {
  max: 100,
  timeWindow: '1 minute'


});
  • Webhook Signature Verification (HMAC):
  • Problem: Anyone who discovers your webhook URL could potentially send fake SMS notifications.
  • Sinch HMAC Support: Sinch SMS API supports HMAC (Hash-based Message Authentication Code) using SHA-256 for webhook authentication. HMAC provides cryptographic verification of webhook authenticity and payload integrity. Source: Sinch Webhooks Documentation (2024)
  • Configuration Required: HMAC authentication must be configured by contacting your Sinch account manager. It can be assigned to a specific callback URL or an entire Service Plan. HMAC can also be configured alongside Basic Auth or OAuth 2.0.
  • Implementation Approaches:
  1. Shared Secret Token (Simpler): Include a hard-to-guess secret token as a query parameter in the Callback URL configured in Sinch (e.g., https://…/webhooks/sinch?token=YOUR_SECRET_TOKEN). Verify this token in your handler. This adds protection but is less robust than HMAC.
       const expectedToken = process.env.WEBHOOK_SECRET_TOKEN;
       const receivedToken = request.query.token;
       if (!expectedToken || receivedToken !== expectedToken) {
         request.log.warn('Invalid or missing webhook token');
         reply.code(401).send({ status: 'unauthorized' });
         return;
       }
  1. HMAC-SHA256 (Most Secure, Recommended for Production): Once configured by your account manager, Sinch includes signature headers in webhook requests. Your application calculates the signature using the webhook secret and compares it to Sinch's provided signature. Typical headers include:
  • x-sinch-webhook-signature-nonce: Unique nonce value
  • x-sinch-webhook-signature-timestamp: Request timestamp
  • x-sinch-webhook-signature: HMAC-SHA256 signature (base64-encoded)

HMAC Verification with Replay Attack Prevention:

       const crypto = require('crypto');

       const usedNonces = new Set();

       function verifyHmacSignature(request, webhookSecret) {
         const signature = request.headers['x-sinch-webhook-signature'];
         const nonce = request.headers['x-sinch-webhook-signature-nonce'];
         const timestamp = request.headers['x-sinch-webhook-signature-timestamp'];
         const rawBody = JSON.stringify(request.body);

         if (!signature || !nonce || !timestamp) {
           return false;
         }


         const requestTime = parseInt(timestamp, 10);
         const now = Date.now();
         const fiveMinutes = 5 * 60 * 1000;
         if (Math.abs(now - requestTime) > fiveMinutes) {
           return false;
         }


         if (usedNonces.has(nonce)) {
           return false;
         }
         usedNonces.add(nonce);



         const message = nonce + timestamp + rawBody;


         const expectedSignature = crypto
           .createHmac('sha256', webhookSecret)
           .update(message)
           .digest('base64');


         return crypto.timingSafeEqual(
           Buffer.from(signature),
           Buffer.from(expectedSignature)
         );
       }

       const webhookSecret = process.env.SINCH_WEBHOOK_SECRET;
       if (webhookSecret && !verifyHmacSignature(request, webhookSecret)) {
         request.log.warn('Invalid HMAC signature – potential unauthorized request');
         reply.code(401).send({ status: 'unauthorized' });
         return;
       }

Webhook Secret Management:

  • Store secrets in environment variables, never in code
  • Use secret management services (AWS Secrets Manager, HashiCorp Vault, Google Secret Manager) in production
  • Rotate secrets every 90 days
  • When rotating, support both old and new secrets for 24 hours to prevent downtime

Note: Contact your Sinch account manager to enable and configure HMAC authentication for your webhooks.

  • Least Privilege: Ensure the API Token used only has permissions necessary for sending SMS (and potentially managing numbers/callbacks if needed), not broader account access.

7. Handling Special Cases

  • Character Encoding: Sinch and modern platforms handle UTF-8 correctly, supporting various characters and emojis. Ensure your database (if used) is also configured for UTF-8.
  • Long Messages (Concatenation): Sinch handles splitting long messages into multiple parts and delivering them correctly. The body received by your webhook contains the fully reassembled message. When sending, Sinch also handles splitting if the body exceeds standard SMS limits.
  • Non-Text Messages (MMS/Binary): This guide focuses on text (mo_text). Handling MMS (images, etc.) or binary SMS requires different webhook types (mo_binary) and payload structures, often involving links to media content. This requires extending the schema and handler logic.
  • Invalid Numbers: The sendSmsReply function might fail if the senderNumber is invalid or cannot receive SMS. The error handling block catches this (often as a 4xx error from Sinch).
  • Duplicate Messages: Network issues could potentially cause Sinch to retry sending a webhook. Use the unique Sinch message ID (request.body.id) to deduplicate messages. Inbound messages are stored in Sinch's system for 14 days and can be retrieved via the Inbounds API if needed. Source: Sinch Inbounds API (2024)

Deduplication Implementation:

const messageId = request.body.id;

const existingMessage = await prisma.message.findUnique({
  where: { sinchMsgId: messageId }
});

if (existingMessage) {
  request.log.info(`Duplicate message ${messageId} detected – skipping processing`);
  reply.code(200).send({ status: 'already processed' });
  return;
}
  • Character Encoding Edge Cases: SMS messages use either GSM-7 (supports 160 chars) or Unicode/UCS-2 (supports 70 chars). Sinch automatically detects and uses the appropriate encoding. Characters like emojis force Unicode encoding, reducing the character limit per message segment.
  • Opt-Out Keywords: Implement automatic handling for opt-out keywords (STOP, UNSUBSCRIBE, CANCEL):
const normalizedBody = messageContent.trim().toUpperCase();

if (['STOP', 'UNSUBSCRIBE', 'CANCEL', 'END', 'QUIT'].includes(normalizedBody)) {
  request.log.info(`Opt-out request from ${senderNumber}`);


  await prisma.contact.update({
    where: { phoneNumber: senderNumber },
    data: { optedOut: true, optedOutAt: new Date() }
  });


  await sendSmsReply(
    senderNumber,
    'You have been unsubscribed. Reply START to opt back in.',
    request.log
  );

  reply.code(200).send({ status: 'received' });
  return;
}

8. Performance Optimizations

  • Fastify: Chosen for its high performance out-of-the-box
  • Asynchronous Operations: All I/O (logging, API calls, potential DB access) uses async/await, preventing the Node.js event loop from being blocked
  • Logging Level: In production, set the log level to info or warn instead of debug to reduce logging overhead:
const fastify = require('fastify')({
  logger: {
    level: process.env.LOG_LEVEL || 'info'
  }
});
  • Payload Size: Be mindful of very large webhook payloads if they occur, though typical SMS webhooks are small
  • Database Optimization: Proper indexing (as mentioned in Section 5) is crucial if storing messages. Prevent N+1 queries by using Prisma's include and select options strategically.
  • Load Testing: Use tools like k6, autocannon, or wrk to simulate high volumes of webhook traffic and identify bottlenecks in your processing logic or downstream dependencies:
autocannon -m POST -H "Content-Type=application/json" -b '{ "id": "LT01", "from": "16051234567", "to": "13185551234", "body": "Load test", "type": "mo_text", "received_at": "2025-01-01T00:00:00Z" }' http://localhost:3000/webhooks/sinch

Expected Throughput: A properly configured Fastify application on modern hardware should handle 5,000–10,000 requests/second for simple webhook processing. With database writes, expect 500–2,000 requests/second depending on database performance.


9. Monitoring, Observability, and Analytics

  • Health Checks: The GET / route serves as a basic health check endpoint for load balancers or monitoring systems
  • Logging: Centralized logging (Section 4) is key for observability
  • Performance Metrics (APM): Integrate Application Performance Monitoring tools like Sentry (which has Fastify integration), Datadog APM, or Dynatrace. These automatically instrument your Fastify app to track request latency, error rates, throughput, and trace requests across services.

Sentry Example:

  npm install --save @sentry/node @sentry/profiling-node
  const Sentry = require('@sentry/node');
  const { ProfilingIntegration } = require('@sentry/profiling-node');

  Sentry.init({
    dsn: process.env.SENTRY_DSN,
    integrations: [
      new Sentry.Integrations.Http({ tracing: true }),
      new ProfilingIntegration(),
    ],
    tracesSampleRate: 1.0,
    profilesSampleRate: 1.0,
  });

  const fastify = require('fastify')({ logger: true });

  fastify.addHook('onRequest', Sentry.Handlers.requestHandler());
  fastify.addHook('onRequest', Sentry.Handlers.tracingHandler());

  fastify.setErrorHandler(async (error, request, reply) => {
    Sentry.captureException(error);
    reply.send(error);
  });
  • Business Metrics: Track SMS-specific KPIs:
  • Inbound message volume (messages/hour)
  • Outbound message volume (messages/hour)
  • Delivery rate (delivered / sent)
  • Response time (time between inbound and outbound)
  • Failed sends by error type
  • Unique active users (contacts sending messages)
  • Alerting: Set up alerts in your monitoring or logging system for:
  • High error rates (5xx responses on webhook, API call failures)
  • Increased latency (> 500ms p95)
  • Low throughput (if expecting consistent traffic)
  • Specific error messages (e.g., "Invalid Sinch credentials")
  • Delivery rate drops below 95%

10. Deployment Considerations

  • Containerization (Docker): Package the application into a Docker image for consistent deployments.

Dockerfile Example:

  # Dockerfile
  FROM node:22-alpine AS base

  WORKDIR /app

  # Install dependencies only when package files change
  COPY package*.json ./
  RUN npm ci --only=production

  # Copy application code
  COPY . .

  # Expose the port the app runs on
  EXPOSE 3000

  # Set environment variables (can be overridden at runtime)
  ENV NODE_ENV=production
  ENV PORT=3000
  ENV HOST=0.0.0.0
  # Ensure SINCH_* variables are injected securely at runtime (e.g., via secrets management)

  # Run the application
  CMD [ "node", "index.js" ]

.dockerignore: Similar to .gitignore, include:

  node_modules
  .env
  Dockerfile
  .dockerignore
  *.log
  .git
  • Platform Choice:
  • PaaS (e.g., Heroku, Render, Railway): Simplest option, handles infrastructure, scaling, HTTPS. Ensure the platform supports long-running Node.js servers (not just serverless functions for this webhook pattern)
  • Container Orchestration (e.g., Kubernetes, AWS ECS, Google Cloud Run): More control and scalability, requires more setup. Ideal for larger applications
  • Virtual Machine (e.g., AWS EC2, Google Compute Engine): Full control, requires manual setup of Node.js, process manager (like pm2), reverse proxy (Nginx/Caddy for HTTPS), and firewall
  • Environment Variables: Inject sensitive environment variables (SINCH_API_TOKEN, etc.) securely using platform secrets management:
  • Heroku: heroku config:set SINCH\_API\_TOKEN=xyz
  • Kubernetes: Store in Secrets and mount as env vars
  • AWS ECS: Use AWS Secrets Manager or Parameter Store
  • Never hardcode secrets in Docker images or code
  • Process Management: In non-PaaS environments, use a process manager like pm2 to keep the Node.js application running:
npm install pm2 -g
pm2 start index.js --name sinch-sms
pm2 startup
pm2 save
  • HTTPS Termination: Ensure HTTPS is enforced. PaaS and orchestrators often handle this. If using VMs, configure a reverse proxy like Nginx or Caddy to handle SSL certificates (e.g., via Let's Encrypt) and proxy requests to your Node.js app running on localhost:3000.
  • Scaling:
  • Vertical: Increase CPU/RAM of the server/container instance
  • Horizontal: Run multiple instances of the application behind a load balancer. Ensure your application is stateless or manages state externally (e.g., using a database or Redis) if scaling horizontally. The webhook handler itself is generally stateless.
  • Zero-Downtime Deployments: Use blue-green or rolling deployment strategies:
  • Blue-Green: Deploy new version to separate environment, test, then switch traffic
  • Rolling: Gradually replace old instances with new ones (Kubernetes does this automatically)
  • Always test new deployments with health checks before directing traffic

11. Troubleshooting

Common Issues and Solutions:

Issue Solution
Webhooks not arriving 1. Verify ngrok is running and HTTPS URL is correct 2. Check Sinch dashboard callback URL configuration 3. Check server logs for incoming requests 4. Verify firewall allows inbound traffic
400 Bad Request errors 1. Check webhook payload matches schema 2. Verify Fastify schema validation isn't too strict 3. Log full request body to inspect structure
500 Internal Server errors 1. Check server logs for error stack traces 2. Verify environment variables are set correctly 3. Test database connectivity if using persistence
SMS not sending 1. Verify SINCH_API_TOKEN is correct 2. Check SINCH_SERVICE_PLAN_ID matches dashboard 3. Verify SINCH_NUMBER is in E.164 format 4. Check Sinch API error response details
Duplicate messages 1. Implement deduplication using sinch_msg_id 2. Respond faster (< 2 seconds) to prevent retries 3. Check Sinch dashboard for retry settings

Diagnostic Steps:

  1. Check Server Logs: The first step for any issue. Look for errors reported by Fastify, axios, or your custom logic
  2. Verify ngrok Tunnel: If testing locally, ensure ngrok is running and the HTTPS URL is correctly configured in the Sinch dashboard. Check the ngrok web interface (http://localhost:4040 by default) to see incoming requests
  3. Test with curl: Use the curl command (provided in Section 2) to simulate requests directly to your running application, bypassing Sinch/ngrok to isolate issues
  4. Check Sinch Dashboard:
  • API Logs: Look for logs related to callback attempts or SMS sending failures in the Sinch dashboard (if available)
  • Callback URL: Double-check the configured callback URL is correct, uses HTTPS, and includes the /webhooks/sinch path
  • Number Configuration: Ensure the Sinch number is correctly provisioned and assigned to the Service Plan ID used
  1. Environment Variables: Ensure all required .env variables are set correctly and accessible by the application (especially in deployment environments). Log them on startup (excluding secrets) for verification:
fastify.log.info({
  port: process.env.PORT,
  host: process.env.HOST,
  region: process.env.SINCH_REGION,
  hasServicePlanId: !!process.env.SINCH_SERVICE_PLAN_ID,
  hasApiToken: !!process.env.SINCH_API_TOKEN,
  hasNumber: !!process.env.SINCH_NUMBER
});
  1. Firewall Issues: In deployed environments, ensure firewalls allow incoming traffic on the application's port (e.g., 3000 or 443 if using a reverse proxy) from Sinch's IP ranges (check Sinch documentation for these)
  2. Sinch API Errors: Examine the detailed error logs from the sendSmsReply function's catch block (Status, Headers, Data) to understand failures when sending replies.

Common Sinch API Error Codes:

Status Code Meaning Action
400 Bad Request – Invalid parameters Check phone number format, message body, API payload structure
401 Unauthorized – Invalid API token Verify SINCH_API_TOKEN is correct and active
403 Forbidden – Insufficient permissions Check API token has SMS sending permissions
404 Not Found – Service Plan ID doesn't exist Verify SINCH_SERVICE_PLAN_ID is correct
429 Rate Limit Exceeded Implement exponential backoff, check rate limits in dashboard
500/502/503 Sinch Server Error Implement retry logic with exponential backoff

This guide provides a solid foundation for receiving Sinch SMS messages with Fastify. Adapt the business logic, error handling, security measures, and deployment strategy to your specific production requirements.

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