Frequently Asked Questions
Integrate the Sinch Batch SMS API into your RedwoodJS application. This involves setting up environment variables for your Sinch credentials, creating database models for campaigns and contacts, and implementing RedwoodJS services to manage these entities and interact with the Sinch API. This guide provides a step-by-step tutorial for this integration process.
The Sinch Batch SMS API allows you to send bulk SMS messages programmatically within your RedwoodJS app, making it suitable for marketing campaigns. This guide focuses on integrating with the /xms/v1/{SERVICE_PLAN_ID}/batches endpoint, enabling automated campaign creation and targeted sending. Note that Sinch may offer dedicated Marketing Campaign APIs with additional features.
You can create a dedicated Sinch API client within your api/src/lib directory to handle the API interaction logic. Then import and call the client functions from your RedwoodJS services, specifically within the service responsible for managing and sending campaigns.
Prisma acts as an ORM (Object-Relational Mapper), simplifying database interactions within your RedwoodJS application. It allows you to define data models (like Contacts and Campaigns) and easily perform CRUD operations without writing raw SQL queries.
You primarily need services for managing campaigns and contacts. The campaign service handles creating, updating, and sending campaigns, while the contact service manages your contact list. These services interact with Prisma for database access and the Sinch client for sending SMS messages.
Create a .env file in the root of your RedwoodJS project. Add your SINCH_SERVICE_PLAN_ID, SINCH_API_TOKEN, SINCH_SENDER_ID, and SINCH_API_BASE_URL obtained from your Sinch dashboard to this file. Your .env file should already be in .gitignore for security.
GraphQL serves as the communication layer between the RedwoodJS frontend (web side) and backend (api side). You define GraphQL schemas (SDL) to specify data types and queries/mutations. RedwoodJS automatically generates resolvers that map these to your service functions.
Use the command yarn create redwood-app <project-name> --typescript in your terminal. The --typescript flag is recommended for better type safety. Then, navigate into the project directory using cd <project-name>.
While Node.js has a built-in fetch, using node-fetch@^2 explicitly ensures better CommonJS compatibility, particularly with the RedwoodJS api side. Install it with yarn workspace api add node-fetch@^2 and its types with yarn workspace api add -D @types/node-fetch@^2.
The example uses SQLite for simplicity, but you can configure PostgreSQL or MySQL in your schema.prisma file. The DATABASE_URL in your .env file controls the database connection. For local SQLite, use DATABASE_URL="file:./dev.db".
The provided sinchRequest helper function in the Sinch client includes basic error handling and logging. It attempts to parse error responses from Sinch to provide more detailed messages for debugging. Always avoid exposing raw Sinch errors to the frontend if possible.
Yes, you can use a registered phone number, short code, or alphanumeric sender ID approved by Sinch. Set the SINCH_SENDER_ID environment variable in your .env file. This value is then used in the from field of the API request.
The Sinch Service Plan ID is a unique identifier that specifies the service plan you're using within the Sinch platform. It's required to make authenticated requests to the Sinch API and is included in the API endpoint URL.
Integrate Sinch Batch SMS API with RedwoodJS for Marketing Campaigns
Learn how to build a complete SMS marketing system by integrating the Sinch Batch SMS API with your RedwoodJS application. This step-by-step tutorial covers campaign creation, contact management, bulk SMS sending, and database setup using GraphQL and Prisma ORM.
This RedwoodJS SMS integration tutorial provides programmatic control over SMS marketing campaigns with automated message creation, targeted bulk sending, and centralized management. We'll use the Sinch Batch SMS API endpoint (
/xms/v1/{SERVICE_PLAN_ID}/batches) for sending marketing messages to multiple recipients. For advanced features like audience segmentation or detailed analytics, consult the official Sinch SMS API documentation.Technologies Used:
System Architecture:
What You'll Build:
CampaignandContactdataNote: This guide focuses on backend implementation. UI components (pages, cells) for campaign management are outlined but require additional implementation for production use. Consider adding monitoring, analytics tracking, and comprehensive error recovery for production deployments.
Prerequisites:
Important: SMS messaging incurs costs. Review Sinch pricing and set up spending alerts before sending production messages. This guide assumes a new RedwoodJS project – adapt steps for existing projects.
1. RedwoodJS Project Setup for SMS Integration
Create a new RedwoodJS application and configure environment variables for Sinch API authentication.
Create RedwoodJS App: Open your terminal and create the project named
redwood-sinch-campaigns:The
--typescriptflag initializes the project with TypeScript for type safety.Navigate to Project Directory:
Environment Variables Setup: Create a
.envfile in the project root for your Sinch credentials:Add the following variables, replacing placeholders with your actual Sinch credentials:
Variable Explanations:
SINCH_SERVICE_PLAN_ID: Unique identifier for your Sinch service planSINCH_API_TOKEN: Secret authentication token (treat like a password)SINCH_SENDER_ID: Registered phone number, short code, or alphanumeric sender ID approved by SinchSINCH_API_BASE_URL: Base URL for Sinch REST API (adjust for your region: us, eu, etc.)DATABASE_URL: Database connection string (adjust provider inschema.prisma)Security Best Practices:
.envis in your.gitignorefile (RedwoodJS adds this by default)Install Dependencies: Install
node-fetchfor HTTP requests to the Sinch API. While Node.js includes built-in fetch, explicitly addingnode-fetchensures compatibility across versions:yarn workspace api add: Installs packages for the API side onlynode-fetch@^2: Version 2 for CommonJS compatibility@types/node-fetch@^2: TypeScript typingsProject Structure Overview:
Backend (
api/):api/db/schema.prisma: Database schema definitionapi/src/functions/: Serverless function handlers (GraphQL endpoint)api/src/graphql/: GraphQL schema definitions (*.sdl.ts)api/src/services/: Business logic implementationsapi/src/lib/: Utility functions and third-party clientsFrontend (
web/):web/src/pages/: Page componentsweb/src/components/: Reusable UI components (including Cells)web/src/layouts/: Layout componentsweb/src/Routes.tsx: Frontend routingConfiguration:
.env: Environment variables (Git-ignored)redwood.toml: Project configuration2. Database Schema and Service Implementation
Design Prisma database models for contacts and campaigns, then implement RedwoodJS services for business logic.
Define Database Schema: Open
api/db/schema.prismaand add models forContactandCampaign:Schema Notes:
+15551234567)sinchBatchIdstores the ID returned by Sinch for trackingCampaign.statusimproves query performanceApply Database Migrations: Create and apply a database migration based on the schema changes:
This command creates a new SQL migration file in
api/db/migrations/, applies the migration to your development database, and generates/updates the Prisma Client.Generate Services: Generate boilerplate code for services that handle business logic:
This creates
api/src/services/contacts/contacts.ts,api/src/services/campaigns/campaigns.ts, and corresponding test/scenario files.Implement Service Logic (Basic CRUD): Open the generated service files and add basic CRUD operations.
api/src/services/contacts/contacts.ts:Production Recommendations: Implement E.164 phone number validation using a library like
libphonenumber-js. Add duplicate detection and merge logic for contacts with existing phone numbers.api/src/services/campaigns/campaigns.ts:Production Recommendations: Add pagination, filtering, and sorting capabilities for the campaigns query. Implement cursor-based pagination for large datasets.
Why RedwoodJS Services? Services encapsulate business logic, making your SMS marketing code modular, testable, and reusable. They bridge the GraphQL API layer with Prisma database operations and external API integrations like Sinch. For more on RedwoodJS architecture, see the official RedwoodJS documentation.
Data Layer Summary:
ERD (Simplified):
db.campaign.findMany(),db.contact.create(), etc.). Redwood'sdbobject is an instance ofPrismaClient.yarn rw prisma migrate dev. For production, useyarn rw prisma migrate deploy.Seed Sample Data (Optional): Use Prisma seeds to populate your development database.
Create seed file:
Add seed logic:
Configure the seed command in
prismasection of rootpackage.jsonif not present:Run seeding:
3. GraphQL API Layer Configuration
Define GraphQL schemas (SDL) to expose campaign and contact operations through RedwoodJS's type-safe API layer.
Generate GraphQL SDL: Generate SDL files based on your Prisma schema models:
The
--crudflag generates standard GraphQL types, queries, and mutations based on the model and corresponding service functions.Review and Customize SDL: Inspect the generated files (
api/src/graphql/contacts.sdl.tsandapi/src/graphql/campaigns.sdl.ts). Customize as needed:api/src/graphql/contacts.sdl.ts:Enhancement Opportunity: Implement custom GraphQL scalar types for E.164 phone number validation. Add field-level documentation using GraphQL description strings.
api/src/graphql/campaigns.sdl.ts:@requireAuth: RedwoodJS directive for enforcing authentication on GraphQL operations. Configure RedwoodJS Authentication (yarn rw setup auth ...) before production deployment. During development, you can temporarily remove this directive, but always restore it for security.SendCampaignResponse&sendCampaignMutation: Custom mutation to trigger campaign sending logic in the service.Testing API Endpoints (GraphQL Playground):
Start the development server:
Open your browser to
http://localhost:8910/graphql(or the port specified in the console output). Test your queries and mutations.Example Query (Get Campaigns):
Example Mutation (Create Campaign):
Note:
@requireAuthmight block requests if auth isn't configured. Remove it from the SDL temporarily for testing if needed, but ensure it's present for production.4. Sinch Batch SMS API Integration
Implement a Node.js client to send bulk SMS messages using the Sinch API's
/batchesendpoint.Create Sinch Client Library: Create a new file for Sinch API interaction logic:
Implement Sinch API Client Logic: Open
api/src/lib/sinchClient/index.tsand add the code to interact with Sinch:Key Features:
process.envsinchRequesthelper function handling authentication, headers, request/response logging, and error handling for all Sinch API callssendSinchSmsBatchto interact with the/batchesendpoint for sending messages to multiple recipientsProduction Recommendations: Implement retry logic with exponential backoff, rate limiting to respect Sinch API quotas, and circuit breaker patterns for fault tolerance. Consider using libraries like
axios-retryorp-retryfor robust SMS delivery. For more on SMS API best practices, see our guide on bulk SMS broadcasting.Obtaining Sinch Credentials:
.envfileus.sms.api.sinch.com,eu.sms.api.sinch.com)Troubleshooting Tips:
Connect Sinch Client to Campaign Service: Update the
sendCampaignfunction inapi/src/services/campaigns/campaigns.tsto use the Sinch client:Note: Complete implementation of
sendCampaignfunction with full error handling, transaction management, delivery tracking, and UI components requires additional sections (5–8) covering frontend implementation, testing strategies, production deployment, monitoring setup, and comprehensive troubleshooting guides. Implement these features before production use.Next Steps for Production SMS Marketing
To deploy a production-ready RedwoodJS SMS marketing platform: