This guide provides a complete walkthrough for building a production-ready Fastify API endpoint capable of sending SMS messages using the Sinch SMS API and their official Node.js SDK. We'll cover project setup, configuration, core implementation, error handling, security considerations, testing, and deployment basics.
The final application will expose a simple API endpoint that accepts a recipient phone number and a message body, then uses Sinch to dispatch the SMS.
Technologies Used:
- Node.js: The runtime environment. (LTS version recommended)
- Fastify: A high-performance, low-overhead web framework for Node.js. Chosen for its speed, extensibility, and developer experience.
- Sinch Node.js SDK (
@sinch/sdk-client
): The official library for interacting with Sinch APIs, simplifying authentication and requests. dotenv
: A module to load environment variables from a.env
file intoprocess.env
.@fastify/env
: For validating and managing environment variables within Fastify.@fastify/helmet
: For basic security headers.@fastify/rate-limit
: For API rate limiting.
System Architecture:
The architecture is straightforward:
- Client (e.g., curl, Postman, Frontend App): Sends an HTTP POST request to the Fastify API endpoint (
/sms/send
). - Fastify API:
- Receives the request.
- Validates the request payload (recipient number, message).
- Calls the Sinch Service module.
- Returns a response to the client (success or error).
- Sinch Service Module:
- Uses the Sinch Node.js SDK.
- Authenticates with Sinch using credentials from environment variables.
- Constructs and sends the SMS batch request to the Sinch API.
- Handles potential errors from the Sinch API.
- Sinch Platform: Receives the API request, processes it, and delivers the SMS message to the recipient's phone.
graph LR
Client -- POST /sms/send --> FastifyAPI[Fastify API];
FastifyAPI -- sendSms(to, message) --> SinchService[Sinch Service Module];
SinchService -- Send SMS Request --> SinchPlatform[Sinch Platform API];
SinchPlatform -- SMS --> RecipientPhone[Recipient Phone];
SinchPlatform -- API Response --> SinchService;
SinchService -- Success/Error --> FastifyAPI;
FastifyAPI -- HTTP Response --> Client;
Prerequisites:
- Node.js and npm: Installed on your system. Download LTS from nodejs.org.
- Sinch Account: A registered account at Sinch.com.
- Sinch API Credentials: You'll need a Project ID, SDK Key ID, and SDK Key Secret from your Sinch Dashboard.
- Sinch Phone Number: An SMS-enabled number purchased or assigned within your Sinch account.
- Basic Terminal/Command Line Knowledge: Familiarity with navigating directories and running commands.
- (Optional)
fastify-cli
: For generating project boilerplate. Install globally:npm install -g fastify-cli
. - (Optional) Postman or
curl
: For testing the API endpoint.
Final Outcome:
By the end of this guide, you will have a running Fastify application with a /sms/send
endpoint that securely sends SMS messages via Sinch, including basic validation, error handling, and configuration management.
1. Setting up the Project
Let's initialize our Node.js project using Fastify CLI for a standard structure. If you prefer not to use the CLI, you can create the files and folders manually.
Using Fastify CLI (Recommended):
# 1. Create a project directory
mkdir fastify-sinch-sms
cd fastify-sinch-sms
# 2. Generate a basic Fastify project
fastify generate .
# Respond to the prompts (defaults are usually fine for this guide)
# Choose standard JavaScript
# 3. Install necessary production dependencies
npm install @sinch/sdk-client dotenv @fastify/env @fastify/helmet @fastify/rate-limit
# 4. Install development dependencies
npm install --save-dev tap sinon # Fastify's default test runner and mocking library
# 5. (Optional) If not using fastify-cli, initialize npm and install core fastify
# npm init -y
# npm install fastify @sinch/sdk-client dotenv @fastify/env @fastify/helmet @fastify/rate-limit
# npm install --save-dev tap sinon
Manual Setup (Alternative):
If you didn't use fastify generate
, create the following basic structure:
fastify-sinch-sms/
├── node_modules/
├── routes/
│ └── sms/
│ └── index.js # Our SMS sending route
├── services/
│ └── sinchService.js # Logic for interacting with Sinch SDK
├── plugins/ # For Fastify plugins if needed later
├── test/ # Test files (e.g., routes/sms.test.js)
│ ├── routes/
│ │ └── sms.test.js
│ └── helper.js # Test helper for building the app
├── app.js # Main application entry point
├── package.json
├── package-lock.json
├── .env # Environment variables (DO NOT COMMIT)
└── .gitignore # Git ignore file
Create app.js
, routes/sms/index.js
, services/sinchService.js
, and test files manually if needed. Ensure your package.json
includes the dependencies listed above.
Create .gitignore
:
It's crucial to prevent committing sensitive information and unnecessary files. Create a .gitignore
file in the project root:
# .gitignore
# Node dependencies
node_modules/
# Environment variables
.env
*.env
.env.*
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Build output
dist
build
# OS generated files
.DS_Store
Thumbs.db
2. Configuration and Environment Variables
We need to configure our application with the Sinch API credentials and settings. We'll use dotenv
and @fastify/env
to manage these securely and robustly.
Create .env
file:
Create a file named .env
in the root of your project. Never commit this file to version control.
# .env
# Sinch Credentials - Get from Sinch Dashboard > API & SDK > SDK Keys
SINCH_PROJECT_ID=YOUR_SINCH_PROJECT_ID
SINCH_KEY_ID=YOUR_SINCH_KEY_ID
SINCH_KEY_SECRET=YOUR_SINCH_KEY_SECRET
# Sinch Settings
SINCH_REGION=us # Or eu, etc. Check Sinch docs for available regions.
SINCH_NUMBER=+1xxxxxxxxxx # Your purchased/assigned Sinch SMS number
# Application Settings
PORT=3000
HOST=0.0.0.0 # Listen on all available network interfaces
LOG_LEVEL=info # Pino log level (trace, debug, info, warn, error, fatal)
How to Obtain Sinch Credentials:
- Log in to your Sinch Customer Dashboard.
- Navigate to the API & SDK section (or similar, the exact path might change).
- Find or create an SDK Key pair associated with your project.
SINCH_PROJECT_ID
: This is usually visible on your main dashboard or project settings.SINCH_KEY_ID
: This is the public identifier for your SDK key.SINCH_KEY_SECRET
: This is the secret credential. Important: Sinch typically shows this secret only once upon creation. Store it securely immediately (in your.env
file locally, and use secrets management for production).
- Find your Sinch Phone Number (
SINCH_NUMBER
) under the Numbers section or associated with your SMS Service Plan. It must be SMS-enabled. - Determine the correct Region (
SINCH_REGION
) for your Sinch account/service plan (e.g.,us
,eu
). This is often specified when setting up your service plan or found in the API documentation corresponding to your account setup. Using the wrong region will cause authentication or connection errors.
Load and Validate Environment Variables:
We need to load these variables when the application starts. Modify your main application file (app.js
or server.js
) to use @fastify/env
. While dotenv
alone can load variables into process.env
, @fastify/env
adds crucial schema validation, type coercion, default values, and makes configuration centrally available via fastify.config
. This prevents runtime errors due to missing or invalid environment variables.
// app.js (or server.js)
'use strict'
const path = require('node:path')
const AutoLoad = require('@fastify/autoload')
const fastifyEnv = require('@fastify/env')
// Define schema for environment variables using @fastify/env
// This ensures required variables are present and have the correct type.
const envSchema = {
type: 'object',
required: [
'PORT',
'HOST',
'SINCH_PROJECT_ID',
'SINCH_KEY_ID',
'SINCH_KEY_SECRET',
'SINCH_REGION',
'SINCH_NUMBER'
],
properties: {
PORT: { type: 'string', default: 3000 },
HOST: { type: 'string', default: '0.0.0.0' },
LOG_LEVEL: { type: 'string', default: 'info'},
SINCH_PROJECT_ID: { type: 'string' },
SINCH_KEY_ID: { type: 'string' },
SINCH_KEY_SECRET: { type: 'string' },
SINCH_REGION: { type: 'string' },
SINCH_NUMBER: { type: 'string' } // Keep as string to preserve leading +
},
// Make NODE_ENV available if needed, with a default
// NODE_ENV: { type: 'string', default: 'development' }
};
const envOptions = {
confKey: 'config', // Access variables via `fastify.config`
schema: envSchema,
dotenv: true // Tells @fastify/env to load .env file(s) using dotenv
};
module.exports = async function (fastify, opts) {
// Register @fastify/env FIRST to load and validate config
// Other plugins/routes can then safely access fastify.config
await fastify.register(fastifyEnv, envOptions);
// Set logger level based on validated config
// Do this early so subsequent logs respect the level
fastify.log.level = fastify.config.LOG_LEVEL;
// Standard Fastify setup
// Place here your custom code! (e.g., other plugins like Helmet, Rate Limit)
// Do not touch the following lines provided by fastify-cli
// This loads all plugins defined in plugins
// those should be support plugins that are reused
// through your application
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'plugins'),
options: Object.assign({}, opts) // Pass opts, which now includes fastify.config
})
// This loads all plugins defined in routes
// define your routes in one of these
fastify.register(AutoLoad, {
dir: path.join(__dirname, 'routes'),
options: Object.assign({}, opts) // Pass opts, including fastify.config
})
}
// Export the options for fastify-cli
module.exports.options = {
// Pass logger options: https://getpino.io/#/docs/api?id=options
// Use Fastify's default Pino logger, level set above from config
logger: true
}
Now, validated environment variables are accessible via fastify.config
throughout your application (e.g., in routes, plugins). If any required variable is missing or invalid on startup, @fastify/env
will throw an error immediately.
3. Implementing Core Functionality (Sinch Service)
Let's create a dedicated service to handle interactions with the Sinch SDK. This promotes separation of concerns.
Create services/sinchService.js
:
// services/sinchService.js
'use strict'
const { SinchClient } = require('@sinch/sdk-client');
// Note: For better testability and centralized logging/config,
// pass `fastify.log` and `fastify.config` into this service,
// perhaps during instantiation or via request decoration.
// This example accesses process.env directly for simplicity,
// assuming @fastify/env has already populated it via dotenv: true.
// Initialize Sinch Client using environment variables
// These should have been validated by @fastify/env already
const sinchClient = new SinchClient({
projectId: process.env.SINCH_PROJECT_ID,
keyId: process.env.SINCH_KEY_ID,
keySecret: process.env.SINCH_KEY_SECRET,
// The `region` parameter for the client might affect internal SDK defaults,
// but explicitly setting the `baseUrl` in the API call (below) is often
// the most reliable way to target the correct regional API endpoint.
});
/**
* Sends an SMS message using the Sinch SDK.
* @param {string} recipientPhoneNumber - The full recipient phone number in E.164 format (e.g., +15551234567).
* @param {string} messageText - The text content of the SMS.
* @param {object} [logger=console] - Optional logger instance (defaults to console). Pass request.log for contextual logging.
* @returns {Promise<object>} - An object containing success status and the result from the Sinch API (e.g., batch ID).
* @throws {Error} - Throws an error if the SMS sending fails at the API level or due to configuration issues.
*/
async function sendSms(recipientPhoneNumber, messageText, logger = console) {
const senderNumber = process.env.SINCH_NUMBER;
const region = process.env.SINCH_REGION; // Used to construct the base URL
// Basic validation (though route schema should catch most issues)
if (!recipientPhoneNumber || !messageText) {
throw new Error('Recipient phone number and message text are required.');
}
if (!senderNumber) {
// This should ideally be caught by @fastify/env on startup
logger.error('Sinch sender number (SINCH_NUMBER) is not configured.');
throw new Error('Internal configuration error: Sinch sender number missing.');
}
if (!region) {
// This should ideally be caught by @fastify/env on startup
logger.error('Sinch region (SINCH_REGION) is not configured.');
throw new Error('Internal configuration error: Sinch region missing.');
}
// Construct the correct base URL for the Sinch SMS API based on the region.
// This is crucial for routing the request correctly.
// Refer to Sinch documentation for exact regional endpoints:
// https://developers.sinch.com/docs/sms/api-reference/regional-availability/
const baseUrl = `https://${region}.sms.api.sinch.com`;
logger.info(`Attempting to send SMS via Sinch from ${senderNumber} to ${recipientPhoneNumber} via region ${region} (${baseUrl})`);
try {
// Use the 'batches' endpoint for sending SMS via the SDK
const response = await sinchClient.sms.batches.send(
// smsSendBatchRequest payload:
{
to: [recipientPhoneNumber],
from: senderNumber,
body: messageText,
// Optional parameters can be added here (e.g., delivery_report: 'summary', client_reference: 'your_unique_id')
},
// RequestOptions: Explicitly setting the `baseUrl` here overrides any SDK default
// and ensures the request hits the correct regional API endpoint. This is recommended
// as SDK behavior regarding the client's `region` parameter might vary.
{
baseUrl: baseUrl,
}
);
// The exact structure of the success response might vary slightly based on SDK version.
// Check the SDK documentation or log the response during development.
// A `batch_id` is typically present on successful submission.
logger.info({ sinchResponse: response }, 'Sinch API Response Received');
if (response?.batch_id) {
logger.info(`SMS batch submitted successfully. Batch ID: ${response.batch_id}`);
// Return a consistent success object
return { success: true, batchId: response.batch_id, details: response };
} else {
// This case might indicate an unexpected successful (e.g., 2xx) response format from Sinch
logger.warn({ sinchResponse: response }, 'Sinch API response successful but missing expected batch_id.');
// Treat as failure since we can't confirm the batch ID
throw new Error('Sinch API response did not contain the expected batch_id.');
}
} catch (error) {
// Log the detailed error from the Sinch SDK/API
// error.response often contains details from the API response on HTTP errors
logger.error({
err: error,
responseData: error?.response?.data,
responseStatus: error?.response?.status
},
'Error sending SMS via Sinch'
);
// Re-throw a more context-specific error for the route handler to catch
// Avoid leaking raw Sinch error details unless necessary/safe
const errorMessage = error?.response?.data?.error?.text || // Sinch specific error text
error?.response?.data?.message || // General error message
error.message; // Fallback error message
throw new Error(`Failed to send SMS via Sinch: ${errorMessage}`);
}
}
module.exports = {
sendSms
};
Explanation:
- Import SDK: Imports
SinchClient
. - Instantiate Client: Creates
SinchClient
using credentials fromprocess.env
(populated and validated by@fastify/env
). sendSms
Function:- Accepts
recipientPhoneNumber
,messageText
, and an optionallogger
. Defaults toconsole
but should ideally receiverequest.log
. - Retrieves
senderNumber
andregion
fromprocess.env
. Includes checks, though@fastify/env
should prevent these errors at runtime if configured correctly. - Constructs the regional
baseUrl
. This is critical. - Uses the passed
logger
(orconsole
) for logging. - Calls
sinchClient.sms.batches.send()
. - Passes the
to
,from
,body
in the first argument (payload). - Crucially, passes
{ baseUrl: baseUrl }
as the second argument (RequestOptions) to explicitly target the correct regional Sinch API endpoint. - Error Handling: Uses
try...catch
to capture errors. Logs detailed error information using the logger. Throws a new, cleaner error for the route handler. - Success Response: Logs success, checks for
batch_id
, and returns a structured object{ success: true, batchId: ..., details: ... }
. Throws an error ifbatch_id
is missing even on a seemingly successful call.
- Accepts
4. Building the API Layer (Fastify Route)
Now, let's create the Fastify route that will use our sinchService
.
Modify routes/sms/index.js
(or create it):
// routes/sms/index.js
'use strict'
const sinchService = require('../../services/sinchService'); // Adjust path if needed
// Schema for request body validation using Fastify's built-in JSON Schema support
const sendSmsBodySchema = {
type: 'object',
required: ['to', 'message'],
properties: {
to: {
type: 'string',
description: 'Recipient phone number in E.164 format (e.g., +15551234567)',
// E.164 regex: Starts with +, then 1-9, then 1 to 14 digits.
pattern: '^\\+[1-9]\\d{1,14}$'
},
message: {
type: 'string',
description: 'The text message content',
minLength: 1,
maxLength: 1600 // Max length for concatenated SMS; adjust as needed.
}
},
additionalProperties: false // Disallow properties not defined in the schema
};
// Schema for the success response (2xx)
const successResponseSchema = {
type: 'object',
properties: {
success: { type: 'boolean', const: true },
message: { type: 'string' },
batchId: { type: 'string', description: 'Sinch Batch ID for the sent message(s)' }
}
};
// Schema for generic error responses (e.g., 4xx, 5xx)
const errorResponseSchema = {
type: 'object',
properties: {
success: { type: 'boolean', const: false },
message: { type: 'string' },
// Optionally include error code or details in non-production environments
// error: { type: 'string' }
}
};
// Combine response schemas for documentation/validation
const sendSmsResponseSchema = {
200: successResponseSchema, // Use specific code for success
// Define schemas for expected error codes for better API contracts
400: errorResponseSchema, // Validation errors (handled by Fastify)
500: errorResponseSchema // Server/Service errors
};
module.exports = async function (fastify, opts) {
// Route definition with schema validation and response schema documentation
fastify.post('/send', {
schema: {
description: 'Sends an SMS message via Sinch.',
tags: ['sms'],
summary: 'Send SMS',
body: sendSmsBodySchema,
response: sendSmsResponseSchema
}
}, async function (request, reply) {
// `request.body` is automatically validated against `sendSmsBodySchema` by Fastify.
// If validation fails, Fastify sends a 400 response automatically.
const { to, message } = request.body;
// Use the contextual logger from the request object
const log = request.log;
// Log securely - avoid logging full message content in production if sensitive
log.info({ recipient: to }, `Received request to send SMS`);
try {
// Call the service function, passing the contextual logger
const result = await sinchService.sendSms(to, message, log);
// If sinchService.sendSms completes without throwing, assume success based on its contract.
// The service already verified the presence of batchId or threw an error.
log.info({ batchId: result.batchId }, 'SMS batch submitted successfully via Sinch');
// Send a 200 OK response with the success payload
return reply.code(200).send({
success: true,
message: 'SMS submitted successfully.',
batchId: result.batchId
});
} catch (error) {
// Catch errors thrown by sinchService.sendSms or other unexpected issues
log.error({ err: error, recipient: to }, 'Error processing send SMS request');
// Send a 500 Internal Server Error for unexpected failures
// Avoid leaking sensitive internal error details to the client in production
const errorMessage = (process.env.NODE_ENV !== 'production')
? error.message
: 'Internal server error while attempting to send SMS.';
return reply.code(500).send({
success: false,
message: errorMessage
});
}
})
}
Explanation:
- Import Service: Imports the
sinchService
. - Schemas:
- Defines
sendSmsBodySchema
for request validation. The E.164 regex is corrected (pattern: '^\\+[1-9]\\d{1,14}$'
).additionalProperties: false
is added for stricter validation. - Defines
successResponseSchema
anderrorResponseSchema
. - Combines response schemas in
sendSmsResponseSchema
mapping them to HTTP status codes (e.g.,200
,400
,500
) for better documentation and potentially response validation.
- Defines
- Route Definition: Defines
POST /send
under the/sms
prefix (via AutoLoad). Attaches the schemas. - Handler Function:
- Extracts
to
andmessage
fromrequest.body
(already validated). - Uses
request.log
for contextual logging. - Calls
sinchService.sendSms
, passinglog
. - Simplified Success Handling: The
try...catch
block handles execution flow. Ifawait sinchService.sendSms
completes without throwing, it's considered a success according to the service's logic (which should throw on failure or missingbatchId
). - Catch Error: Logs the error using the request logger. Sends a
500 Internal Server Error
. It includes the specific error message only if not in production.
- Extracts
5. Error Handling, Logging, and Retry Mechanisms
Error Handling:
- Validation Errors: Handled automatically by Fastify schemas (
400 Bad Request
). - Service Errors (
sinchService.js
): Catches Sinch API errors, logs details, throws a standardized error. - Route Errors (
routes/sms/index.js
): Catches errors from the service call, logs them, returns a500 Internal Server Error
to the client (with generic message in production). - Configuration Errors: Handled on startup by
@fastify/env
.
Logging:
- Fastify Logger (Pino): Used via
fastify.log
(global) andrequest.log
(contextual). - Log Levels: Configured via
LOG_LEVEL
env var (validated by@fastify/env
).info
for production,debug
/trace
for development. - Structured Logging: Pino outputs JSON logs, suitable for log aggregation systems.
- Contextual Logging: Passing
request.log
to services allows tracing logs back to specific requests. - What to Log: Incoming requests (mask sensitive data), service calls, Sinch responses (
batchId
), errors (with stack traces in dev).
Retry Mechanisms (Basic Considerations):
Implementing retries for SMS requires care to avoid duplicates.
- When to Retry: Only for transient issues: network errors, Sinch
429 Too Many Requests
, Sinch5xx
server errors. Do not retry4xx
client errors (validation, auth, invalid number). - Idempotency: Crucial for retries. Use the
client_reference
parameter in the Sinchbatches.send
request payload. Provide a unique ID for each logical message attempt. If you retry with the sameclient_reference
, Sinch can detect and prevent duplicate sends. Generate this ID in your route handler or service before the first attempt.// Inside sinchService.sendSms or route handler const uniqueMessageId = require('node:crypto').randomUUID(); // Generate unique ID // ... inside batches.send payload ... // sendBatchRequest: { // This is illustrative, the actual payload structure is simpler // ... other params // client_reference: uniqueMessageId, // } // Correct placement within the payload object: // { // to: [recipientPhoneNumber], // from: senderNumber, // body: messageText, // client_reference: uniqueMessageId, // Add it here // }
- Implementation: Use libraries like
async-retry
or implement a custom loop with exponential backoff (increasing delays) withinsinchService.js
, ensuring theclient_reference
is passed consistently for each retry attempt of the same message.
Example (Conceptual Retry in sinchService.js
using async-retry
):
// services/sinchService.js - Conceptual Retry Addition
// Ensure you install: npm install async-retry
const retry = require('async-retry');
const crypto = require('node:crypto'); // For unique client_reference
// Modify sendSms or create a wrapper function
async function sendSmsWithRetry(recipientPhoneNumber, messageText, logger = console) {
const uniqueMessageId = crypto.randomUUID(); // Generate unique ID for this message attempt
logger.info({ clientReference: uniqueMessageId }, 'Generated client_reference for idempotency');
return retry(
async (bail, attemptNumber) => {
// bail(error) is called to stop retrying on non-retryable errors
// Throwing an error triggers a retry if attempts remain
logger.info(`Attempt ${attemptNumber} to send SMS to ${recipientPhoneNumber} (Ref: ${uniqueMessageId})`);
const senderNumber = process.env.SINCH_NUMBER;
const region = process.env.SINCH_REGION;
// Basic validation (should be done before retry ideally)
if (!recipientPhoneNumber || !messageText || !senderNumber || !region) {
const missingConfigError = new Error('Internal configuration error detected before sending.');
logger.error(missingConfigError);
bail(missingConfigError); // Stop retrying on config issues
return; // Needed after bail
}
const baseUrl = `https://${region}.sms.api.sinch.com`;
try {
const response = await sinchClient.sms.batches.send(
{ // Payload
to: [recipientPhoneNumber],
from: senderNumber,
body: messageText,
client_reference: uniqueMessageId, // Use the same ID for all retries of this message
},
{ // RequestOptions
baseUrl: baseUrl,
}
);
logger.info({ sinchResponse: response, attempt: attemptNumber }, 'Sinch API Response Received');
if (response?.batch_id) {
logger.info(`SMS batch submitted successfully on attempt ${attemptNumber}. Batch ID: ${response.batch_id}`);
return { success: true, batchId: response.batch_id, details: response };
} else {
logger.warn({ sinchResponse: response, attempt: attemptNumber }, 'Sinch API response successful but missing batch_id.');
// Treat as potentially retryable internal issue or unexpected format
throw new Error('Sinch API response did not contain expected batch_id.');
}
} catch (error) {
const statusCode = error?.response?.status;
logger.warn({ err: error, status: statusCode, attempt: attemptNumber }, `Attempt ${attemptNumber} failed`);
// Decide if error is retryable
if (statusCode === 429 || (statusCode >= 500 && statusCode <= 599)) {
logger.info(`Retrying due to status code ${statusCode}...`);
throw error; // Throw error to trigger retry by async-retry
} else {
// Don't retry on other errors (4xx client errors_ config errors_ etc.)
logger.error(`Not retrying for status code ${statusCode || 'N/A'}. Bailing.`);
bail(error); // Stop retrying and pass the error up
// Note: bail() throws the error passed to it_ so no explicit throw needed here.
}
}
}_
{ // async-retry options
retries: 3_ // Number of retries (total attempts = retries + 1)
factor: 2_ // Exponential backoff factor
minTimeout: 1000_ // Minimum delay in ms
maxTimeout: 5000_ // Maximum delay in ms
onRetry: (error_ attemptNumber) => {
logger.warn(`Retrying SMS send (attempt ${attemptNumber}). Error: ${error.message}`);
},
}
);
}
// Remember to update the route handler to call sendSmsWithRetry instead of sendSms
// And update the module exports if needed
// module.exports = { sendSms: sendSmsWithRetry }; // Or export both
module.exports = { sendSms, sendSmsWithRetry }; // Example: export both
Note: Implement retries carefully. Understand Sinch's idempotency features (client_reference
) and potential costs.
6. Database Schema and Data Layer (Not Applicable)
This guide focuses solely on the immediate action of sending an SMS via an API call. Therefore, a database is not required for the core functionality described.
If your application needed features like:
- Storing historical message logs.
- Tracking SMS delivery status updates (received via Sinch Webhooks).
- Managing user accounts or API keys associated with sending.
- Implementing message queuing for delayed or bulk sending.
You would introduce a database (e.g., PostgreSQL, MongoDB) and a corresponding data access layer (using an ORM like Prisma, Sequelize, or native drivers). This is beyond the scope of this basic guide.
7. Adding Security Features
Securing your API is crucial.
-
Input Validation:
- Fastify Schemas: Already implemented in Section 4. This is the first line of defense against malformed requests and basic injection attempts.
-
Secrets Management:
- Local: Use
.env
(and.gitignore
). - Production: Use your platform's secrets management (AWS Secrets Manager, GCP Secret Manager, Vault, Kubernetes Secrets, CI/CD injected variables). Never commit secrets.
- Local: Use
-
Rate Limiting: Protect against abuse and control costs.
- Dependency
@fastify/rate-limit
was installed in Section 1. - Register the plugin in
app.js
(usually after@fastify/env
but before routes):
// app.js // ... other requires const fastifyRateLimit = require('@fastify/rate-limit'); const fastifyHelmet = require('@fastify/helmet'); // Import helmet module.exports = async function (fastify, opts) { // ... register @fastify/env first ... await fastify.register(fastifyEnv, envOptions); fastify.log.level = fastify.config.LOG_LEVEL; // Set log level // Register Rate Limiting globally await fastify.register(fastifyRateLimit, { max: 100, // Max requests per timeWindow per key (default is IP) timeWindow: '1 minute', // Time window as string or milliseconds // Consider using a persistent store like Redis for multi-instance deployments // redis: new Redis({ host: '127.0.0.1' }), // keyGenerator: function (request) { /* custom key logic */ } }); // Register Helmet // Note: Register Helmet *after* rate-limit if rate-limit needs to identify clients before headers are potentially modified. // Usually, registering Helmet early is fine. await fastify.register(fastifyHelmet, { contentSecurityPolicy: false // Disable CSP or configure it properly if needed // Enable other recommended headers by default }); // ... autoload plugins and routes ... // fastify.register(AutoLoad, ...) // Load plugins defined in plugins/ // fastify.register(AutoLoad, ...) // Load routes defined in routes/ }
- Dependency
-
Security Headers (Helmet): Protect against common web vulnerabilities.
- Dependency
@fastify/helmet
was installed in Section 1. - Register the plugin in
app.js
(see rate limiting example above). It adds headers likeX-Frame-Options
,Strict-Transport-Security
,X-Content-Type-Options
, etc., by default. Review and configure Helmet options as needed for your specific application, especiallycontentSecurityPolicy
.
- Dependency