Frequently Asked Questions
You can send SMS messages with RedwoodJS by integrating with an SMS API provider like Infobip. This involves setting up a RedwoodJS project, installing an HTTP client like Axios, creating a service to handle SMS sending logic, and exposing this functionality through a GraphQL API. This setup allows you to trigger SMS messages programmatically within your RedwoodJS application.
RedwoodJS acts as the full-stack framework for building the SMS marketing application. It handles the user interface, API interactions, business logic, and database connections. RedwoodJS offers a productive environment for developing and deploying such applications by streamlining common web development tasks.
Infobip is a global cloud communication platform with a powerful SMS API that enables sending messages programmatically. It provides infrastructure and tools for reliable SMS delivery, making it a suitable choice for businesses needing scalable SMS solutions.
Integrate Infobip by obtaining your API Key and Base URL from the Infobip portal and placing them into a `.env` file in your project root, along with the desired sender ID. Then, install an HTTP client library like Axios and use it within a RedwoodJS service to make requests to the Infobip API endpoints.
Environment variables should be used for sensitive data, such as API keys, database connection URLs, and session secrets. Storing these in `.env` files keeps them out of your codebase and allows for different values across various environments (development, staging, production), enhancing security.
Implement comprehensive error handling using `try...catch` blocks to trap errors during API calls and other operations. Log errors with Redwood's logger, providing context like status codes and timestamps. Consider retry mechanisms for transient network issues to improve resilience.
RedwoodJS uses Prisma, an ORM, which allows flexibility with different databases. PostgreSQL is recommended for production environments due to its scalability and features. SQLite is used by default for development due to its ease of setup.
Prisma is a next-generation ORM (Object-Relational Mapper) for Node.js and TypeScript. It simplifies database interactions within RedwoodJS applications. Developers define their data models in a schema file (`schema.prisma`), and Prisma generates type-safe client code for database access, improving developer experience and code safety.
Create a new RedwoodJS project using the command `yarn create redwood-app ./redwood-infobip-sms --typescript`. This initializes a RedwoodJS application with TypeScript support. Add the `--typescript` flag to start with TypeScript.
A RedwoodJS service for Infobip integration should handle the core SMS sending logic, including API calls, data validation, error handling, and logging. It should also include appropriate retry mechanisms for resilience and security measures such as safe storage of API credentials.
The GraphQL schema (SDL) defines the API for your RedwoodJS application. It specifies the available queries and mutations, their input types, and the expected output types. This contract between the front-end and back-end facilitates communication and data exchange.
Test GraphQL APIs using Redwood's built-in GraphQL Playground, accessible at `http://localhost:8911/graphql` in the development environment. You can execute queries and mutations directly within the Playground to verify functionality and data retrieval.
Infobip API keys are generated within your Infobip account portal. Navigate to the API Key management section, usually located within the developer settings or account area. Create a new API key and securely store it for use in your RedwoodJS project.
The tutorial provides a mechanism for overriding the default `INFOBIP_SENDER_ID` within each campaign. This allows using different Sender IDs (numbers or shortcodes) for various campaigns, as long as they comply with Infobip's registration and compliance requirements.
This guide provides a step-by-step walkthrough for building a RedwoodJS application capable of sending SMS marketing campaigns using the Infobip API. We will cover project setup, core SMS sending functionality, API integration, database modeling, error handling, security, testing, and deployment.
By the end of this tutorial, you will have a functional RedwoodJS application that can define simple SMS campaigns and send messages to a list of recipients via Infobip, along with the foundational knowledge to extend its capabilities.
Project Overview and Goals
What We're Building:
We are building a full-stack application using RedwoodJS that allows users (potentially administrators or marketers) to:
Problem Solved:
This application provides a basic framework for businesses needing to programmatically send targeted SMS messages for marketing or notifications, leveraging a robust provider like Infobip within the productive RedwoodJS ecosystem.
Technologies:
System Architecture:
Prerequisites:
Expected Outcome:
A RedwoodJS application where you can trigger an API mutation (e.g., via the GraphQL playground) to send a predefined SMS message to a list of phone numbers using your Infobip account.
1. Setting up the Project
Let's initialize our RedwoodJS project and configure the essential components.
Create RedwoodJS App
Open your terminal and run the following command to create a new RedwoodJS project. We'll use TypeScript.
Navigate to Project Directory
Environment Variables
RedwoodJS uses
.env
files for environment variables. Create a.env
file in the project root..env
(Git-ignored, for sensitive local development keys):.env.defaults
(Committed to Git, for non-sensitive defaults):Purpose: Using
.env
keeps sensitive credentials like API keys out of your codebase and version control..env.defaults
provides non-sensitive defaults. Redwood automatically loads these. Ensure.env
is listed in your.gitignore
.Database Configuration (Prisma)
The database connection is defined by
DATABASE_URL
in.env
. The schema is inapi/db/schema.prisma
. We'll define models later.Initialize Database
Apply the initial Prisma schema to create the database (for SQLite) or ensure connection (for PostgreSQL).
schema.prisma
and generates the Prisma Client.2. Implementing Core Functionality (SMS Service)
The core logic for interacting with Infobip will reside in a RedwoodJS service.
Install HTTP Client
We need
axios
to make HTTP requests to the Infobip API.Generate Campaign Service
Use Redwood's generator. We use
--crud
to quickly scaffold the service file, tests, and SDL, even though we'll replace the initial CRUD functions with our custom logic first.api/src/services/campaigns/campaigns.ts
,campaigns.test.ts
,campaigns.sdl.ts
, and related files. We will modify these.Implement SMS Sending Logic
Open
api/src/services/campaigns/campaigns.ts
. Replace the generated CRUD function placeholders with a function to send SMS via Infobip. We will add database-interacting functions later.axios
for HTTP, follows Infobip API structure, includes basic validation, logging, and error handling.3. Building the API Layer (GraphQL)
Expose backend functionality via GraphQL.
Define GraphQL Schema (SDL)
Modify
api/src/graphql/campaigns.sdl.ts
to define the mutation and its input/output types.@requireAuth
: Ensures only authenticated users can call this. Set up Redwood Auth (e.g.,dbAuth
) or remove temporarily for initial testing without auth.Link Service to Mutation
Rename the service function to match the mutation name (
sendSms
).api/src/services/campaigns/campaigns.ts
, renamesendSmsViaInfobip
tosendSms
.Testing with GraphQL Playground
yarn rw dev
http://localhost:8911/graphql
.4. Integrating with Infobip (Configuration Details)
Details on obtaining and managing Infobip credentials.
Obtaining Infobip Credentials
.env
file asINFOBIP_API_KEY
.https://your-unique-id.api.infobip.com
)..env
file asINFOBIP_BASE_URL
.from
number/name):.env
or.env.defaults
(INFOBIP_SENDER_ID
).Secure Storage
.env
files or API keys to Git. Ensure.env
is in.gitignore
.Environment Variables Summary
INFOBIP_API_KEY
: Your secret API key. Obtain: Infobip Portal.INFOBIP_BASE_URL
: Your account-specific API URL. Obtain: Infobip Portal/Docs.INFOBIP_SENDER_ID
: Default sender ID/number. Configure: Infobip Portal (subject to regulations).DATABASE_URL
: Database connection string. Obtain: Database provider/setup.SESSION_SECRET
: Secure random string for session management (used by Redwood auth). Generate one.Fallback Mechanisms
opossum
), or alternative providers for critical systems, though this adds complexity.5. Error Handling, Logging, and Retry Mechanisms
Building resilience into the application.
Consistent Error Handling Strategy
try...catch
, logs errors with context (logger.error
), and re-throws errors for GraphQL to handle.Logging
src/lib/logger.ts
).info
(success),warn
(recoverable issues, retries),error
(failures),debug
(verbose dev info).bulkId
, error messages, status codes.Retry Mechanism (Simple Example)
Add basic retries with exponential backoff to
sendSms
for transient network or server errors.async-retry
for more complex retry strategies.Testing Error Scenarios
.env
) -> Expect 401 error.6. Creating a Database Schema and Data Layer
Define models for campaigns and recipients.
Define Prisma Schema
Update
api/db/schema.prisma
.isOptedOut
field added toRecipient
.Database Migrations
Apply schema changes.
This updates the DB schema and regenerates the Prisma Client.
Implement Data Access (CRUD Operations)
Add CRUD functions and the
triggerCampaignSend
logic toapi/src/services/campaigns/campaigns.ts
.