Frequently Asked Questions
Use the Sinch MMS JSON API with Express.js and Node.js to create an API endpoint that accepts requests for sending multimedia messages. This involves setting up a Node.js project, installing required dependencies like Axios and Express, and implementing a service to interact with the Sinch API.
The Sinch MMS JSON API, specifically the XMS API endpoint, allows developers to send multimedia messages programmatically. It handles requests containing recipient details, message content, and media URLs for sending MMS messages via the Sinch platform.
Sinch requires a publicly accessible media URL so its servers can directly fetch the media content (images, audio, video) to include in the MMS message. Ensure your media hosting server includes the Content-Length header for Sinch to process correctly.
Use the Sinch MMS API when you need to send rich media content like images, audio, or video along with your messages. SMS is limited to plain text, making MMS essential for marketing campaigns, notifications with visuals, or other communication needing more than text.
The article doesn't explicitly address international MMS. However, it does mention E.164 number formatting for the "SINCH_MMS_NUMBER" environment variable, implying international number support might be available. Consult the official Sinch documentation for details on supported countries and regions for sending international MMS messages.
Initialize a Node.js project using npm init, then install necessary packages such as express, axios, dotenv, and winston. Configure environment variables like SINCH_SERVICE_PLAN_ID and SINCH_API_TOKEN in a .env file to securely store your Sinch credentials.
Axios, a promise-based HTTP client, is used to make POST requests to the Sinch XMS API. It simplifies sending the MMS payload to Sinch and handles the API responses.
The example code provides error handling at multiple levels. Input validation using express-validator catches bad requests, authentication middleware handles unauthorized access, and a try-catch block in the Sinch service manages errors during API calls. Winston logs error details for debugging.
Winston provides structured logging with different levels (debug, info, warn, error), facilitating efficient debugging and monitoring. It's configured to log timestamps, stack traces, and specific error data for better insight into API interactions and potential issues.
You need a Sinch account with an active MMS API subscription, a provisioned phone number (Short Code, Toll-Free, or 10DLC) enabled for MMS, Sinch Service Plan ID and API Token, and a publicly accessible URL for your media file. Node.js and npm must also be installed.
Secure your integration by storing Sinch credentials as environment variables, never committing your .env file, and using a strong, random API key for authentication (INTERNAL_API_KEY) to protect your Express API endpoint. Use HTTPS and consider rate limiting with express-rate-limit and security headers with Helmet.
The article recommends creating separate directories for routes, controllers, services, middleware, and configuration files. Place your main server logic in server.js. This structure promotes code organization and makes future updates or extensions easier.
The article doesn't specify Sinch's rate limits. Refer to the official Sinch documentation for details on rate limits, as exceeding them can lead to throttled or rejected requests. Consider implementing your own rate limiting using express-rate-limit.
The code uses axios-retry to automatically retry failed Axios requests to the Sinch API. It retries on network errors or 5xx server errors with exponential backoff (1s, 2s, 3s delays between retries), increasing resilience to temporary issues.
Send MMS with Sinch in Node.js Express: Complete Implementation Guide
Build a production-ready Node.js application using Express to send Multimedia Messaging Service (MMS) messages via the Sinch MMS JSON API. This guide covers project setup, core implementation, API creation, error handling, security, deployment, and verification.
By the end, you'll have a functional Express API endpoint that accepts requests to send MMS messages, including text and media content hosted at a public URL, using your Sinch account credentials.
What Will You Build with Sinch MMS?
Goal: Create a reliable backend service that sends MMS messages programmatically using Sinch.
Problem Solved: Automate sending rich media messages (images, audio, video) to users – essential for notifications, marketing, or user engagement requiring more than plain text SMS.
Technologies:
.env
file/batches
endpoint withmt_media
typeSystem Architecture:
Prerequisites:
Content-Type
header (e.g.,image/jpeg
,video/mp4
) and aContent-Length
header.Source: Sinch MMS Support Documentation
MMS File Size Limits and Best Practices:
Content-Type
header (e.g.,text/plain
,image/gif
,audio/mp3
,video/mp4
)Source: Sinch MMS Best Practices
Supported Media Types:
Source: Sinch MMS Sizes and Limitations
How Do You Set Up Your Sinch MMS Project?
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal and create a new directory for the project.
Initialize Node.js Project: Create a
package.json
file.Enable ES Modules: Use
import
/export
syntax by adding"type": "module"
to yourpackage.json
. Alternatively, rename all.js
files to.mjs
. Openpackage.json
and add:Install Dependencies: Install Express, Axios, dotenv, validation, rate limiting, security headers, logging, and retry libraries.
Install Development Dependencies: Install
nodemon
for automatic server restarts during development.Create Project Structure: Organize the code for better maintainability.
Configure
.gitignore
: Prevent sensitive files and unnecessary modules from version control.Set Up Environment Variables (
.env
): Store your sensitive credentials and configuration here. Never commit this file.PORT
: Port the Express server listens onNODE_ENV
: Environment type (development
,production
)SINCH_SERVICE_PLAN_ID
,SINCH_API_TOKEN
: Your credentials from the Sinch Dashboard (see Prerequisites)SINCH_MMS_NUMBER
: The Sinch phone number you send MMS from (E.164 format)SINCH_API_BASE_URL
: Base URL for the Sinch API region. Regional endpoints:us.sms.api.sinch.com
(US) oreu.sms.api.sinch.com
(EU). Choose based on your location and data protection requirements.INTERNAL_API_KEY
: Crucial: Replace the placeholder with a cryptographically secure random string. This key protects your API endpoint.LOG_LEVEL
: Controls logging verbositySource: Sinch SMS API Reference
Add npm Scripts: Add scripts to
package.json
for running the server.How Do You Implement the Sinch MMS Service?
We'll create a dedicated service to handle interactions with the Sinch MMS API, incorporating logging and retry logic.
src/config/logger.js
src/services/sinchService.js
Explanation:
winston
logger./batches
endpoint using the format{region}.sms.api.sinch.com/xms/v1/{service_plan_id}/batches
.axios
instance and configuresaxios-retry
to automatically retry requests on network errors or 5xx responses from Sinch, using exponential backoff. Logs retry attempts.sendMms
Function:/batches
endpoint. Key fields includeto
,from
,body.type
(must be"mt_media"
),body.url
,body.message
, andbody.parameters
(conditionally added).strict_validation
parameter enables validation against Sinch MMS channel best practices.Content-Type
andContent-Length
headers.parameters
ormessage
fields if not used.Content-Type
andAuthorization: Bearer
.logger.info
,logger.debug
,logger.warn
,logger.error
). Logs payload at debug level.sinchAxios
instance (with retry) to make thePOST
request.catch
block logs detailed error information and constructs a specific error message before re-throwing it.Source: Sinch Batches API Reference
How Do You Build the Express API for MMS?
Now, let's create the Express endpoint that will use our
sinchService
.src/middleware/authMiddleware.js
src/controllers/mmsController.js
src/routes/mmsRoutes.js
Explanation:
authMiddleware.js
): Checks forX-API-Key
header against.env
. Logs warnings if the key is missing or invalid.mmsController.js
):validationResult
to check for errors fromexpress-validator
. Returns 400 if invalid.sendMms
service function within atry...catch
block.202 Accepted
on success, including the service response.500 Internal Server Error
.mmsRoutes.js
):express-validator
.POST /api/mms/send
route.apiKeyAuth
, validation rules, then the controller.How Do You Integrate the Sinch MMS API?
Focus on the specific Sinch integration points.
Credentials:
SINCH_SERVICE_PLAN_ID
,SINCH_API_TOKEN
,SINCH_MMS_NUMBER
,SINCH_API_BASE_URL
in your.env
file (locally) and as secure environment variables in your deployment environment. Never commit.env
or hardcode credentials.API Endpoint:
${SINCH_API_BASE_URL}/xms/v1/${SINCH_SERVICE_PLAN_ID}/batches
.us.sms.api.sinch.com
(United States) oreu.sms.api.sinch.com
(European Union). Choose based on your location and data protection requirements.Source: Sinch SMS API Reference
Authentication:
Authorization: Bearer ${SINCH_API_TOKEN}
header insinchService.js
.Payload:
mt_media
type within the/batches
structure in your JSON payload. Set the type field tomt_media
for MMS messages.message
field of the body object.strict_validation
field to enable message validation against Sinch MMS channel best practices.Source: Sinch MMS Support Documentation
mediaUrl
publicly accessible via HTTP GET.Content-Length
header. Check usingcurl -I <your_media_url>
.Content-Type
header (e.g.,image/jpeg
,video/mp4
,audio/mp3
).Source: Sinch MMS Best Practices
Fallback Mechanism:
parameters.mms_fallback_text
field to control the SMS text if MMS fails.disable_fallback_sms_link
ordisable_fallback_sms
if needed.MMS Enablement (US Region):
Source: Sinch Batches API Documentation
How Do You Handle Errors and Implement Retries?
express-validator
in routesapiKeyAuth
middlewaresinchService.js
catch block with retries viaaxios-retry
catch
block handles service errorswinston
for structured, leveled logging (src/config/logger.js
)console.*
withlogger.*
axios-retry
insinchService.js
Frequently Asked Questions
What are the file size limits for Sinch MMS messages?
Keep media files under 1 MB – most MMS providers use this limit. Without transcoding, keep video and image files under 500 KB, with a maximum of 740 KB. With Sinch transcoding enabled, files under 1 MB work best. To estimate the final MMS size, multiply your file size by 1.37 and add 814 bytes for Base64 encoding headers that Sinch uses for MMS delivery.
Which media formats does Sinch support for MMS?
Sinch supports Images (GIF, JPG, PNG), Audio (MP3, WAV), Video (3GP, MP4, MPEG, MPG, AVI, WMV), and Text (TEXT/PLAIN). All media files must be served with a valid
Content-Type
header (e.g.,image/jpeg
,video/mp4
,audio/mp3
) and aContent-Length
header from publicly accessible URLs.How do you calculate Base64 encoding overhead for MMS?
Sinch delivers MMS messages in Base64 encoding. Calculate the final size by multiplying your file size by 1.37 and adding 814 bytes for headers. For example, a 500 KB image becomes approximately (500 KB × 1.37) + 814 bytes = 685.8 KB after encoding. This calculation helps ensure your media stays within the 1 MB MMS provider limit.
What is the mt_media type in Sinch API?
The
mt_media
type is a required field in the Sinch XMS API/batches
endpoint for sending MMS messages. Setbody.type
to"mt_media"
(mobile-terminated media message) to indicate you're sending MMS rather than plain SMS. This type enables thebody.url
field where you specify the publicly accessible media URL.How do you enable MMS functionality in the US region?
In the US region, contact your Sinch account manager to enable MMS functionality for your Service Plan ID. Verify in the Sinch dashboard (under "Numbers" → "Your Numbers") that your chosen phone number has MMS sending capabilities enabled before attempting to send MMS messages. This requirement is specific to the US region.
What headers must media URLs return for Sinch MMS?
Media URLs must return two required headers:
Content-Type
(e.g.,image/jpeg
,video/mp4
,audio/mp3
) to specify the media format, andContent-Length
to indicate file size. Test your media URL usingcurl -I <your_media_url>
to verify both headers are present before sending MMS messages.What are the regional endpoint differences for Sinch?
Sinch offers two regional endpoints:
us.sms.api.sinch.com
(United States) andeu.sms.api.sinch.com
(European Union). Choose based on your location and data protection requirements. Configure theSINCH_API_BASE_URL
environment variable with the appropriate regional endpoint. The full XMS API endpoint follows the format{region}.sms.api.sinch.com/xms/v1/{service_plan_id}/batches
.How do you implement retry logic for failed MMS sends?
Use the
axios-retry
plugin configured insinchService.js
to automatically retry failed requests. The implementation retries network errors or 5xx server responses from Sinch up to 3 times with exponential backoff (1s, 2s, 3s delays). The retry mechanism usesaxiosRetry.isNetworkOrIdempotentRequestError(error)
to determine which errors warrant retries, ensuring transient failures don't cause message delivery to fail.