Frequently Asked Questions
Use the Sinch MMS JSON API integrated with a NestJS service. Create a NestJS service that interacts with the Sinch API, define DTOs for data validation, and expose an API endpoint to trigger sending MMS messages. Follow the steps in the guide to set up the project and dependencies, create the service and controller, and load Sinch credentials from environment variables.
It's a specific Sinch API endpoint ('sendmms' action) used for sending multimedia messages programmatically. The API allows detailed configuration of MMS content, including images, videos, audio, contacts, and more, along with options for fallback SMS and delivery settings.
NestJS provides a structured, scalable, and maintainable way to build server-side applications in Node.js using TypeScript. Its modular architecture, dependency injection, and built-in tooling make it ideal for integrating with third-party APIs like Sinch.
Obtain your Sinch API Token, Service ID, and MMS-enabled 'From' number from the Sinch Dashboard. Store these securely in a .env file. In your NestJS application, use the @nestjs/config package to load these credentials into the MmsService, where they will be used to authenticate and make requests to the Sinch API. Remember to never commit the .env file to version control.
Implement robust error handling in your NestJS MMS service. Catch potential errors during the API call using try-catch blocks. Use AxiosError type for handling errors specifically from the HTTP client. Log error details, including status codes, error messages, and potentially the failed request payload (with caution due to sensitive data).
Create a dedicated MMS module and service to encapsulate the interaction logic with Sinch. Inject HttpService and ConfigService. Define DTOs for request validation and transformation. Implement a sendMms method in the service to construct the API payload and make the HTTP request to Sinch. Handle API responses and errors gracefully.
DTOs (Data Transfer Objects) are classes that define the structure of data exchanged between layers of your application. They enhance code organization, validation, and data integrity. Use class-validator decorators to enforce rules on incoming data, ensuring requests to the Sinch API are correctly formatted.
class-validator provides decorators for data validation, ensuring data integrity and security. class-transformer facilitates transforming plain JavaScript objects into class instances (DTOs) and vice versa. These libraries help maintain the structure and correctness of data flowing through your application.
Use HTTP status code 202 (Accepted). Sending MMS is typically asynchronous; 202 signifies that Sinch has accepted the request, but delivery is not immediate and will be confirmed later (e.g., through webhooks).
Provide a fallback SMS message in case the recipient's device doesn't support MMS or if MMS delivery fails. Configure the 'fallback-sms-text' property in your API request to provide a short message. You can also control fallback behavior with 'disable-fallback-sms' and 'disable-fallback-sms-link' options.
It manages application configuration and environment variables securely. It loads variables from a .env file (which should never be committed to version control) and provides type-safe access to them via the ConfigService, keeping sensitive credentials out of your codebase.
Your Sinch Service ID (sometimes referred to as Project ID or Campaign ID) can be found in your Sinch Customer Dashboard. Navigate to the SMS & MMS section of your account. The ID is usually displayed prominently in the overview or API settings.
Yes, Prisma can be integrated for database logging of MMS attempts and tracking IDs. Add Prisma to your project and inject the PrismaService into the MmsService. You can then log details like recipient, tracking ID, status, and any errors that may occur, providing a history of MMS activity.
The 'client-reference' field is an optional parameter that allows you to include a custom identifier for the MMS message, such as an order ID or user ID. This helps you track messages and reconcile them with your internal systems.
Send Sinch MMS Messages with NestJS: A Developer Guide
Learn how to send MMS messages using Sinch API in your NestJS application. This comprehensive tutorial covers everything you need to build a production-ready multimedia messaging service: initial project setup, TypeScript implementation, request validation, error handling, security best practices, and deployment.
Whether you're building notification systems, marketing campaigns, or two-way multimedia messaging features, this guide shows you how to integrate Sinch MMS capabilities into your Node.js backend. By the end, you'll have a robust NestJS service that reliably sends MMS messages with images, videos, and rich media content.
What you'll learn:
What is Sinch MMS and Why Use It with NestJS?
Sinch MMS (Multimedia Messaging Service) enables you to send rich media messages—images, videos, audio files, and documents—to mobile devices via the Sinch platform. Unlike SMS, which is limited to text, MMS allows you to deliver engaging visual content that enhances user communication.
Why NestJS for Sinch MMS Integration?
NestJS is a progressive Node.js framework that provides a solid foundation for building scalable server-side applications. Its modular architecture, built-in dependency injection, TypeScript support, and extensive tooling make it ideal for implementing reliable Sinch API integrations with proper error handling and maintainability.
Project Overview and Goals
Goal: Create a NestJS backend service that exposes an API endpoint to send MMS messages via the Sinch platform.
Problem Solved: Programmatically send rich media messages (images, videos, audio, contacts) as part of your application's workflows – notifications, marketing campaigns, or user interactions – leveraging Sinch's MMS capabilities.
Technologies You'll Use:
sendmms
action) designed for sending individual MMS messages with detailed configuration options.@nestjs/axios
): A promise-based HTTP client for making requests to the Sinch API.@nestjs/config
: Manages environment variables and application configuration securely.class-validator
&class-transformer
: Provides robust request data validation and transformation.@nestjs/swagger
: Generates API documentation automatically.System Architecture:
Prerequisites:
Media File Size Best Practices: Keep media files under 500 KB to ensure reliable MMS delivery across all US carriers. While technical limits vary by carrier (AT&T: 1 MB, Verizon: 1.7 MB, T-Mobile: 3 MB), industry consensus recommends 300–500 KB for optimal deliverability (source: Bandwidth Support, verified January 2025). All carriers reliably handle messages up to 300 KB.
1. Set Up Your NestJS Project for Sinch MMS
Initialize a new NestJS project and install the necessary dependencies for Sinch API integration.
Create Your New NestJS Project: Open your terminal and run the NestJS CLI command:
Choose your preferred package manager (npm or yarn) when prompted.
Install Dependencies: Install modules for HTTP requests, configuration management, validation, and optionally Swagger and Prisma.
@nestjs/axios
&axios
: For making HTTP requests to the Sinch API.@nestjs/config
: Manages environment variables securely.class-validator
&class-transformer
: For validating incoming request payloads.@nestjs/swagger
&swagger-ui-express
: (Optional) For generating OpenAPI documentation.@prisma/client
&prisma
: (Optional) For database interactions if you choose to log messages.Initialize Prisma (Optional): If you plan to add database logging:
This creates a
prisma
directory with aschema.prisma
file and a.env
file.Configure Environment Variables: Create or update the
.env
file in your project root. Never commit this file to version control. Add your Sinch credentials and other necessary configurations:E.164 Format Requirements: E.164 is the ITU-T international standard (ITU-T Recommendation E.164) for phone number formatting. Numbers must start with
+
, followed by the country code (1–3 digits) and subscriber number (max 12 digits), for a maximum total of 15 digits. No spaces, parentheses, or dashes are allowed. Examples:+14151231234
(US),+442012341234
(UK). This format ensures correct international SMS/MMS routing (source: ITU-T E.164, Twilio E.164 Guide)..env
? Keeps sensitive credentials out of your codebase and allows different configurations per environment (development, staging, production).SINCH_BASE_URL
and the specific API endpoint path (used later inMmsService
) against the official Sinch documentation for your account and region, as these can differ.Load Configuration: Modify
src/app.module.ts
to load environment variables usingConfigModule
.isGlobal: true
: MakesConfigService
injectable in any module without needing to importConfigModule
explicitly everywhere.Review Project Structure: After completing the next steps, your structure will resemble:
2. Implement Sinch MMS Service in NestJS
Create a dedicated module and service to handle Sinch API interaction logic for sending MMS messages.
Generate MMS Module and Service: Use the NestJS CLI:
This creates
src/mms/mms.module.ts
andsrc/mms/mms.service.ts
.Define Data Transfer Objects (DTOs): Create DTOs to represent the data structure needed to send an MMS, including validation rules. Create a
src/mms/dto
directory.MMS Slide Technical Note: MMS messages use SMIL (Synchronized Multimedia Integration Language) to structure slide presentations. Each slide can contain up to two regions: an image/video region and a text region, plus optional audio. The 8-slide maximum is a common API provider limit; actual technical limits depend on total message size (typically 300–600 KB) rather than slide count (source: W3C SMIL, OMA MMS Specification).
class-validator
decorators for automatic validation, improving data integrity and security.@ApiProperty
is used for Swagger documentation.Implement MMS Service: Inject
HttpService
(from@nestjs/axios
) andConfigService
intoMmsService
. Implement thesendMms
method.firstValueFrom
converts the Observable returned byhttpService
into a Promise.sendMms
to returnPromise<SinchMmsSuccessResponse>
and added interfaces for better type safety.Update MMS Module: Import and configure
HttpModule
and makeMmsService
available for injection.HttpModule.registerAsync
? Allows configuringHttpModule
dynamically, potentially using values fromConfigService
(like timeouts).3. Create NestJS API Endpoint for Sending MMS
Expose MMS sending functionality via a REST API endpoint that clients can call to send multimedia messages.
Generate MMS Controller:
This creates
src/mms/mms.controller.ts
.Implement Controller Endpoint: Define a POST endpoint, inject
MmsService
, use the DTO for validation, and add Swagger decorators (optional).ValidationPipe
? Automatically validates the incoming request body againstSendMmsDto
rules.whitelist: true
removes properties not defined in the DTO,forbidNonWhitelisted: true
throws an error if extra properties are present, andtransform: true
attempts to convert plain objects to DTO instances.HttpStatus.ACCEPTED
? Sending an MMS is usually asynchronous. The API accepts the request, but delivery confirmation comes later (via webhooks, not covered in detail here). 202 reflects this.ValidationPipe Security Benefits: The combination of
whitelist: true
andforbidNonWhitelisted: true
provides critical security protection by preventing malicious users from injecting unexpected data into requests (mass assignment attacks). This configuration ensures only explicitly defined DTO properties are processed, reducing attack surface and maintaining application integrity (source: NestJS Official Documentation, verified January 2025).Enable Global Validation Pipe and Swagger (Optional): Modify
src/main.ts
to enable the validation pipe globally and set up Swagger.enableImplicitConversion
: This option inValidationPipe
can be convenient but may lead to unexpected type coercion if your DTO property types are not strictly defined (e.g., usingany
or union types). Ensure your DTOs are robust.Test with
curl
or Postman: Start your application:npm run start:dev
Use
curl
to test the endpoint (replace placeholders).Expected Response (Success - Status Code 202):
Expected Response (Validation Error - Status Code 400):
4. Configure Sinch API Credentials
This section details obtaining and configuring your Sinch credentials for MMS integration.
Obtain Sinch Credentials:
dashboard.sinch.com
).SINCH_SERVICE_ID
.SINCH_API_TOKEN
. Treat it like a password.+
and country code). This isSINCH_FROM_NUMBER
.Configure Environment Variables: As done in Step 1.4, place these values into your
.env
file:SINCH_BASE_URL
and the specific API endpoint path (e.g.,/v1/projects/{serviceId}/messages
) used inMmsService
against the official Sinch documentation for the MMS JSON API (sendmms
action) corresponding to your specific account and region. These values can vary.Secure API Keys:
.gitignore
: Ensure.env
is listed in your.gitignore
file to prevent accidental commits.5. How to Handle Errors in Sinch MMS Integration
Implement robust error handling to catch and respond to Sinch API errors gracefully.
Common Sinch API Errors:
Error Handling Strategy:
The
MmsService
implements centralized error handling in thehandleSinchApiError
method:BadRequestException
for client errors andInternalServerErrorException
for server errorsBest Practices:
6. Validate MMS Requests with class-validator
Use
class-validator
decorators in your DTOs to ensure all incoming MMS requests are properly validated.Key Validation Rules:
@IsPhoneNumber()
ensures E.164 format@IsUrl()
validates media URLs@ArrayMinSize()
and@ArrayMaxSize()
enforce slide count limits@MaxLength()
prevents oversized messages@IsNotEmpty()
ensures critical fields are presentWhy Validation Matters:
7. Secure Your Sinch MMS API
Implement security best practices to protect your MMS service and Sinch credentials.
Security Checklist:
.env
files to version controlwhitelist: true
andforbidNonWhitelisted: true
to prevent mass assignment attacks@nestjs/throttler
to prevent abuseRate Limiting Example:
8. Deploy Your NestJS MMS Application
Deploy your Sinch MMS service to production with Docker and proper configuration.
Build for Production:
Docker Deployment:
Create a
Dockerfile
:Build and run:
Deployment Considerations:
Frequently Asked Questions
How do I send MMS messages with Sinch and NestJS?
To send MMS messages with Sinch and NestJS, create a NestJS service that uses the Sinch MMS JSON API with the
sendmms
action. Configure your Sinch credentials in environment variables, implement DTOs for request validation, and use Axios to make HTTP POST requests to the Sinch API endpoint with your message payload including recipient number, slides with media URLs, and optional parameters.What is the Sinch MMS API endpoint?
The Sinch MMS API endpoint typically follows the pattern
https://mms.api.sinch.com/v1/projects/{serviceId}/messages
where{serviceId}
is your Sinch Service ID or Campaign ID. Always verify the exact endpoint URL in the official Sinch documentation as it may vary by region and account type.What file types are supported for Sinch MMS?
Sinch MMS supports various media types including images (JPEG, PNG, GIF), videos (MP4, 3GP), audio files (MP3, AAC), contacts (vCard), calendar events (iCal), and PDF documents. Each slide can contain one media file plus optional text. Keep files under 500 KB for optimal deliverability across all carriers.
How do I validate phone numbers for Sinch MMS?
Use the
@IsPhoneNumber()
decorator fromclass-validator
in your NestJS DTO to validate phone numbers in E.164 format. E.164 format requires a plus sign (+), country code, and subscriber number with no spaces or special characters (e.g., +15551234567 for US numbers). This prevents Sinch API errors caused by invalid phone number formatting.What is the maximum number of slides in a Sinch MMS?
Sinch MMS supports a maximum of 8 slides per message. Each slide can contain text (up to 5,000 characters) and one media file (image, video, audio, contact, calendar, or PDF). The total message size should stay under 500 KB for optimal deliverability across all US carriers.
How do I handle Sinch API authentication errors?
Sinch API authentication errors (HTTP 401/403) typically occur due to invalid API tokens or Service IDs. Verify your
SINCH_API_TOKEN
andSINCH_SERVICE_ID
in your.env
file match the credentials from your Sinch Dashboard. Ensure your API token has proper permissions for MMS messaging and hasn't expired.What is E.164 phone number format?
E.164 is the international standard for phone number formatting defined by ITU-T. It requires numbers to start with
+
, followed by the country code (1-3 digits) and subscriber number (up to 12 digits), for a maximum of 15 digits total. No spaces, parentheses, or dashes are allowed. Examples:+14151231234
(US),+442012341234
(UK).How do I test Sinch MMS integration locally?
Test your Sinch MMS integration locally by running
npm run start:dev
, then use curl or Postman to send POST requests tohttp://localhost:3000/mms/send
with a valid payload including recipient number, slides array with media URLs, and optional parameters. Monitor the console logs for Sinch API responses and any errors.Can I use Sinch MMS internationally?
Sinch MMS availability varies by country and carrier. Native MMS is primarily supported in the US and Canada. For international destinations, check Sinch documentation for specific country support and consider SMS fallback options which Sinch can automatically enable when MMS delivery fails.
How do I implement retry logic for failed Sinch MMS?
Implement retry logic using libraries like
async-retry
or queue systems like Bull/BullMQ. Only retry transient errors (network issues, temporary Sinch outages) and avoid retrying permanent failures (invalid numbers, authentication errors). Check Sinch error codes to determine if retrying is appropriate, and implement exponential backoff to prevent overwhelming the API.Related Resources