Bulk SMS

Build SMS Marketing Campaigns with RedwoodJS and Infobip API

Complete guide to building a RedwoodJS application for SMS marketing campaigns using Infobip API. Covers GraphQL, Prisma, TCPA compliance, error handling, retry logic, and production deployment with Node.js 20.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 6, 2026 β€’ 20 min read

Developer Quick-Start: Complete guide to building a RedwoodJS application for SMS marketing campaigns using Infobip API. Covers GraphQL, Prisma, TCPA compliance, error handling, retry logic, and production deployment with Node.js 20. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.

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:

  1. Define basic SMS marketing campaigns (e.g., campaign name, message content).
  2. Associate recipients (phone numbers) with campaigns.
  3. Trigger the sending of SMS messages for a campaign via the Infobip API.

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:

  • RedwoodJS: A full-stack JavaScript/TypeScript framework for the modern web.
  • Infobip: A global cloud communications platform offering various APIs, including a powerful SMS API.
  • Prisma: A next-generation Node.js and TypeScript ORM used by RedwoodJS.
  • GraphQL: A query language for APIs used by RedwoodJS.
  • Node.js: The JavaScript runtime environment.
  • Yarn: Package manager for Node.js.
  • PostgreSQL (Recommended for Production) / SQLite (Default for Dev): Relational database systems.

System Architecture:

graph LR
    A[User Browser] -- GraphQL --> B(RedwoodJS API Side / GraphQL Server);
    B -- Prisma Client --> C(Database - PostgreSQL/SQLite);
    B -- REST API Call --> D(Infobip SMS API);
    C -- Stores --> E(Campaigns & Recipients Data);
    D -- Sends --> F(SMS Messages);

    subgraph RedwoodJS App
        direction LR
        G(RedwoodJS Web Side / React UI) --- A;
        B --- G;
    end
  • User Browser: Interacts with the React frontend (RedwoodJS Web Side).
  • RedwoodJS Web Side: Handles UI rendering and sends GraphQL requests to the API side.
  • RedwoodJS API Side: Contains the GraphQL server, business logic (services), and database access layer (Prisma).
  • Database: Stores application data like campaign details and recipient lists.
  • Infobip SMS API: External service responsible for actually sending the SMS messages.

Prerequisites:

  • Node.js (=20.x required for RedwoodJS v7+)
  • Yarn (>=1.22.21, managed via Corepack built into Node.js v18+)
  • An Infobip Account (Sign up at Infobip)
  • Basic understanding of JavaScript/TypeScript, React, GraphQL, and databases.
  • Access to a terminal or command prompt.
  • Minimum RedwoodJS version 7.0.0

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.

yarn create redwood-app ./redwood-infobip-sms --typescript

Navigate to Project Directory

cd redwood-infobip-sms

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

  # .env
  # Replace placeholder values with your actual Infobip credentials
  # Obtain these from your Infobip account dashboard
  INFOBIP_API_KEY=""PASTE_YOUR_INFOBIP_API_KEY_HERE""
  INFOBIP_BASE_URL=""https://youruniqueid.api.infobip.com"" # Example: Replace with your actual Base URL
  INFOBIP_SENDER_ID=""MyBrand"" # Example: Replace with your registered Sender ID or number

  # Database URL (Example for PostgreSQL - replace user, password, host, dbname)
  DATABASE_URL=""postgresql://db_user:db_password@localhost:5432/redwood_infobip_db?schema=public""
  # Database URL (Example for SQLite - default for Redwood dev)
  # DATABASE_URL=""file:./dev.db""

  # Add a secure session secret for auth (generate a random string)
  SESSION_SECRET=""replace-this-with-a-very-long-random-string-32-chars-or-more""
  • .env.defaults (Committed to Git, for non-sensitive defaults):

.env

  # .env.defaults
  # Default sender ID if not overridden in .env (optional)
  INFOBIP_SENDER_ID=""InfoSMS""
  • 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 in api/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).

yarn rw prisma migrate dev
  • Purpose: This command synchronizes your database schema with 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.

yarn workspace api add axios

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.

yarn rw g service campaign --crud
  • This creates 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.

import axios from 'axios'
import type { Prisma } from '@prisma/client'
import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'

interface SendSmsPayload {
  to: string[]
  text: string
  from?: string
}

export const sendSmsViaInfobip = async ({ to, text, from }: SendSmsPayload) => {
  const apiKey = process.env.INFOBIP_API_KEY
  const baseUrl = process.env.INFOBIP_BASE_URL

  const senderId = from || process.env.INFOBIP_SENDER_ID || 'InfoSMS'

  if (!apiKey || !baseUrl) {
    logger.error('Infobip API Key or Base URL missing in environment variables.')
    throw new Error('Infobip configuration is incomplete.')
  }


  if (!to || to.length === 0 || !text) {
    logger.error('Missing required parameters: to (list of numbers) and text.')
    throw new Error('Recipient numbers and message text are required.')
  }


  const infobipUrl = `${baseUrl}/sms/3/messages`



  const payload = {
    messages: to.map((recipient) => ({
      destinations: [{ to: recipient }],
      from: senderId,
      text: text,
    })),
  }

  try {
    logger.info(`Sending SMS via Infobip to ${to.length} recipients.`)
    logger.debug({ payload: { messages: payload.messages.map(m => ({...m, text: '[REDACTED]'})) } }, 'Infobip Request Payload (Text Redacted):')

    const response = await axios.post(infobipUrl, payload, {
      headers: {
        Authorization: `App ${apiKey}`,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      timeout: 10000,
    })

    logger.info(
      { bulkId: response.data.bulkId, status: response.status },
      'Infobip SMS submitted successfully.'
    )


    return {
      success: true,
      bulkId: response.data.bulkId,
      messages: response.data.messages,
    }
  } catch (error) {
    logger.error({ error }, 'Failed to send SMS via Infobip.')

    if (axios.isAxiosError(error)) {
      logger.error(
        {
          status: error.response?.status,
          data: error.response?.data,

        },
        'Infobip API Error Details'
      )

      const errorMessage = error.response?.data?.requestError?.serviceException?.text || error.message;
      throw new Error(`Infobip API request failed: ${errorMessage}`)
    } else {
      throw new Error(`An unexpected error occurred: ${error.message}`)
    }
  }
}
  • Why this approach? Encapsulates Infobip logic, uses environment variables, 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.

export const schema = gql`

  type SendSmsResponse {
    success: Boolean!
    bulkId: String
    message: String


  }


  input SendSmsInput {
    to: [String!]!
    text: String!
    from: String
  }


  type Mutation {
    """"""
    Triggers sending an SMS message to multiple recipients via Infobip.
    Requires authentication. Use for ad-hoc sends not tied to a stored campaign.
    """"""
    sendSms(input: SendSmsInput!): SendSmsResponse! @requireAuth
  }















`
  • @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).

  • In api/src/services/campaigns/campaigns.ts, rename sendSmsViaInfobip to sendSms.
interface SendSmsInput {
  to: string[]
  text: string
  from?: string
}

export const sendSms = async ({ input }: { input: SendSmsInput }) => {
  const { to, text, from } = input

  const apiKey = process.env.INFOBIP_API_KEY
  const baseUrl = process.env.INFOBIP_BASE_URL
  const senderId = from || process.env.INFOBIP_SENDER_ID || 'InfoSMS'



  const infobipUrl = `${baseUrl}/sms/3/messages`
  const payload = {
    messages: to.map((recipient) => ({
      destinations: [{ to: recipient }],
      from: senderId,
      text: text,
    })),
  }

  try {
    logger.info(`Sending SMS via Infobip to ${to.length} recipients.`)
    logger.debug({ payload: { messages: payload.messages.map(m => ({...m, text: '[REDACTED]'})) } }, 'Infobip Request Payload (Text Redacted):')

    const response = await axios.post(infobipUrl, payload, {
      headers: {
        Authorization: `App ${apiKey}`,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      timeout: 10000,
    })

    logger.info(
      { bulkId: response.data.bulkId, status: response.status },
      'Infobip SMS submitted successfully.'
    )


     return {
      success: true,
      bulkId: response.data.bulkId,

      message: `SMS submitted successfully to ${to.length} numbers.`
    }
  } catch (error) {
     logger.error({ error }, 'Failed to send SMS via Infobip.')

     if (axios.isAxiosError(error)) {
       logger.error(
         {
           status: error.response?.status,
           data: error.response?.data,
         },
         'Infobip API Error Details'
       )
       const errorMessage = error.response?.data?.requestError?.serviceException?.text || error.message;
       throw new Error(`Infobip API request failed: ${errorMessage}`)
     } else {
       throw new Error(`An unexpected error occurred: ${error.message}`)
     }


  }
}

Testing with GraphQL Playground

  • Start the dev server: yarn rw dev
  • Open http://localhost:8911/graphql.
  • Execute the mutation (replace placeholders with real, E.164 formatted numbers for testing):
mutation SendTestSms {

  sendSms(
    input: {

      to: [""+15551234567"", ""+15559876543""]
      text: ""Hello from RedwoodJS and Infobip!""

    }
  ) {
    success
    bulkId
    message
  }
}
  • Check your terminal logs for success/errors and the Infobip portal for message status.

4. Integrating with Infobip (Configuration Details)

Details on obtaining and managing Infobip credentials.

Obtaining Infobip Credentials

  • API Key:
  • Log in to your Infobip account portal.
  • Navigate to API Key management (often under developer settings or account).
  • Create a new API key, name it descriptively.
  • Copy the key immediately and store it securely.
  • Place this key into your .env file as INFOBIP\_API\_KEY.
  • Base URL:
  • Find your account-specific Base URL in the Infobip portal/documentation (e.g., https://your-unique-id.api.infobip.com).
  • Place this URL into your .env file as INFOBIP\_BASE\_URL.
  • Sender ID (from number/name):
  • This is the identifier shown to recipients.
  • Regulations vary greatly by country (alphanumeric, short code, long code, toll-free).
  • You may need to register/purchase Sender IDs/numbers via the Infobip portal.
  • Crucially, consult Infobip documentation or support regarding Sender ID requirements and registration processes for your target countries.
  • Set a default in .env or .env.defaults (INFOBIP\_SENDER\_ID).

Secure Storage

  • Never commit .env files or API keys to Git. Ensure .env is in .gitignore.
  • Use your hosting provider's secrets management for production environments (Vercel, Netlify, AWS Secrets Manager, etc.).

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

  • Consider retries (Section 5), circuit breakers (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

  • Our service uses try...catch, logs errors with context (logger.error), and re-throws errors for GraphQL to handle.

Logging

  • Use Redwood's Pino logger (src/lib/logger.ts).
  • Use levels appropriately: info (success), warn (recoverable issues, retries), error (failures), debug (verbose dev info).
  • Redwood's JSON logs are ideal for aggregation services (Datadog, Logflare, etc.).
  • Filter/search logs by bulkId, error messages, status codes.

Retry Mechanism (Simple Example)

Add basic retries with exponential backoff to sendSms for transient network or server errors.

import axios from 'axios'

import { logger } from 'src/lib/logger'

const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export const sendSms = async ({ input }: { input: SendSmsInput }) => {
  const { to, text, from } = input
  const apiKey = process.env.INFOBIP_API_KEY
  const baseUrl = process.env.INFOBIP_BASE_URL
  const senderId = from || process.env.INFOBIP_SENDER_ID || 'InfoSMS'


  if (!apiKey || !baseUrl) {
    logger.error('Infobip API Key or Base URL missing in environment variables.')
    throw new Error('Infobip configuration is incomplete.')
  }
  if (!to || to.length === 0 || !text) {
    logger.error('Missing required parameters: to (list of numbers) and text.')
    throw new Error('Recipient numbers and message text are required.')
  }

  const infobipUrl = `${baseUrl}/sms/3/messages`
  const payload = {
    messages: to.map((recipient) => ({
      destinations: [{ to: recipient }],
      from: senderId,
      text: text,
    })),
  }

  const MAX_RETRIES = 3;
  let attempt = 0;

  while (attempt < MAX_RETRIES) {
      attempt++;
      try {
          logger.info(`Sending SMS via Infobip (Attempt ${attempt}/${MAX_RETRIES}) to ${to.length} recipients.`);


          const response = await axios.post(infobipUrl, payload, {
             headers: {
                Authorization: `App ${apiKey}`,
                'Content-Type': 'application/json',
                Accept: 'application/json',
             },
             timeout: 15000
          });

          logger.info(
            { bulkId: response.data.bulkId, status: response.status, attempt },
            'Infobip SMS submitted successfully.'
          );
          return {
             success: true,
             bulkId: response.data.bulkId,
             message: `SMS submitted successfully on attempt ${attempt}.`,

          };

      } catch (error) {
          logger.warn({ error: error.message, attempt, maxRetries: MAX_RETRIES }, `Attempt ${attempt} failed for Infobip SMS.`);

          let shouldRetry = false;

          let waitMs = 1000 * Math.pow(2, attempt - 1) + Math.random() * 500;

          if (axios.isAxiosError(error)) {
              const status = error.response?.status;

              if (!status || (status >= 500 && status <= 599)) {
                  shouldRetry = true;
                  logger.warn(`Network or server error (${status || 'N/A'}), scheduling retry.`);
              } else {

                   logger.error({ status: error.response?.status, data: error.response?.data }, 'Non-retryable Infobip API Error Details');
              }
          } else {

              logger.error({ error }, 'Non-Axios error during Infobip request attempt.');

          }

          if (shouldRetry && attempt < MAX_RETRIES) {
              logger.info(`Waiting ${Math.round(waitMs)}ms before next retry.`);
              await delay(waitMs);

          } else {

               logger.error({ error: error.message, attempt }, 'Failed to send SMS via Infobip after all retries or due to non-retryable error.');

               let finalError;
               if (axios.isAxiosError(error)) {
                 const errorMessage = error.response?.data?.requestError?.serviceException?.text || error.message;
                 finalError = new Error(`Infobip API request failed after ${attempt} attempts: ${errorMessage}`);
               } else {
                 finalError = new Error(`An unexpected error occurred after ${attempt} attempts: ${error.message}`);
               }
               throw finalError;
          }
      }
  }




}
  • Exponential Backoff: Prevents overwhelming services during transient issues.
  • Consider libraries like async-retry for more complex retry strategies.

Testing Error Scenarios

  • Temporarily use an invalid API key (.env) -> Expect 401 error.
  • Simulate network issues -> Expect retry logic to engage.
  • Send invalid phone numbers/payload -> Expect 400 error from Infobip.

6. Creating a Database Schema and Data Layer

Define models for campaigns and recipients.

Define Prisma Schema

Update api/db/schema.prisma.

Prisma

// api/db/schema.prisma

datasource db {
  provider = ""postgresql"" // Or ""sqlite""
  url      = env(""DATABASE_URL"")
}

generator client {
  provider      = ""prisma-client-js""
  binaryTargets = ""native"" // Or specific targets like ""debian-openssl-1.1.x"" for deployment
}

model Recipient {
  id          Int      @id @default(autoincrement())
  phoneNumber String   @unique // E.164 format REQUIRED
  firstName   String?
  lastName    String?
  isOptedOut  Boolean  @default(false) // Added for opt-out tracking
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  // Many-to-Many relationship with Campaign
  campaigns   Campaign[] @relation(""CampaignRecipients"")

  @@index([isOptedOut]) // Index for filtering active recipients
}

model Campaign {
  id            Int      @id @default(autoincrement())
  name          String   @unique
  message       String
  senderId      String?  // Campaign-specific sender override
  // Suggested statuses: DRAFT, SCHEDULED, SENDING, SENT, FAILED, COMPLETE_NO_RECIPIENTS
  status        String   @default(""DRAFT"")
  scheduledAt   DateTime?
  sentAt        DateTime? // Timestamp when sending was initiated/completed
  infobipBulkId String?  // Store Infobip's bulk ID for tracking
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt

  // Many-to-Many relationship with Recipient
  recipients    Recipient[] @relation(""CampaignRecipients"")

  @@index([status])
  @@index([scheduledAt])
}

// Prisma implicitly handles the join table (_CampaignRecipients)
// based on the @relation definition above.
  • isOptedOut field added to Recipient.
  • Status list expanded in comments.
  • Indexes added for common query fields.

Database Migrations

Apply schema changes.

yarn rw prisma migrate dev

This updates the DB schema and regenerates the Prisma Client.

Implement Data Access (CRUD Operations)

Add CRUD functions and the triggerCampaignSend logic to api/src/services/campaigns/campaigns.ts.

import axios from 'axios'
import type { Prisma, Campaign, Recipient } from '@prisma/client'
import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'
import { requireAuth } from 'src/lib/auth'

const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

interface SendSmsInput { to: string[]; text: string; from?: string; }

export const sendSms = async ({ input }: { input: SendSmsInput }) => {

    const { to, text, from } = input
    const apiKey = process.env.INFOBIP_API_KEY
    const baseUrl = process.env.INFOBIP_BASE_URL
    const senderId = from || process.env.INFOBIP_SENDER_ID || 'InfoSMS'

    if (!apiKey || !baseUrl) {
      logger.error('Infobip API Key or Base URL missing in environment variables.')
      throw new Error('Infobip configuration is incomplete.')
    }
    if (!to || to.length === 0 || !text) {
      logger.error('Missing required parameters: to (list of numbers) and text.')
      throw new Error('Recipient numbers and message text are required.')
    }

    const infobipUrl = `${baseUrl}/sms/3/messages`
    const payload = {
      messages: to.map((recipient) => ({
        destinations: [{ to: recipient }],
        from: senderId,
        text: text,
      })),
    }

    const MAX_RETRIES = 3;
    let attempt = 0;

    while (attempt < MAX_RETRIES) {
        attempt++;
        try {
            logger.info(`Sending SMS via Infobip (Attempt ${attempt}/${MAX_RETRIES}) to ${to.length} recipients.`);

            const response = await axios.post(infobipUrl, payload, {
               headers: {
                  Authorization: `App ${apiKey}`,
                  'Content-Type': 'application/json',
                  Accept: 'application/json',
               },
               timeout: 15000
            });

            logger.info(
              { bulkId: response.data.bulkId, status: response.status, attempt },
              'Infobip SMS submitted successfully.'
            );
            return {
               success: true,
               bulkId: response.data.bulkId,
               message: `SMS submitted successfully on attempt ${attempt}.`,
            };

        } catch (error) {
            logger.warn({ error: error.message, attempt, maxRetries: MAX_RETRIES }, `Attempt ${attempt} failed for Infobip SMS.`);

            let shouldRetry = false;
            let waitMs = 1000 * Math.pow(2, attempt - 1) + Math.random() * 500;

            if (axios.isAxiosError(error)) {
                const status = error.response?.status;
                if (!status || (status >= 500 && status <= 599)) {
                    shouldRetry = true;
                    logger.warn(`Network or server error (${status || 'N/A'}), scheduling retry.`);
                } else {
                     logger.error({ status: error.response?.status, data: error.response?.data }, 'Non-retryable Infobip API Error Details');
                }
            } else {
                logger.error({ error }, 'Non-Axios error during Infobip request attempt.');
            }

            if (shouldRetry && attempt < MAX_RETRIES) {
                logger.info(`Waiting ${Math.round(waitMs)}ms before next retry.`);
                await delay(waitMs);
            } else {
                 logger.error({ error: error.message, attempt }, 'Failed to send SMS via Infobip after all retries or due to non-retryable error.');
                 let finalError;
                 if (axios.isAxiosError(error)) {
                   const errorMessage = error.response?.data?.requestError?.serviceException?.text || error.message;
                   finalError = new Error(`Infobip API request failed after ${attempt} attempts: ${errorMessage}`);
                 } else {
                   finalError = new Error(`An unexpected error occurred after ${attempt} attempts: ${error.message}`);
                 }
                 throw finalError;
            }
        }
    }

    throw new Error('SMS sending failed unexpectedly after retry loop.');
}

export const campaigns = () => {
  requireAuth({ roles: ['admin', 'marketer'] })
  return db.campaign.findMany({ orderBy: { createdAt: 'desc' } })
}

export const campaign = ({ id }: Prisma.CampaignWhereUniqueInput) => {
  requireAuth()
  return db.campaign.findUnique({
    where: { id },
    include: {
      recipients: {
         orderBy: { createdAt: 'asc' }
      }
    },
  })
}

interface CreateCampaignServiceInput {
  input: Omit<Prisma.CampaignCreateInput, 'recipients'> & {
    recipientIds?: number[]
  }
}

export const createCampaign = async ({ input }: CreateCampaignServiceInput) => {
  requireAuth({ roles: ['admin', 'marketer'] })
  const { recipientIds, ...campaignData } = input

  return db.campaign.create({
    data: {
      ...campaignData,
      status: campaignData.status || 'DRAFT',

      recipients: recipientIds && recipientIds.length > 0
        ? { connect: recipientIds.map((id) => ({ id })) }
        : undefined,
    },
  })
}

interface UpdateCampaignServiceInput {
   id: number;
   input: Omit<Prisma.CampaignUpdateInput, 'recipients'> & {
     recipientIds?: number[]
   }
}

export const updateCampaign = ({ id, input }: UpdateCampaignServiceInput) => {
   requireAuth({ roles: ['admin', 'marketer'] })
   const { recipientIds, ...campaignData } = input

   return db.campaign.update({
     where: { id },
     data: {
       ...campaignData,


       recipients: recipientIds
        ? { set: recipientIds.map((id) => ({ id })) }
        : undefined,
     },
   })
}

export const deleteCampaign = ({ id }: Prisma.CampaignWhereUniqueInput) => {
   requireAuth({ roles: ['admin'] })

   return db.campaign.delete({
     where: { id },
   })
}

interface TriggerCampaignSendInput {
  campaignId: number
}

export const triggerCampaignSend = async ({ input }: { input: TriggerCampaignSendInput }) => {
    requireAuth({ roles: ['admin', 'marketer'] })
    const { campaignId } = input;

    logger.info({ campaignId }, ""Attempting to trigger campaign send."");


    const camp = await db.campaign.findUnique({
        where: { id: campaignId },
        include: { recipients: true }
    });

    if (!camp) {
        logger.error({ campaignId }, ""Campaign not found for triggering send."");
        throw new Error(`Campaign with ID ${campaignId} not found.`);
    }


    const activeRecipients = camp.recipients.filter(r => !r.isOptedOut);

    if (activeRecipients.length === 0) {
        logger.warn({ campaignId }, ""Campaign has no active (opted-in) recipients. Nothing to send."");

        await db.campaign.update({
            where: { id: campaignId },
            data: { status: 'COMPLETE_NO_RECIPIENTS', sentAt: new Date() }
        });
        return { success: true, message: ""Campaign has no active recipients."" };
    }


    if (camp.status === 'SENDING' || camp.status === 'SENT') {
         logger.warn({ campaignId, status: camp.status }, ""Campaign is already sending or has been sent. Send trigger ignored."");

         return { success: false, message: `Campaign status is already ${camp.status}. Send trigger ignored.` };
    }


    await db.campaign.update({
        where: { id: campaignId },
        data: { status: 'SENDING', sentAt: new Date() }
    });

    let sendResult;
    try {
        const recipientNumbers = activeRecipients.map(r => r.phoneNumber);
        const sender = camp.senderId;


        sendResult = await sendSms({
            input: {
                to: recipientNumbers,
                text: camp.message,
                from: sender
            }
        });


        await db.campaign.update({
            where: { id: campaignId },
            data: {
                status: 'SENT',
                infobipBulkId: sendResult.bulkId
            }
        });

        logger.info({ campaignId, bulkId: sendResult.bulkId, recipientCount: recipientNumbers.length }, ""Campaign SMS successfully submitted to Infobip."");
        return { success: true, bulkId: sendResult.bulkId, message: `Campaign ${campaignId} sent to ${recipientNumbers.length} recipients.` };

    } catch (error) {
        logger.error({ campaignId, error: error.message }, ""Failed to send campaign SMS via Infobip."");

        await db.campaign.update({
            where: { id: campaignId },
            data: { status: 'FAILED' }
        });

        throw new Error(`Failed to send campaign ${campaignId}: ${error.message}`);
    }
}

---

## 7. SMS Marketing Compliance (TCPA & FCC Regulations)

**CRITICAL: Legal requirements for SMS marketing in the United States.**

### TCPA Requirements (United States)

The Telephone Consumer Protection Act (TCPA) governs commercial SMS messaging. **Non-compliance can result in penalties of $500 per violation, or $1,500 per willful violation, with no cap on total damages.**

#### Prior Express Written Consent (Required)

Before sending any marketing SMS messages, you **must** obtain prior express written consent from recipients. This means:

*   **Clear Authorization**: Consumers must explicitly agree to receive SMS messages
*   **Written Record**: Maintain documentation of consent (date, time, method, exact language used)
*   **Scope Disclosure**: Clearly state what types of messages they'll receive and frequency

**Example Consent Language:**

By providing your phone number and checking this box, you agree to receive marketing text messages from [Business Name] at the number provided, including messages sent by autodialer. Consent is not a condition of purchase. Message and data rates may apply. Message frequency varies. Reply HELP for help or STOP to cancel.


#### New FCC Opt-Out Rules (Effective April 11, 2025)

The FCC adopted new opt-out rules that take effect **April 11, 2025**:

1. **Any Reasonable Method**: Consumers can revoke consent through ANY reasonable method – not just texting "STOP". Examples include:
   - "Please stop texting me"
   - "Unsubscribe"
   - "Remove me"
   - Misspellings like "STPO" or "SOTP"
2. **10-Business-Day Processing**: You must honor opt-out requests within **10 business days** of receipt (previously no specific timeline)
3. **One Confirmation Only**: You may send ONE confirmation message acknowledging the opt-out request. No additional messages are permitted.
4. **Cross-Channel Revocation**: If a consumer revokes consent via phone call, that revocation also applies to text messages, and vice versa.

#### Time Restrictions

**Do not send SMS messages before 8:00 AM or after 9:00 PM** in the recipient's local time zone.

#### Implementation Recommendations

**Enhance the `Recipient` model to track compliance** (already included in Section 6 schema):

TypeScript

model Recipient { id Int @id @default(autoincrement()) phoneNumber String @unique firstName String? lastName String? isOptedOut Boolean @default(false) consentDate DateTime? consentMethod String? optOutDate DateTime? optOutMethod String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt campaigns Campaign[] @relation("CampaignRecipients") @@index([isOptedOut]) }


**Add time validation to `triggerCampaignSend`:**

TypeScript

const now = new Date(); const hour = now.getHours();

if (hour < 8 || hour >= 21) { logger.warn({ campaignId, hour }, "Campaign send attempted outside allowed hours (8 AM - 9 PM)."); throw new Error("SMS messages cannot be sent before 8:00 AM or after 9:00 PM per TCPA regulations."); }


**Implement robust opt-out recognition:**

Create a webhook endpoint to handle incoming SMS responses via Infobip's delivery reports. Process various opt-out phrases beyond just "STOP":

TypeScript

export const handler = async (event) => { const body = JSON.parse(event.body); const incomingText = body.message?.text?.toLowerCase().trim(); const senderNumber = body.message?.from;

const optOutKeywords = ['stop', 'unsubscribe', 'cancel', 'end', 'quit', 'remove']; const isOptOut = optOutKeywords.some(keyword => incomingText?.includes(keyword) );

if (isOptOut && senderNumber) {

await db.recipient.updateMany({ where: { phoneNumber: senderNumber }, data: { isOptedOut: true, optOutDate: new Date(), optOutMethod: 'SMS_KEYWORD' } });

logger.info({ senderNumber, keyword: incomingText }, 'Recipient opted out via SMS');

}

return { statusCode: 200 }; };


### Marketing vs. Informational Messages

- Marketing Messages: Require opt-in consent; opt-out applies
- Informational Messages (account alerts, order updates): Generally exempt from TCPA consent requirements, but:
  - If consumer opts out in response to an informational message, honor the opt-out for ALL messages (both marketing and informational)

### Documentation Requirements

Maintain detailed records for all campaigns:

- Consent records (who, when, how, exact language)
- Opt-out requests and processing timestamps
- Message logs with timestamps
- Campaign audit trails

### International Considerations

If sending SMS internationally:

- Europe (GDPR): Requires explicit opt-in consent and easy opt-out mechanisms
- Canada (CASL): Similar to TCPA with express consent requirements
- Other jurisdictions: Research local regulations before sending

**Resources:**

- FCC TCPA Rules: https://www.fcc.gov/general/telemarketing-and-robocalls
- CTIA Messaging Principles: https://www.ctia.org/the-wireless-industry/industry-commitments/messaging-principles-and-best-practices

---

## 8. Testing and Deployment

### Testing Strategy

**Unit Tests:**

Test your service functions in isolation:

TypeScript

import { sendSms, triggerCampaignSend } from './campaigns';

scenario('sends SMS successfully', async (scenario) => {

const result = await sendSms({ input: { to: ['+15551234567'], text: 'Test message', from: 'TestSender' } });

expect(result.success).toBe(true); expect(result.bulkId).toBeDefined(); });

scenario('respects opt-out status', async (scenario) => { const campaign = scenario.campaign.withOptedOutRecipient; const result = await triggerCampaignSend({ input: { campaignId: campaign.id } });

expect(result.message).toContain('no active recipients'); });


**Integration Tests:**

Test the full GraphQL API flow:

TypeScript

import { mockGraphQLQuery, mockCurrentUser } from '@redwoodjs/testing/api';

test('sendSms mutation works', async () => { mockCurrentUser({ id: 1, roles: ['admin'] });

const result = await mockGraphQLQuery(SEND_SMS_MUTATION, { variables: { input: { to: ['+15551234567'], text: 'Test' } } });

expect(result.data.sendSms.success).toBe(true); });


### Deployment

**Environment Variables:**

Ensure all production environment variables are set:

- INFOBIP\_API\_KEY
- INFOBIP\_BASE\_URL
- INFOBIP\_SENDER\_ID
- DATABASE\_URL
- SESSION\_SECRET

**Deployment Platforms:**

RedwoodJS deploys well to:

- Vercel: Automatic deployments from Git
- Netlify: Built-in RedwoodJS support
- AWS: Via Amplify or custom setup
- Render: Full-stack hosting with databases

**Database Migrations:**

Run migrations in production:

Bash

yarn rw prisma migrate deploy


**Monitoring:**

Implement monitoring for:

- SMS send success/failure rates
- Opt-out request processing time
- API error rates and response times
- Campaign completion status

---

## 9. Summary and Next Steps

### What We Built

A production-ready RedwoodJS application featuring:

- βœ… GraphQL API for SMS campaign management
- βœ… Prisma database models for campaigns and recipients
- βœ… Infobip API integration with retry logic
- βœ… TCPA compliance tracking (opt-outs, consent, time restrictions)
- βœ… Error handling and logging
- βœ… Authentication and authorization

### Key Enhancements for Production

1. Scheduled Campaigns: Implement background jobs (Redis + Bull) to send campaigns at scheduled times
2. Rate Limiting: Add per-campaign and global rate limits to respect carrier requirements
3. Delivery Reports: Create webhook endpoint to receive and process Infobip delivery reports
4. Analytics Dashboard: Build React UI to visualize campaign performance
5. Template System: Add message templates with variable substitution
6. Timezone Handling: Use libraries like luxon to respect recipient timezones for TCPA time restrictions
7. A/B Testing: Implement split testing for message variants
8. Unsubscribe Page: Create web interface for managing preferences

### Additional Resources

- RedwoodJS Docs: https://redwoodjs.com/docs
- Infobip API Reference: https://www.infobip.com/docs/api
- Prisma Documentation: https://www.prisma.io/docs
- TCPA Compliance Guide: https://www.fcc.gov/document/fcc-adopts-rules-prevent-illegal-robocalls-and-robotexts

This foundation provides everything needed to build a compliant, scalable SMS marketing platform with RedwoodJS and Infobip.

Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)

If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.

curl -X POST https://api.sendsmsnokyc.com/messages \
  -H "x-api-key: $SMSROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["+14155551234"],
    "channel": ["sms"],
    "body": "Your verification code is 482910"
  }'
  • Instant onboarding: No KYC paperwork or sales queues β€” grab an API key and fund with crypto (BTC/USDT) or card.
  • Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
  • Transparent global pricing: Compare exact per-country termination rates on our live pricing page.

Ship Global SMS in One API Call

Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.

Explore SMSRoute Developers β†’