Frequently Asked Questions
You can send MMS messages by creating a Node.js application with Express that uses the Sinch MMS JSON API. This involves setting up a project with dependencies like Axios and dotenv, configuring your Sinch credentials, and implementing an API endpoint to handle MMS requests. Refer to the provided code examples for a step-by-step guide.
The Sinch MMS JSON API is a specific Sinch API endpoint and protocol for sending multimedia messages. It's important to consult the official Sinch documentation for the most up-to-date details on its structure, authentication methods, and required parameters, as these may change.
Sinch offers multiple APIs, such as legacy APIs and a unified Messages API, to cater to different integration needs and preferences. This tutorial specifically uses the MMS JSON API for its dedicated MMS capabilities.
Use the Sinch MMS JSON API when you need to send multimedia messages (MMS) containing images, videos, or audio alongside text within your application. It's ideal for automating communication workflows requiring rich media.
While this guide utilizes Axios, you can potentially use other HTTP client libraries for Node.js, but you'll have to adapt the code to the respective client's API and usage patterns. Axios is recommended for its ease of use with promises.
Set up Sinch credentials by creating a .env file containing your SINCH_SERVICE_PLAN_ID
, SINCH_API_TOKEN
, and SINCH_NUMBER
. These are essential for interacting with the Sinch API. Never commit the .env file to version control, as it contains sensitive information.
The fallbackText
parameter provides the message content for a fallback SMS if the recipient's device cannot receive MMS or if MMS delivery fails. It's required unless fallback is explicitly disabled using disableFallbackSms
.
The MMS payload should be a JSON object with specific keys like 'to', 'from', 'message-subject', and 'slide'. The 'slide' key holds an array of slide objects. You must verify the correct structure according to the latest Sinch documentation for the MMS JSON API.
The provided code examples demonstrate error handling using try...catch blocks and status codes. The code logs detailed error information from Sinch, allowing you to identify the cause of failure. For production, enhance logging with tools like Pino and consider retry mechanisms with exponential backoff for transient errors.
The client-reference
parameter is an optional field where you can include your own internal reference ID for the message, up to a recommended maximum of 64 characters. This helps you track and identify messages within your system.
Implement retry mechanisms when you want to increase the resilience of your MMS sending. Retries are useful for transient errors like network issues or temporary Sinch API unavailability (5xx errors). Use exponential backoff to prevent overwhelming the API.
Verifying the official Sinch MMS API documentation is crucial because endpoint URLs, payload structures, and other API specifics may vary depending on factors like your account settings, region, and API version. Using outdated information can lead to integration errors.
Media (images, videos, etc.) are added using the 'slides' parameter. Each 'slide' object can have media specified as a URL. These media URLs must be publicly accessible and return a Content-Length header. Always consult the Sinch API documentation for correct slide structure.
Sending MMS with Node.js, Express, and Sinch
You'll build a production-ready Node.js application using the Express framework to send Multimedia Messaging Service (MMS) messages via the Sinch MMS JSON API. This guide covers everything from initial project setup to deployment and monitoring.
Important: Sinch offers multiple APIs (e.g., legacy APIs, unified Messages API). This guide focuses on a specific MMS JSON API structure. Always verify endpoints, payload structures, authentication methods, and specific behaviors against the current, official Sinch documentation relevant to your account and the specific API product version you are using. API details can change.
By the end of this tutorial, you will have a functional Express API endpoint capable of accepting MMS details (recipient number, media URLs, text) and dispatching the message through Sinch, including handling fallbacks to SMS.
Project Overview and Goals
Goal: To create a robust backend service that enables sending MMS messages programmatically using Sinch's dedicated MMS API.
Problem Solved: Provides a reliable way to integrate rich media messaging into applications, automating communication workflows that require images, videos, or other media alongside text. This is essential for marketing campaigns, transactional notifications with visual content, and customer engagement workflows that need multimedia support.
Technologies Used:
.env
file for secure credential management.System Architecture:
(Note: This is a simplified text-based representation.)
Prerequisites:
Content-Length
header.How to Set Up a Node.js Project for Sinch MMS Integration
Initialize your Node.js project and install the necessary dependencies.
Step 1: Create Project Directory
Open your terminal and create a new directory for the project, then navigate into it.
Step 2: Initialize Node.js Project
Initialize the project using npm. Accept the defaults or customize as needed.
This creates a
package.json
file.Step 3: Install Dependencies
We need Express for the server, Axios to make HTTP requests, and dotenv to handle environment variables. We'll also add
nodemon
as a development dependency for easier development.Step 4: Configure Environment Variables
Create a file named
.env
in the root of your project. This file will store your sensitive credentials and configuration. Never commit this file to version control.SINCH_SERVICE_PLAN_ID
: Found on your Sinch Customer Dashboard. The exact name and location might vary. ReplaceYOUR_SERVICE_PLAN_ID
with your actual ID.SINCH_API_TOKEN
: Found on the Sinch Customer Dashboard, often near the Service Plan ID configuration. ReplaceYOUR_API_TOKEN
with your actual token.SINCH_NUMBER
: A virtual number assigned to your Sinch account, capable of sending MMS. Use the E.164 international format (e.g.,+12223334444
). ReplaceYOUR_SINCH_PHONE_NUMBER
with your actual Sinch number.SINCH_API_BASE_URL
: The base URL for the Sinch MMS API. Crucially, verify the correct URL and structure in the official Sinch documentation. It can vary based on region, API version, and whether the Service Plan ID is part of the path. The example provided is common but requires verification. ReplaceYOUR_SERVICE_PLAN_ID
within the URL if this structure is correct for your API.PORT
: The port your Express server will listen on.Step 5: Set Up Project Structure
Create the following basic structure:
Create the
src
directory and the subdirectories/files within it.Step 6: Create
.gitignore
Create a
.gitignore
file in the project root to prevent committing sensitive files and unnecessary directories.Step 7: Add Run Scripts to
package.json
Modify the
scripts
section in yourpackage.json
:(Note: The
test
script is a placeholder. It will be updated in Section 13 when testing with Jest is introduced.)npm start
: Runs the application using Node.npm run dev
: Runs the application usingnodemon
, which automatically restarts the server on file changes.How to Implement the Sinch MMS Service Layer
This service will encapsulate the logic for interacting with the Sinch MMS API.
File:
src/services/sinchService.js
Explanation:
axios
anddotenv
. Loads environment variables and checks for essential Sinch credentials and the base URL, exiting if missing.sendmms
action based on theSINCH_API_BASE_URL
. Includes a prominent warning to verify this endpoint against official documentation.sendMms
Function:to
,from
,subject
,slides
) and optionalfallbackText
andoptions
.fallbackText
is present if fallback SMS is not explicitly disabled.payload
according to a common Sinch MMS JSON API specification. Includes a warning to verify the payload structure against official documentation. Handles common optional fields and cleans undefined values.axios.post
to send the request.Content-Type
andAuthorization
(Bearer token - verify this method).status: 'success'
andtracking-id
) as 200 OK might not guarantee acceptance. This check might need adjustment based on the specific API response structure.How to Build Express API Routes and Controllers for MMS
Now, let's create the Express route and controller to expose our MMS sending functionality.
File:
src/routes/mmsRoutes.js
File:
src/controllers/mmsController.js
Explanation:
mmsRoutes.js
): Defines a single POST route/api/mms/send
that maps to thehandleSendMms
controller function. Includes a commented-out example showing where validation middleware (Section 7) would go.mmsController.js
):sinchService
.SINCH_NUMBER
from environment variables to use as thefrom
number, exiting if not found.to
,subject
,slides
,fallbackText
, and optional fields likeclientReference
,disableFallbackSms
) from the request body (req.body
).express-validator
(Section 7) for robust validation in production.serviceOptions
object.sinchService.sendMms
with the extracted and validated data.tracking-id
).How to Configure Express Application with Sinch MMS Integration
Let's tie everything together in our main Express application file.
File:
src/app.js
File:
src/server.js
Explanation:
app.js
:app
).dotenv
early.pino-http
or similar for production),express.json()
for parsing JSON bodies, andexpress.urlencoded()
(optional).mmsRoutes
under the/api/mms
path prefix./health
check endpoint for monitoring.err, req, res, next
) to catch unhandled errors from routes ornext(error)
calls. It logs the error and sends a standardized JSON error response to the client, avoiding leaking stack traces in production.server.js
:app
fromapp.js
.dotenv
again (safe if already loaded) to ensure environment variables are available here too.PORT
andNODE_ENV
from environment variables (with defaults).app.listen
and stores the server instance.SIGTERM
, using the storedserver
instance.How to Implement Error Handling, Logging, and Retry Logic for MMS
We've built foundational error handling. Let's refine logging and consider retries.
Error Handling Strategy (Recap):
sinchService.js
: Catchesaxios
errors during the API call. Logs detailed Sinch API error responses. Throws a new, informativeError
object containing relevant details.mmsController.js
: Uses atry...catch
block to catch errors fromsinchService
. Logs a summary. Responds to the client with an appropriate HTTP status (400 for known client/API errors, 500 for unexpected internal errors) and a JSON error message derived from the caught error.app.js
(Global Handler): Catches any errors missed by route handlers or thrown unexpectedly. Logs the full stack trace (server-side) and sends a generic 500 response to the client.Logging Enhancements (Production):
Standard
console.log
/error
is okay for development, but insufficient for production. Use a dedicated, structured logging library likepino
.npm install pino pino-http
src/utils/logger.js
).pino-http
middleware inapp.js
for automatic request/response logging.console.log
/error
calls throughout your services and controllers withlogger.info()
,logger.warn()
,logger.error()
, etc. Pass error objects directly tologger.error(error, "Optional message")
for stack trace logging.Retry Mechanisms:
Network issues or temporary Sinch API unavailability (e.g., 5xx errors) can occur. Retrying failed requests can improve resilience.
axios-retry
simplifies this.Example using
axios-retry
:npm install axios-retry
src/services/sinchService.js
:(Note: The
axios-retry
example above is illustrative and requires careful integration with the existingsendMms
function, particularly regarding how the URL/endpoint is passed to thesinchApiClient.post
method based on whetherbaseURL
is set on the instance.)Frequently Asked Questions About Sinch MMS Integration
What Node.js version do I need for Sinch MMS integration?
You need Node.js 18 or later for this Sinch MMS implementation. As of January 2025, Node.js 22 (codenamed 'Jod') is the current LTS version recommended for production. Node.js 18.x reaches end-of-life on April 30, 2025 – plan to upgrade to Node.js 20 or 22 for continued support. This guide uses Express v5.x, which requires Node.js 18+ and includes security improvements and async error handling.
What are the MMS file size limits for Sinch API?
Sinch MMS supports up to 8 slides per message, with each slide containing text and/or one media type (image, audio, video). The recommended file size is under 500 KB for reliable delivery across all carriers. While most US and Canadian carriers accept up to 1 MB, carrier-specific limits vary: AT&T accepts up to 1 MB, Verizon up to 1.7 MB, and T-Mobile up to 3 MB. All media files must serve a valid
Content-Length
header and properContent-Type
headers (e.g.,image/jpeg
,video/mp4
).How do I authenticate with the Sinch MMS API?
Sinch MMS API uses Bearer token authentication. Include your API token in the
Authorization
header asBearer YOUR_API_TOKEN
. You'll also need your Service Plan ID (sometimes called Campaign ID), which may be included in the API endpoint path or request payload depending on your API version. Always verify the authentication method and endpoint structure in the official Sinch documentation for your specific account and region (US, EU, AU).What's the difference between Sinch MMS JSON API and XML API?
Sinch offers two MMS APIs: the XML API (industry standard for sending rich multimedia content with higher throughput) and the MM7 API (SOAP-based protocol used by carriers). This guide focuses on the JSON API, which sends MMS messages defined in JSON format to mobile numbers via HTTP POST requests. The JSON API requires UTF-8 encoded JSON data and supports slides with embedded text, images, videos, audio, and other objects.
How do I handle MMS delivery failures and fallback to SMS?
The Sinch MMS API includes automatic fallback to SMS when MMS delivery fails or is disabled by the recipient. Set
fallback-sms-text
in your payload with the SMS message to send if MMS fails. You can disable fallback by settingdisableFallbackSms: true
, though this is not recommended. Setdisable-fallback-sms-link: false
to include a link to view media in the fallback SMS. Implement delivery status webhooks to track message delivery and handle failures in your application logic.What error handling should I implement for Sinch MMS requests?
Implement comprehensive error handling for three scenarios: API errors (4xx/5xx status codes), network errors (timeouts, DNS failures), and request setup errors. Log detailed error information including Sinch API error responses. Use
axios-retry
with exponential backoff for transient errors (5xx, network issues) but don't retry 4xx client errors. Set reasonable timeouts (15 seconds recommended). Use structured logging (pino) in production. Implement global error handlers in Express to catch unhandled errors.How do I validate phone numbers and media URLs for MMS?
Validate that phone numbers use E.164 international format (starting with
+
, e.g.,+12223334444
) for both sender and recipient. Check that the recipient number is MMS-capable. Validate media URLs are publicly accessible and return properContent-Length
andContent-Type
headers. Verify file sizes are under carrier limits (500 KB recommended). Validate slide count (max 8), subject length (max 80 chars, 40 recommended), and text length (up to 1600 chars). Useexpress-validator
middleware for robust production validation.What's the recommended project structure for Sinch MMS integration?
Use a layered architecture:
services/
for business logic (Sinch API interaction),controllers/
for request/response handling,routes/
for API route definitions, andapp.js
for Express configuration. Separate concerns by keeping API logic in the service layer, validation in middleware, and HTTP handling in controllers. Store credentials in.env
files (never commit to version control). Use environment-specific configurations. Implement proper error boundaries at each layer.How do I test MMS sending in development without sending real messages?
Use Sinch's sandbox/test environment if available for your account. Mock the Sinch API responses using tools like
nock
ormsw
(Mock Service Worker) in your unit tests. Create integration tests that verify request payloads without calling the real API. Use Jest for testing withaxios-mock-adapter
to intercept HTTP requests. Implement feature flags to disable MMS sending in development. Log request payloads to verify correct message formatting before enabling production sends.What are the rate limits for Sinch MMS API?
Sinch MMS API rate limits vary by account and service plan. Each service plan has a maximum messages per second (MPS) setting, with default limits varying by account type. For batch messages with multiple recipients, each recipient counts toward the rate limit. Status query limits are typically 1 request per second per IP address (HTTP 429 if exceeded). Maximum API concurrency is often 700 requests per second per IP address. Check your specific rate limits in the Sinch Dashboard under your service plan details and contact Sinch support for higher volume adjustments.