Frequently Asked Questions
Use the Vonage Messages API with the Vonage Node.js SDK. Set up an Express route to handle requests, then use the SDK to send SMS messages via the API. This allows you to integrate SMS functionality directly into your Node.js applications.
The Vonage Messages API is a service that allows you to send and receive messages through different channels like SMS, WhatsApp, and more. This tutorial focuses on using it to send SMS notifications from your Node.js app.
Dotenv loads environment variables from a .env
file. This keeps sensitive credentials like your Vonage API key and secret out of your source code, which improves security and prevents accidental exposure.
While the provided Node.js code uses the Messages API directly, it's beneficial to set the default SMS API in your Vonage account settings to the Messages API for consistency, especially if you plan to implement features involving webhook functionality, as webhook formats differ between the legacy SMS API and the Messages API.
No, trial accounts have restrictions. You can only send SMS messages to numbers you've verified in your Vonage Dashboard under 'Getting Started' > 'Add test numbers'. For unrestricted sending, you'll need to upgrade to a paid account.
Use npm install express @vonage/server-sdk dotenv
. This command installs Express for the web framework, the Vonage Server SDK to interface with the Vonage API, and dotenv to securely manage environment variables.
The .gitignore
file specifies files and directories that Git should ignore when tracking changes. It’s crucial to add node_modules
and .env
to your .gitignore
to prevent accidentally committing dependencies and your sensitive Vonage API credentials.
First, install it with npm, then initialize it with your API key and secret, which you obtain from the Vonage API Dashboard. These credentials are loaded into your project from the '.env' file via dotenv.
E.164 is an international standard for phone number formatting. It includes a '+' sign followed by the country code and the national subscriber number without any spaces or special characters. For example, a US number would be +14155550100.
Create a POST route handler in your Express app (e.g., app.post('/send-sms', ...)
). This route will receive the recipient's phone number and the message text from a request. Use this data to send the SMS using the Vonage SDK.
A 400 Bad Request error indicates an issue with the client's request, typically due to missing required fields or invalid formatting. Ensure the request body contains 'to' and 'text' fields, and that the 'to' number follows E.164 format.
After starting your server, use a command like curl -X POST -H "Content-Type: application/json" -d '{"to": "+1XXXXXXXXXX", "text": "Test message"}' http://localhost:3000/send-sms
. Replace +1XXXXXXXXXX with a valid E.164 formatted phone number and 'Test message' with your desired SMS content.
This usually occurs with trial Vonage accounts. Ensure the recipient's phone number is added to your allowed list of test numbers in the Vonage Dashboard. If you need to send to any number, upgrade to a paid account.
Use a try-catch block around your API calls to handle errors. Log these errors for debugging and return appropriate error responses to the client. For production, consider using a logging framework like Winston or Pino.
Send SMS with MessageBird, Next.js, and Supabase
This comprehensive guide walks you through building a Next.js application that sends SMS messages using the MessageBird API and logs message data to Supabase. You'll create a production-ready API route with proper error handling, validation, and database integration—perfect for building SMS notifications, two-factor authentication, or transactional messaging systems.
Why This Stack?
By the end of this tutorial, you'll have a functional Next.js API endpoint at
/api/send-sms
that accepts SMS requests, sends them via MessageBird, and logs all transactions to a Supabase database for tracking and analytics.Key Technologies:
System Architecture:
Prerequisites:
1. Setting Up Your Next.js Project with MessageBird and Supabase
Next.js provides an optimized setup command that scaffolds a complete project structure.
Create Next.js Project: Open your terminal and run the official Next.js creation command:
When prompted, select these options:
Navigate to Project Directory:
Install Required Dependencies: Add MessageBird SDK and Supabase client:
messagebird
: Official MessageBird Node.js SDK for SMS API integration@supabase/supabase-js
: Supabase JavaScript client for database operationsCreate Environment Variables File: Next.js uses
.env.local
for environment variables that you should never commit:Configure
.env.local
: Add your API credentials (replace placeholders with actual values from your dashboards):Variable Explanations:
MESSAGEBIRD_API_KEY
: Your MessageBird access key from the API Access page. Test keys have thetest_
prefix.MESSAGEBIRD_ORIGINATOR
: The sender ID (phone number in E.164 format like+14155550100
or alphanumeric string up to 11 characters). Note: Alphanumeric senders aren't supported in all countries including the United States.NEXT_PUBLIC_SUPABASE_URL
: Your Supabase project URL from Project Settings > APINEXT_PUBLIC_SUPABASE_ANON_KEY
: Your Supabase anonymous public key (safe for client-side use with RLS policies)Security Note: The
NEXT_PUBLIC_
prefix makes variables accessible in the browser. Only use this for public keys. KeepMESSAGEBIRD_API_KEY
without the prefix to ensure it stays server-side only.Update
.gitignore
: Next.js automatically includes.env.local
in.gitignore
, but verify it contains:2. Setting Up Supabase Database
Before writing code, create a database table to store SMS message logs.
Creating the SMS Logs Table
Navigate to SQL Editor: In your Supabase Dashboard, go to the SQL Editor section.
Create Table with SQL: Run this SQL to create an
sms_logs
table with proper indexes:Schema Explanation:
id
: UUID primary key, automatically generatedrecipient
: Phone number that received the SMS (E.164 format)message
: Content of the SMS sentoriginator
: Sender ID used (your MessageBird number)message_id
: MessageBird's unique message identifier for trackingstatus
: Message status (sent, failed, etc.)created_at
/updated_at
: Timestamps for record trackingVerify Table Creation: Go to the Table Editor in your Supabase Dashboard and confirm the
sms_logs
table exists with the correct columns.Security Note: Row Level Security (RLS) is enabled to control access. The policies allow API routes (using service role key) to insert and all users to read. Adjust policies based on your security requirements.
3. Creating the Next.js API Route for SMS Sending
Next.js API Routes provide serverless functions for backend logic. Any file in
pages/api/
becomes an API endpoint.Create the API Route File
Create API Directory Structure: If not already present, create the pages/api folder:
Create
send-sms.ts
Route Handler: Createpages/api/send-sms.ts
:Code Walkthrough:
Client Initialization: Initialize the MessageBird client once at module level per SDK best practices. The Supabase client uses environment variables from
.env.local
.Method Check: Next.js API routes handle all HTTP methods. We restrict this endpoint to POST only.
Input Validation: Validates required fields and E.164 phone format. E.164 is the international standard format required by MessageBird.
SMS Sending: Uses
messages.create()
method from MessageBird SDK with callback-style API wrapped in Promise for async/await compatibility.Database Logging: Inserts success/failure record to Supabase. Non-blocking error handling ensures SMS delivery isn't blocked by logging failures.
Error Handling: Catches MessageBird API errors and returns structured error responses with proper HTTP status codes (400 for validation, 500 for server errors).
4. Testing Your SMS Integration
Start the Development Server
Run Next.js Development Server:
Next.js displays output confirming the server is running:
Verify Environment Variables: Check the terminal for any errors about missing environment variables. If you see errors, verify your
.env.local
file.Test with cURL
Send Test SMS: Open a new terminal and run:
Replace
+1XXXXXXXXXX
with a valid phone number in E.164 format. For MessageBird test accounts, verify the destination number first in your dashboard.Expected Success Response:
Validation Error Example (missing field):
Response:
Format Validation Error (invalid phone format):
Response:
Verify in Dashboards
MessageBird Dashboard: Navigate to Developers > Message Logs to see sent messages with delivery status.
Supabase Dashboard:
sms_logs
tablerecipient
,message
,message_id
, andstatus
valuescreated_at
timestamps match your test timing5. Error Handling and Common Issues
MessageBird-Specific Error Codes
MessageBird returns structured error responses with error codes:
2
MESSAGEBIRD_API_KEY
in.env.local
9
10
20
25
99
Supabase Connection Errors
Common Supabase errors and solutions:
NEXT_PUBLIC_SUPABASE_URL
andNEXT_PUBLIC_SUPABASE_ANON_KEY
are correctsms_logs
table exists in public schemaNext.js API Route Debugging
Environment Variables Not Loading:
.env.local
is in project root directory (same level aspackage.json
)npm run dev
) after changing.env.local
KEY=value
notKEY="value"
NEXT_PUBLIC_
) are only available in API routesModule Not Found Errors:
TypeScript Errors:
6. Security Best Practices for Production SMS Applications
Environment Variable Security
.env.local
to version control. Next.js automatically ignores it in.gitignore
.NEXT_PUBLIC_
prefix forMESSAGEBIRD_API_KEY
)API Route Protection
For production, add authentication to prevent unauthorized SMS sending:
Rate Limiting
Implement rate limiting using Next.js middleware to prevent abuse:
Production Rate Limiting: For distributed deployments (Vercel, AWS), use Upstash Rate Limiting with Redis or Vercel Edge Middleware rate limiting.
Supabase Row Level Security
The RLS policies created earlier protect your database. For production:
Store the service role key separately for API routes:
7. Deployment Considerations
Deploying to Vercel
Vercel (creators of Next.js) provides optimal Next.js hosting:
Install Vercel CLI:
Deploy:
Configure Environment Variables:
.env.local
:MESSAGEBIRD_API_KEY
MESSAGEBIRD_ORIGINATOR
NEXT_PUBLIC_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY
test_
prefix) for productionRedeploy: After adding environment variables, redeploy:
Serverless Function Considerations
Next.js API routes on Vercel run as serverless functions with limitations:
Alternative Deployment Platforms
Netlify:
Add environment variables in Netlify Dashboard > Site settings > Environment variables.
AWS Amplify:
Follow Next.js deployment guide and configure environment variables in Amplify Console.
Self-Hosted (VPS/EC2):
Use process managers like PM2 and ensure environment variables are set in system environment or
.env.production.local
.8. Next Steps and Enhancements
Receive SMS Messages (Webhooks)
Implement inbound SMS handling using MessageBird webhooks:
Create Webhook Endpoint (
pages/api/sms-webhook.ts
):Configure in MessageBird: Go to Dashboard > Developers > Webhooks, set webhook URL to
https://your-domain.com/api/sms-webhook
Delivery Status Tracking
Track SMS delivery status by implementing a webhook for delivery reports:
Configure delivery report webhook URL in MessageBird Dashboard.
Build a Dashboard UI
Create a simple dashboard to view SMS logs:
SMS Templates
Store reusable templates in Supabase:
Verification Checklist
npx create-next-app
.env.local
configured with all required keyssms_logs
table created with RLS policiespages/api/send-sms.ts
npm run dev
)sms_logs
tableConclusion
You now have a production-ready Next.js application that sends SMS messages via MessageBird and logs transactions to Supabase. This foundation supports building notification systems, two-factor authentication, marketing campaigns, and customer communication platforms.
Key Resources:
For questions or issues, consult the official documentation or contact MessageBird Support or Supabase Support.