Developer Quick-Start: Step-by-step guide to integrate Vonage WhatsApp Business API in RedwoodJS apps. Includes webhook setup, JWT authentication, message logging with Prisma, automated replies, and production deployment strategies. 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.
Integrate Vonage's WhatsApp Business API to send and receive WhatsApp messages within your RedwoodJS application. This comprehensive tutorial shows you how to build a production-ready solution with secure webhook handling, JWT authentication, Prisma database logging, and automated message replies using RedwoodJS Functions and Services.
By the end of this guide, you'll have a fully functional RedwoodJS WhatsApp integration capable of two-way communication, complete with security best practices, error handling, deployment guidance, and troubleshooting strategies for real-world applications.
Project Overview and Goals
What You'll Build:
Create a RedwoodJS application featuring:
- An API endpoint (Redwood Function) to receive inbound WhatsApp messages from Vonage via webhooks, secured with signature verification
- An API endpoint (Redwood Function) to receive message status updates from Vonage via webhooks, secured with signature verification
- A Redwood Service to encapsulate the logic for interacting with the Vonage Messages API
- Functionality to automatically reply "Message received" to incoming WhatsApp messages
- Secure handling of API credentials using environment variables
- Basic database logging of messages using Prisma
Use Cases:
- Customer support chatbots with automated responses
- Appointment reminders and booking confirmations
- Order status notifications for e-commerce
- Two-way communication for field service management
- Marketing campaigns with opt-in/opt-out handling
Development Time: Approximately 2-3 hours for initial setup and basic implementation. Additional time required for custom business logic and production hardening.
Skill Level: Intermediate. Requires familiarity with JavaScript/TypeScript, REST APIs, and basic understanding of webhooks and asynchronous messaging patterns.
Problem Solved: This guide enables you to leverage WhatsApp's ubiquity (over 2 billion users worldwide as of 2024) for customer communication, notifications, or bot interactions directly within your RedwoodJS applications, using Vonage as the communication provider. WhatsApp offers higher engagement rates (98% open rate) compared to email (20-25%), making it ideal for time-sensitive communications.
Technologies Used:
- RedwoodJS: A full-stack JavaScript/TypeScript framework for building modern web applications. It provides structure, conventions (like Services and Functions), and tools (CLI, Prisma integration) that simplify development.
- Node.js: The runtime environment for the RedwoodJS API side. Requires Node.js v18.x or v20.x (LTS versions recommended).
- Vonage Messages API: Enables sending and receiving messages across various channels, including WhatsApp. You'll use the Node SDK.
- Vonage WhatsApp Sandbox: A testing environment provided by Vonage to develop WhatsApp integrations without needing a dedicated WhatsApp Business Account initially.
- Ngrok: A tool to expose local development servers to the internet, necessary for Vonage webhooks to reach your local machine during development.
- Prisma: The default ORM for RedwoodJS, used for database interactions.
Version Compatibility Matrix:
| Component | Minimum Version | Recommended Version | Notes |
|---|---|---|---|
| Node.js | 18.x | 20.x LTS | Required for RedwoodJS v6+ |
| RedwoodJS | 6.0.0 | Latest stable | Use yarn rw upgrade to update |
| @vonage/server-sdk | 3.13.0 | 3.25.1+ | Released January 2025 |
| @vonage/messages | 2.0.0 | Latest | Part of server-sdk |
| @vonage/jwt | 1.10.0 | 1.12.1+ | For webhook signature verification |
| Prisma | 5.0.0 | Latest | Bundled with RedwoodJS |
System Architecture:
+-----------------+ +------------+ +----------------+ +----------------------+ +-------------------+ +----------------+ +-----------------+
| End User |----->| WhatsApp |----->| Vonage |----->| Ngrok/Public URL |----->| RedwoodJS Function|----->| RedwoodJS Service|----->| Vonage |
| (WhatsApp App) |<-----| Platform |<-----| Messages API |<-----| (API Side - Port 8911)|----->| (Vonage Logic) |<-----| Messages API | | (API & SDK) |
+-----------------+ +------------+ +----------------+ +----------------------+ +-------------------+ +----------------+ +-----------------+
^ (Webhooks) | |
| | Logs Inbound Message | Logs Outbound Message
| v v
+---------------------------------------------------------------------------------------------+ Prisma (Database) |<-----------------+
+-------------------+
Prerequisites:
- Node.js: Version 18 or higher installed. Download from nodejs.org
- Yarn: Package manager for RedwoodJS. Install via npm: npm install -g yarn
- RedwoodJS CLI: Installed globally: npm install -g @redwoodjs/cli or yarn global add @redwoodjs/cli
- Vonage API Account: Sign up for free credit. You'll need your API Key and Secret.
- Ngrok: Download and install, then authenticate with your account token.
- WhatsApp Account: A personal WhatsApp account on a smartphone for testing with the sandbox.
- Basic familiarity with Git for version control.
- OS: Compatible with macOS, Windows (using WSL recommended), and Linux (Node.js and RedwoodJS are generally cross-platform).
Verification Steps:
node --version
yarn --version
yarn rw --version
ngrok version
ngrok config check
1. Setting up Your RedwoodJS WhatsApp Project
Create a new RedwoodJS project and configure it for Vonage WhatsApp integration.
- Create RedwoodJS App: Open your terminal and run:
yarn create redwood-app ./redwood-vonage-whatsapp
cd redwood-vonage-whatsapp
Choose TypeScript when prompted for the best development experience. This command scaffolds a complete RedwoodJS project with api and web directories, configures Prisma, and sets up the development environment.
- Install Vonage SDK Dependencies: Install the Vonage SDKs. Navigate to the
apiworkspace:
cd api
yarn add @vonage/server-sdk@^3.25.0 @vonage/messages@^2.0.0 @vonage/jwt@^1.12.0
cd ..
- @vonage/server-sdk: Core SDK for authentication, general API access, and initialization of Vonage services
- @vonage/messages: Specific SDK for the Messages API with WhatsApp, Viber, and Facebook Messenger support
- @vonage/jwt: Verifies webhook signatures using JWT tokens to ensure requests originate from Vonage
- Define Prisma Schema for Message Logging: Before configuring environment variables,
define the database model for message logging. Open
api/db/schema.prismaand add the MessageLog model:
Prisma
// api/db/schema.prisma
datasource db {
provider = "sqlite" // Use "postgresql" for production
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model MessageLog {
id Int @id @default(autoincrement())
direction String // "INBOUND" or "OUTBOUND"
vonageMessageId String? // UUID from Vonage, nullable for failed sends
fromNumber String // E.164 format phone number
toNumber String // E.164 format phone number
body String // Message content
status String // submitted, delivered, read, failed, etc.
statusDetails String? // JSON string with error details if applicable
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([vonageMessageId])
@@index([fromNumber])
@@index([status])
}
Run Prisma migrations to create the database schema:
yarn rw prisma migrate dev --name add_message_log
- Configure Environment Variables: RedwoodJS uses
.envfiles for environment variables. Create a.envfile in your project root:
.env
# redwood-vonage-whatsapp/.env
# Vonage API Credentials
VONAGE_API_KEY="YOUR_VONAGE_API_KEY"
VONAGE_API_SECRET="YOUR_VONAGE_API_SECRET"
VONAGE_APPLICATION_ID="YOUR_VONAGE_APPLICATION_ID"
# --- Vonage Private Key ---
# Paste the entire content of your private.key file here.
# This is more secure and portable for deployments than using a file path.
# Ensure this value is enclosed in double quotes as it contains newlines and special characters.
# Example: VONAGE_PRIVATE_KEY_CONTENT="-----BEGIN PRIVATE KEY-----\nYOURKEYCONTENTHERE...\n-----END PRIVATE KEY-----"
VONAGE_PRIVATE_KEY_CONTENT="PASTE_YOUR_PRIVATE_KEY_CONTENT_HERE"
# --- Vonage Signature Secret ---
# Used to verify incoming webhooks. Find in Vonage Dashboard β Settings.
VONAGE_API_SIGNATURE_SECRET="YOUR_VONAGE_SIGNATURE_SECRET"
# Vonage WhatsApp Sandbox Number (Provided by Vonage)
# This is often 14157386102 for the Vonage sandbox.
VONAGE_WHATSAPP_NUMBER="YOUR_VONAGE_SANDBOX_NUMBER"
# Redwood API Server Port (Default: 8911)
PORT=8911
# Database URL (Defaults to SQLite for dev, adjust for production)
# Example for Render PostgreSQL: Will be set by Render environment variable group
# DATABASE_URL="postgresql://user:password@host:port/database"
# For local dev (SQLite default):
DATABASE_URL="file:./dev.db"
Environment Variable Validation: Test that environment variables are loaded correctly:
yarn rw console
process.env.VONAGE_API_KEY
process.env.VONAGE_APPLICATION_ID
How to Obtain These Values:
- VONAGE\_API\_KEY & VONAGE\_API\_SECRET: Found on the main page of your Vonage API Dashboard after logging in.
- VONAGE\_APPLICATION\_ID & VONAGE\_PRIVATE\_KEY\_CONTENT:
- Go to Applications β Create a new application in the Vonage Dashboard.
- Give it a name (e.g., "Redwood WhatsApp App").
- Enable Messages under Capabilities. Leave webhook URLs blank for now.
- Click Generate public and private key. Immediately save the
private.keyfile that downloads. - Open the downloaded
private.keyfile with a text editor and copy its entire content. - Paste this content as the value for VONAGE\_PRIVATE\_KEY\_CONTENT in your .env file. Make sure to include the -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- lines and enclose the whole thing in double quotes.
- Click Generate new application.
- The VONAGE\_APPLICATION\_ID will be displayed for your new application. Copy it.
- VONAGE\_API\_SIGNATURE\_SECRET: Go to the Vonage Dashboard β Settings. Find your API key and click Edit. Your signature secret is listed there. If none exists, generate one.
- VONAGE\_WHATSAPP\_NUMBER: Go to Messages API Sandbox in the Vonage Dashboard. The sandbox number is displayed prominently (often 14157386102).
Allowlisting Your WhatsApp Number (Required): To use the Messages API Sandbox, you must allowlist your personal WhatsApp number:
- In the Vonage Dashboard, navigate to Messages API Sandbox
- Click Add to sandbox in the External Accounts section
- Choose one of three methods:
- Scan QR Code: Use your phone camera to open WhatsApp with a pre-filled message
- Email Instructions: Send setup instructions to yourself or team members
- Manual Message: Send the unique phrase shown (e.g., "join example-word") from your WhatsApp to the sandbox number 14157386102
- Verify success: The sandbox page should show "You have 1 user(s) whitelisted". Click Refresh if it doesn't appear immediately.
Security Considerations:
.envFile: Add .env to your .gitignore file to prevent committing secrets. Redwood's default .gitignore usually covers this, but double-check.- Private Key Content: Treat the VONAGE\_PRIVATE\_KEY\_CONTENT value as highly sensitive. Do not commit it to version control. Use platform-specific secret management (like Render Environment Variables, GitHub Secrets, etc.) for production deployments.
- Secret Rotation: Rotate credentials quarterly or immediately if compromised. To rotate:
- Generate a new private key in Vonage Dashboard (Applications β Your App β Generate new key pair)
- Update VONAGE\_PRIVATE\_KEY\_CONTENT in all environments
- Generate new VONAGE\_API\_SIGNATURE\_SECRET (Settings β API Key β Edit β Regenerate signature secret)
- Update secret across all deployments with zero downtime by deploying new version before revoking old credentials
- Start Ngrok for Webhook Development: Vonage needs a publicly accessible URL to send
webhooks. Ngrok creates a secure tunnel to your local machine. The RedwoodJS API server runs on port 8911 by
default (defined by
PORTin.env).
Ngrok Free Tier Limitations (as of 2024):
- 1 GB data transfer per month
- 1 concurrent endpoint
- Up to 20,000 HTTP requests/month
- Up to 5,000 TCP connections/month
- Requires authentication with account token (sign up at ngrok.com)
- Interstitial warning page on free domains (can be bypassed with custom headers)
ngrok config add-authtoken YOUR_NGROK_AUTH_TOKEN
ngrok http 8911
Ngrok displays a forwarding URL like https://<unique_id>.ngrok.io or
https://<unique_id>.ngrok.app. Keep this URL handy. Keep this terminal
window running. Ngrok Troubleshooting:
- Connection refused: Ensure RedwoodJS dev server is running on port 8911 (yarn rw dev api)
- Tunnel not found: Restart ngrok and update webhook URLs in Vonage Dashboard
- Bandwidth exceeded: Upgrade to paid plan or monitor usage at ngrok dashboard
- Interstitial page blocking webhooks: This shouldn't affect API calls from Vonage, only browser traffic
- Configure Vonage Webhooks: Tell Vonage where to send incoming messages and status updates.
- Application Webhooks: Go back to your application settings in the Vonage Dashboard (Applications β Your App β Edit).
- Under Capabilities β Messages, enter:
- Inbound URL: YOUR\_NGROK\_URL/.redwood/functions/whatsappInbound (e.g., https://xyz.ngrok.app/.redwood/functions/whatsappInbound)
- Status URL: YOUR\_NGROK\_URL/.redwood/functions/whatsappStatus (e.g., https://xyz.ngrok.app/.redwood/functions/whatsappStatus)
- Save the changes.
- Sandbox Webhooks: Go to the Messages API Sandbox page.
- Click the Webhooks tab.
- Enter the same URLs as above for Inbound and Status.
- Save the webhooks.
Why configure both? The Sandbox Webhooks are used specifically when you
interact directly with the Messages API Sandbox environment (using the sandbox number, allowlisted numbers,
etc.). The Application Webhooks are tied to your specific Vonage Application (identified by
the VONAGE_APPLICATION_ID). These become relevant when you move beyond the sandbox, potentially
using a purchased WhatsApp number linked to that application or utilizing other application-specific features.
For initial sandbox testing, configuring both ensures messages sent via the sandbox trigger your endpoints
correctly. Why /.redwood/functions/? This is the default path RedwoodJS exposes
its API functions under during development and typically in serverless deployments. Webhook
Testing: After configuration, test webhooks are working:
- Start your RedwoodJS dev server: yarn rw dev api
- Send a test message from your allowlisted WhatsApp number to the sandbox number
- Check your terminal logs for "Inbound WhatsApp webhook received"
- If no webhook arrives within 10 seconds:
- Verify ngrok is running and the URL hasn't changed
- Check Vonage Dashboard β Messages API Sandbox β Webhooks are saved correctly
- Ensure your number is allowlisted (check External Accounts section)
2. Implementing WhatsApp Message Handling (API Side)
Create Redwood Functions to handle the webhooks and a Service to manage Vonage interactions.
- Create Redwood Service for Vonage: Services encapsulate business logic in RedwoodJS, providing a clean separation of concerns and making code testable. Generate a service:
yarn rw g service vonage
This creates api/src/services/vonage/vonage.ts (and test files).
- Implement Vonage Service Logic: Open
api/src/services/vonage/vonage.tsand add the following code:
import { Vonage } from '@vonage/server-sdk'
import { WhatsAppText } from '@vonage/messages'
import { logger } from 'src/lib/logger'
import { db } from 'src/lib/db'
if (
!process.env.VONAGE_API_KEY ||
!process.env.VONAGE_API_SECRET ||
!process.env.VONAGE_APPLICATION_ID ||
!process.env.VONAGE_PRIVATE_KEY_CONTENT ||
!process.env.VONAGE_WHATSAPP_NUMBER
) {
logger.error('Missing required Vonage environment variables.')
throw new Error('Missing required Vonage environment variables.')
}
if (
!process.env.VONAGE_PRIVATE_KEY_CONTENT.includes('-----BEGIN PRIVATE KEY-----') ||
!process.env.VONAGE_PRIVATE_KEY_CONTENT.includes('-----END PRIVATE KEY-----')
) {
logger.warn('VONAGE_PRIVATE_KEY_CONTENT might be malformed (missing BEGIN/END markers).')
}
const vonage = new Vonage(
{
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET,
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: process.env.VONAGE_PRIVATE_KEY_CONTENT,
},
{
apiHost: 'https://messages-sandbox.nexmo.com',
logger: logger,
}
)
const validateE164 = (phoneNumber: string): boolean => {
const e164Regex = /^\+?[1-9]\d{1,14}$/
return e164Regex.test(phoneNumber)
}
export const sendWhatsAppMessage = async ({
to,
text,
}: {
to: string
text: string
}) => {
if (!to || !text) {
throw new Error('Both "to" and "text" parameters are required')
}
if (!validateE164(to)) {
throw new Error(
`Invalid phone number format. Expected E.164 format (e.g., +14155552671), got: ${to}`
)
}
if (text.length > 4096) {
throw new Error('Message text exceeds maximum length of 4096 characters')
}
logger.info({ to }, 'Attempting to send WhatsApp message')
try {
const response = await vonage.messages.send(
new WhatsAppText({
from: process.env.VONAGE_WHATSAPP_NUMBER,
to: to,
text: text,
channel: 'whatsapp',
message_type: 'text',
})
)
logger.info(
{ messageUUID: response.messageUUID },
'WhatsApp message sent successfully'
)
await logMessage({
direction: 'OUTBOUND',
vonageMessageId: response.messageUUID,
fromNumber: process.env.VONAGE_WHATSAPP_NUMBER,
toNumber: to,
body: text,
status: 'submitted',
})
return { success: true, messageUUID: response.messageUUID }
} catch (error) {
const errorMessage = error.response?.data?.title || error.response?.data?.detail || error.message || error
const errorDetails = error.response?.data || error
logger.error(
{ error: errorMessage, details: errorDetails },
'Failed to send WhatsApp message via Vonage'
)
await logMessage({
direction: 'OUTBOUND',
vonageMessageId: null,
fromNumber: process.env.VONAGE_WHATSAPP_NUMBER,
toNumber: to,
body: text,
status: 'failed',
statusDetails: JSON.stringify({ error: errorMessage }),
})
return { success: false, error: 'Failed to send message' }
}
}
export const handleInboundWhatsAppMessage = async ({
fromNumber,
messageBody,
vonageMessageId,
}: {
fromNumber: string
messageBody: string
vonageMessageId: string
}) => {
logger.info(
{ fromNumber, messageBody, vonageMessageId },
'Handling inbound WhatsApp message'
)
await logMessage({
direction: 'INBOUND',
vonageMessageId: vonageMessageId,
fromNumber: fromNumber,
toNumber: process.env.VONAGE_WHATSAPP_NUMBER,
body: messageBody,
status: 'delivered',
})
const replyText = 'Message received.'
await sendWhatsAppMessage({ to: fromNumber, text: replyText })
return { success: true }
}
export const handleMessageStatusUpdate = async ({
vonageMessageId,
status,
timestamp,
error,
}: {
vonageMessageId: string
status: string
timestamp: string
error?: any
}) => {
logger.info(
{ vonageMessageId, status, timestamp, error },
'Handling message status update'
)
try {
await db.messageLog.updateMany({
where: { vonageMessageId: vonageMessageId },
data: {
status: status,
statusDetails: error ? JSON.stringify(error) : null,
updatedAt: new Date(timestamp),
},
})
logger.info(
{ vonageMessageId, status },
'Message status updated in database'
)
} catch (dbError) {
logger.error(
{ dbError, vonageMessageId, status },
'Failed to update message status in database'
)
}
return { success: true }
}
const logMessage = async (data: {
direction: 'INBOUND' | 'OUTBOUND'
vonageMessageId: string | null
fromNumber: string
toNumber: string
body: string
status: string
statusDetails?: string | null // Added optional field
}) => {
try {
await db.messageLog.create({ data })
logger.debug({ data: { ...data, body: '...' } }, 'Message logged to database')
} catch (dbError) {
logger.error({ dbError, messageData: { ...data, body: '...' } }, 'Failed to log message')
}
}
- Initialization: We initialize the Vonage client using environment variables, now directly using
VONAGE\_PRIVATE\_KEY\_CONTENT for the privateKey. The complex file reading logic is removed. Remember to
manage the
VONAGE_PRIVATE_KEY_CONTENTsecurely, especially in production. The sandbox apiHost is explicitly set; remove this line when deploying to production. - Input Validation: Added validateE164() helper function and validation for phone numbers and message length
- E.164 Phone Number Format: All phone numbers must follow E.164 international format: +[country code][national number] with maximum 15 digits. Examples: +14155552671 (US), +442071838750 (UK), +34912345678 (Spain). Read more at Vonage's E.164 guide.
sendWhatsAppMessage: Takes to and text, uses vonage.messages.send with WhatsAppText, logs the outcome, and logs the message to the database. Includes improved error logging.handleInboundWhatsAppMessage: Logs the incoming message and triggers sendWhatsAppMessage for a reply.handleMessageStatusUpdate: Logs the status update and attempts to update the corresponding message record in the database, including error details if present.logMessage: A helper to encapsulate database logging logic, now with statusDetails.
- Create Webhook Functions: Generate the functions to handle HTTP requests from Vonage:
yarn rw g function whatsappInbound --no-typescript
yarn rw g function whatsappStatus --no-typescript
- We use --no-typescript for simplicity here, but feel free to use TypeScript.
- Implement Inbound Webhook Function: Open
api/src/functions/whatsappInbound.js(or.ts) and add:
import { logger } from 'src/lib/logger'
import { verifySignature } from '@vonage/jwt'
import { handleInboundWhatsAppMessage } from 'src/services/vonage/vonage'
export const handler = async (event, context) => {
logger.info('Inbound WhatsApp webhook received')
logger.debug({ headers: event.headers, body: event.body }, 'Inbound Request Details')
const signatureSecret = process.env.VONAGE_API_SIGNATURE_SECRET
if (!signatureSecret) {
logger.error('VONAGE_API_SIGNATURE_SECRET is not set. Cannot verify inbound webhook.')
return { statusCode: 500, body: JSON.stringify({ error: 'Configuration error' }) }
}
try {
const authToken = event.headers.authorization?.split(' ')[1]
if (!authToken) {
logger.warn('Authorization header missing or malformed on inbound webhook')
return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) }
}
if (!verifySignature(authToken, signatureSecret)) {
logger.warn('Invalid JWT signature received on inbound webhook')
return { statusCode: 401, body: JSON.stringify({ error: 'Invalid signature' }) }
}
logger.info('Inbound webhook JWT signature verified successfully')
} catch (error) {
logger.error({ error }, 'Error during JWT verification on inbound webhook')
return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) }
}
let body
try {
body = typeof event.body === 'string' ? JSON.parse(event.body) : event.body;
} catch (parseError) {
logger.error({ parseError, rawBody: event.body }, 'Failed to parse inbound webhook body')
return { statusCode: 400, body: JSON.stringify({ error: 'Invalid JSON payload' }) }
}
if (!body?.from?.number || !body.message_uuid) {
logger.warn({ payload: body }, 'Received incomplete or unexpected inbound payload format')
return {
statusCode: 400,
body: JSON.stringify({ error: 'Invalid payload format' }),
}
}
let messageBody = ''
if (body.message?.content?.text) {
messageBody = body.message.content.text
} else if (body.message?.content?.image) {
messageBody = `[Image: ${body.message.content.image.url}]`
} else if (body.message?.content?.file) {
messageBody = `[File: ${body.message.content.file.url}]`
} else {
logger.warn({ payload: body }, 'Unsupported message type received')
return {
statusCode: 400,
body: JSON.stringify({ error: 'Unsupported message type' }),
}
}
const fromNumber = body.from.number
const vonageMessageId = body.message_uuid
try {
await handleInboundWhatsAppMessage({
fromNumber,
messageBody,
vonageMessageId,
})
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Webhook received successfully' }),
}
} catch (error) {
logger.error({ error }, 'Error processing inbound WhatsApp message')
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ error: 'Internal server error' }),
}
}
}
- Security: This function now includes JWT signature verification, just like the status webhook, ensuring the inbound message request is genuinely from Vonage.
- It parses the JSON body safely.
- It extracts the sender's number (from.number), message text (message.content.text), and message ID (message\_uuid).
- Non-text messages: Added basic handling for images and files. Production apps should extract URLs and process media appropriately.
- Webhook Timeout: Vonage expects a 200 OK response within 5 seconds. If processing takes longer, acknowledge immediately and queue work asynchronously.
- It calls the handleInboundWhatsAppMessage service function.
- It returns a 200 OK status to Vonage. Basic error handling returns appropriate status codes.
- Implement Status Webhook Function: Open
api/src/functions/whatsappStatus.js(or.ts) and add:
import { logger } from 'src/lib/logger'
import { verifySignature } from '@vonage/jwt'
import { handleMessageStatusUpdate } from 'src/services/vonage/vonage'
export const handler = async (event, context) => {
logger.info('WhatsApp status webhook received')
logger.debug({ headers: event.headers, body: event.body }, 'Status Request Details')
const signatureSecret = process.env.VONAGE_API_SIGNATURE_SECRET
if (!signatureSecret) {
logger.error('VONAGE_API_SIGNATURE_SECRET is not set. Cannot verify status webhook.')
return { statusCode: 500, body: JSON.stringify({ error: 'Configuration error' }) }
}
try {
const authToken = event.headers.authorization?.split(' ')[1]
if (!authToken) {
logger.warn('Authorization header missing or malformed on status webhook')
return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) }
}
if (!verifySignature(authToken, signatureSecret)) {
logger.warn('Invalid JWT signature received on status webhook')
return { statusCode: 401, body: JSON.stringify({ error: 'Invalid signature' }) }
}
logger.info('Status webhook JWT signature verified successfully')
} catch (error) {
logger.error({ error }, 'Error during JWT verification on status webhook')
return { statusCode: 401, body: JSON.stringify({ error: 'Unauthorized' }) }
}
let body
try {
body = typeof event.body === 'string' ? JSON.parse(event.body) : event.body;
} catch (parseError) {
logger.error({ parseError, rawBody: event.body }, 'Failed to parse status webhook body')
return { statusCode: 400, body: JSON.stringify({ error: 'Invalid JSON payload' }) }
}
if (!body?.message_uuid || !body?.status || !body?.timestamp) {
logger.warn({ payload: body }, 'Received incomplete status payload format')
return {
statusCode: 400,
body: JSON.stringify({ error: 'Invalid payload format' }),
}
}
const vonageMessageId = body.message_uuid
const status = body.status
const timestamp = body.timestamp
const error = body.error
try {
await handleMessageStatusUpdate({
vonageMessageId,
status,
timestamp,
error,
})
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Status received successfully' }),
}
} catch(error) {
logger.error({ error }, 'Error processing message status update')
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ error: 'Internal server error' }),
}
}
}
- Crucially: This function first verifies the JWT signature using verifySignature and your VONAGE\_API\_SIGNATURE\_SECRET. Do not skip this step.
- It safely parses the body, extracts the relevant status information.
- It calls the handleMessageStatusUpdate service function.
- It returns 200 OK.
Possible Message Status Values: Common status values from Vonage Messages API (source: Vonage API Errors - Messages):
- submitted: Message accepted by Vonage
- delivered: Message delivered to recipient
- read: Message read by recipient (if supported by channel)
- failed: Message delivery failed
- rejected: Message rejected by carrier or Vonage
- undeliverable: Message could not be delivered
3. Building a GraphQL API for WhatsApp Messaging
RedwoodJS handles the API layer primarily through GraphQL. While our core interaction uses webhook Functions (plain HTTP endpoints), you could expose functionality via GraphQL if needed for triggering manual sends or building admin interfaces.
- Webhook Nature: Receiving messages is inherently event-driven via webhooks. Vonage pushes data to your function endpoints.
- Triggering Outbound Messages: You could create a GraphQL mutation to trigger sending an outbound message on demand from your web UI or admin panel.
Example GraphQL Mutation (Conceptual):
- Define Schema: Add to
api/src/graphql/vonage.sdl.ts:
// api/src/graphql/vonage.sdl.ts
export const schema = gql`
type Mutation {
sendManualWhatsApp(to: String!, text: String!): SendWhatsAppResult! @requireAuth
}
type SendWhatsAppResult {
success: Boolean!
messageUUID: String
error: String
}
`
- Implement Service Function: Add a wrapper in
api/src/services/vonage/vonage.ts:
export const sendManualWhatsApp = ({ to, text }: { to: string; text: string }) => {
logger.info({ to }, 'Manual WhatsApp send triggered via GraphQL')
return sendWhatsAppMessage({ to, text })
}
- Generate Types:
yarn rw g types - Test: Use the Redwood GraphQL playground (
yarn rw dev, navigate to/graphql) to call the mutation.
Authentication with @requireAuth:
The @requireAuth directive requires authentication setup. To implement:
- Set up authentication provider (dbAuth, Auth0, Clerk, etc.):
yarn rw setup auth dbAuth
- Follow the setup wizard to create User model in Prisma schema
- Run migrations:
yarn rw prisma migrate dev
- The
@requireAuthdirective will now enforce authentication on the mutation
For detailed authentication setup, see RedwoodJS Authentication docs.
This section is optional for the basic webhook setup but shows how to integrate with Redwood's standard API pattern if needed.
4. Understanding Vonage WhatsApp Integration Components
This was covered extensively during setup and implementation. Key points:
- Credentials: API Key, Secret, Application ID, Private Key Content, Signature Secret stored securely in .env (use proper secret management like platform environment variables or a secrets manager in production).
- SDK Initialization: Using @vonage/server-sdk and @vonage/messages in the service layer (api/src/services/vonage/vonage.ts), configured with credentials (reading private key content from env var) and the sandbox apiHost (which should be removed for production).
- Webhook Configuration: Setting the correct Inbound and Status URLs in both the Vonage Application and Messages API Sandbox settings, pointing to your Ngrok URL + Redwood Function paths (/.redwood/functions/whatsappInbound, /.redwood/functions/whatsappStatus).
- Environment Variables: Each .env variable's purpose and origin is detailed in Section 1, Step 4.
Common Vonage Integration Issues:
| Issue | Symptom | Solution |
|---|---|---|
| Webhooks not received | No logs appear when sending messages | Verify ngrok URL hasn't changed, check webhook URLs in Vonage Dashboard, ensure dev server is running |
| 401 Unauthorized on webhooks | Signature verification fails | Check VONAGE_API_SIGNATURE_SECRET is correct, ensure @vonage/jwt package
is installed |
| Message sends fail with 1420 | Invalid sender error | Ensure VONAGE_WHATSAPP_NUMBER matches sandbox number, verify number is in E.164 format
|
| Message sends fail with 1430 | Invalid recipient error | Recipient number must be allowlisted in sandbox, verify E.164 format with + prefix |
| Private key errors | Application fails to initialize | Verify entire key including BEGIN/END lines is in VONAGE_PRIVATE_KEY_CONTENT, check for
newline encoding |
| Rate limiting (error 1000) | Too many requests | Implement exponential backoff, upgrade Vonage plan, or reduce message frequency |
| Database errors | Message logging fails | Run yarn rw prisma migrate dev, verify DATABASE_URL is set correctly |
5. Error Handling, Logging, and Retry Mechanisms
- Logging: Redwood's built-in
pinologger (api/src/lib/logger.ts) is used throughout the service and function code (logger.info,logger.error,logger.warn,logger.debug). SDK logs are also piped to Redwood's logger. Check your console output during development. Configure production log levels and potentially ship logs to a logging service. - Error Handling:
- try...catch blocks are used in service functions (sendWhatsAppMessage, database interactions) and webhook handlers.
- Specific errors (e.g., JWT verification failure, Vonage API errors, JSON parsing errors) are caught and logged.
- Webhook handlers return appropriate HTTP status codes (200 for success, 400/401 for client errors, 500 for server errors). Avoid leaking internal error details in responses.
- Retry Mechanisms:
- Vonage Webhooks: Vonage has built-in retry logic if your webhook endpoints (whatsappInbound, whatsappStatus) don't return a 2xx status code promptly (within 5 seconds). Vonage will retry with exponential backoff for up to 24 hours. Ensure your functions respond quickly. If processing takes longer, acknowledge the webhook immediately (return 200 OK) and handle the processing asynchronously (e.g., using Redwood experimental background jobs or a dedicated queue).
- Outbound Messages: Example retry implementation with exponential backoff:
export const sendWhatsAppMessageWithRetry = async ({
to,
text,
maxRetries = 3,
}: {
to: string
text: string
maxRetries?: number
}) => {
let lastError: any
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const result = await sendWhatsAppMessage({ to, text })
if (result.success) {
return result
}
lastError = result.error
} catch (error) {
lastError = error
logger.warn(
{ attempt: attempt + 1, maxRetries, error },
'Retry attempt failed'
)
}
if (attempt < maxRetries - 1) {
const delayMs = Math.pow(2, attempt) * 1000
await new Promise(resolve => setTimeout(resolve, delayMs))
}
}
logger.error({ lastError, maxRetries }, 'All retry attempts exhausted')
return { success: false, error: 'Maximum retries exceeded' }
}
Vonage API Error Codes:
Key error codes from Vonage Messages API Errors:
| Error Code | Description | Action |
|---|---|---|
1000 |
Throttled - Rate limit exceeded | Implement backoff, reduce send rate |
1010 |
Missing params | Validate all required fields before sending |
1020 |
Invalid params | Check phone number format (E.164), message length |
1030 |
Internal error | Retry with exponential backoff |
1050 |
Number barred | Remove number from contact list |
1070 |
Partner quota exceeded | Top up account balance |
1120 |
Illegal Sender Address | Verify sender number is correct sandbox/production number |
1160 |
Non White-listed Destination | Add recipient to sandbox allowlist |
1170 |
Invalid MSISDN | Validate phone number is in E.164 format |
1180 |
Absent Subscriber Temporary | Retry later (temporary network issue) |
1190 |
Absent Subscriber Permanent | Remove from contact list |
1240 |
Illegal Number | User has opted out, respect opt-out |
1260 |
Destination unreachable | Check country/carrier support |
1330 |
Unknown | Validate phone number, retry |
1340 |
Outside allowed window | WhatsApp requires prior user-initiated contact within 24h for marketing messages |
1400 |
Unsupported channel | Verify channel is enabled in your Vonage account |
1420 |
Invalid sender | Check VONAGE_WHATSAPP_NUMBER configuration |
1430 |
Invalid recipient | Ensure recipient is allowlisted and in E.164 format |
1460 |
Daily message limit exceeded | Spread messages over time or upgrade account |
For the complete list, see Vonage Messages API Errors.
Summary
This comprehensive guide covered:
- Project Setup: RedwoodJS initialization, dependency installation, environment configuration
- Database Schema: Prisma MessageLog model for tracking all messages
- Core Implementation: Vonage service with E.164 validation, webhook functions with JWT verification
- Security: Environment variable management, signature verification, input validation
- Error Handling: Comprehensive error codes, retry mechanisms, logging strategies
- Production Considerations: Authentication, rate limiting, webhook timeouts
Next Steps:
- Replace sandbox number with production WhatsApp Business API number
- Remove apiHost: 'https://messages-sandbox.nexmo.com' from Vonage initialization
- Implement custom business logic for message handling
- Add rate limiting and circuit breakers for production resilience
- Set up monitoring and alerting for webhook failures
- Configure log aggregation for production debugging
Additional Resources:
- Vonage Messages API Documentation
- RedwoodJS Documentation
- WhatsApp Business API Requirements
- E.164 Phone Number Format
- Vonage Node.js SMS Tutorial
- RedwoodJS SMS Integration Guide
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 β