Tutorials

Twilio WhatsApp Integration with Next.js and Supabase: Complete Guide

A step-by-step guide to building a Node.js/Express application for sending and receiving WhatsApp messages via the Vonage Messages API, including setup, webhooks, signature verification, and deployment considerations.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 1, 2026 β€’ 18 min read

Developer Quick-Start: A step-by-step guide to building a Node.js/Express application for sending and receiving WhatsApp messages via the Vonage Messages API, including setup, webhooks, signature verification, and deployment considerations. 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 comprehensive guide demonstrates how to build a production-ready WhatsApp messaging application using Twilio's WhatsApp API, Next.js for serverless API routes, and Supabase for authentication and data persistence. You'll learn to send and receive WhatsApp messages programmatically, implement secure user authentication, store conversation history in a PostgreSQL database, and handle real-time webhook callbacks.

By completing this tutorial, you'll have a functional Next.js application that:

  1. Sends WhatsApp messages using the Twilio WhatsApp Sandbox or production number
  2. Receives and processes inbound messages through Twilio webhook integration
  3. Authenticates users with Supabase Auth for secure access control
  4. Stores message history in a Supabase PostgreSQL database with real-time capabilities
  5. Handles delivery status updates for message tracking and analytics

This solution addresses common business needs for integrating WhatsApp messaging into web applications for customer support, automated notifications, and conversational workflows.

Technologies and Stack

Core Technologies:

  • Next.js 14+: React framework with App Router for building frontend UI and serverless API routes
  • Supabase: Open-source Backend-as-a-Service providing PostgreSQL database, authentication, and real-time subscriptions
  • Twilio WhatsApp API: Cloud communications platform for programmatic WhatsApp message sending and receiving
  • Node.js 18+: JavaScript runtime environment (v18 LTS or v20 recommended for Next.js 14+ compatibility)
  • TypeScript (Optional but Recommended): Type-safe development for production applications

Key Dependencies:

  • twilio - Official Twilio SDK for Node.js with WhatsApp API support
  • @supabase/supabase-js - Supabase client library for database operations and authentication
  • @supabase/ssr - Server-side rendering helpers for Next.js with Supabase
  • @supabase/auth-helpers-nextjs - Authentication utilities for Next.js middleware and API routes
  • ngrok - Local development tunnel for testing webhooks during development

Prerequisites

Required Accounts and Tools:

  • Twilio Account: Sign up for free - includes trial credits and WhatsApp Sandbox access
  • Supabase Account: Create a free project - includes 500MB PostgreSQL database and 50,000 monthly active users
  • Node.js 18+: Install from nodejs.org with npm or yarn package manager
  • WhatsApp Account: Personal WhatsApp installed on smartphone for testing messages
  • ngrok: Install ngrok for exposing local development server to internet

Optional for Production:

  • WhatsApp Business Account (WABA) for production messaging capabilities beyond Sandbox limitations
  • Twilio phone number with WhatsApp capability ($1-$2/month)
  • Basic understanding of React, Next.js API routes, and SQL queries

Tutorial Specifications:

  • Estimated Completion Time: 45-60 minutes
  • Skill Level Required: Intermediate (familiarity with React and REST APIs)
  • Development Cost: $0 (free tiers available for all services)

System Architecture

graph TB
    subgraph Client Layer
        A[Next.js Frontend] --> B[React Components]
        B --> C[Supabase Auth UI]
    end

    subgraph Next.js Server
        D[API Routes] --> E[/api/send-message]
        D --> F[/api/webhook/inbound]
        D --> G[/api/webhook/status]
    end

    subgraph Supabase Backend
        H[PostgreSQL Database] --> I[messages table]
        H --> J[users table]
        K[Supabase Auth] --> L[JWT Tokens]
    end

    subgraph Twilio Platform
        M[Twilio WhatsApp API]
        N[WhatsApp Sandbox/Production]
    end

    O[User WhatsApp] <--> P[WhatsApp Servers]
    P <--> M
    M --> F
    M --> G
    E --> M
    F --> H
    A --> D
    K --> A
    D --> H

    style Client Layer fill:#e1f5ff,stroke:#01579b,stroke-width:2px
    style Next.js Server fill:#f3e5f5,stroke:#4a148c,stroke-width:2px
    style Supabase Backend fill:#e8f5e9,stroke:#1b5e20,stroke-width:2px
    style Twilio Platform fill:#fff3e0,stroke:#e65100,stroke-width:2px

Data Flow Explanation:

  1. Authentication: User logs in through Supabase Auth in Next.js frontend
  2. Message Sending: Authenticated user sends WhatsApp message via /api/send-message API route
  3. Twilio Integration: API route uses Twilio SDK to send message through WhatsApp API
  4. Message Delivery: Twilio delivers message to recipient's WhatsApp account
  5. Inbound Messages: When recipient replies, Twilio sends webhook POST request to /api/webhook/inbound
  6. Data Persistence: Webhook handler validates request and stores message in Supabase database
  7. Real-time Updates: Frontend queries Supabase for message history with real-time subscriptions
  8. Status Tracking: Delivery status updates received at /api/webhook/status endpoint

Expected Outcome:

A production-ready Next.js application featuring Twilio WhatsApp integration, Supabase authentication, and persistent message storage - ready for deployment to Vercel, Netlify, or any Node.js hosting platform.

1. Setting Up Your Next.js Project

Let's create a new Next.js project configured for Twilio WhatsApp integration and Supabase.

1.1 Initialize Next.js Project

Create a new Next.js 14 application with App Router (recommended for modern Next.js development):

npx create-next-app@latest twilio-whatsapp-nextjs --typescript --app --tailwind
cd twilio-whatsapp-nextjs

When prompted, choose:

  • TypeScript: Yes (recommended for type safety)
  • ESLint: Yes
  • Tailwind CSS: Yes (for UI styling)
  • App Router: Yes (required for this tutorial)
  • Import alias: No (or customize as preferred)

1.2 Install Required Dependencies

Install Twilio SDK, Supabase client, and necessary utilities:

npm install twilio @supabase/supabase-js @supabase/ssr @supabase/auth-helpers-nextjs

Install development dependencies:

npm install --save-dev ngrok

Dependency Explanation:

  • twilio: Official Twilio SDK providing WhatsApp message sending, SMS, and voice capabilities
  • @supabase/supabase-js: Core Supabase client for database queries and authentication
  • @supabase/ssr: Server-side rendering utilities for Next.js with automatic cookie handling
  • @supabase/auth-helpers-nextjs: Middleware and helpers for Next.js authentication flows
  • ngrok: Exposes local development server for Twilio webhook testing

1.3 Project Structure

Your project should have this structure:

twilio-whatsapp-nextjs/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ send-message/
β”‚   β”‚   β”‚   └── route.ts
β”‚   β”‚   └── webhook/
β”‚   β”‚       β”œβ”€β”€ inbound/
β”‚   β”‚       β”‚   └── route.ts
β”‚   β”‚       └── status/
β”‚   β”‚           └── route.ts
β”‚   β”œβ”€β”€ dashboard/
β”‚   β”‚   └── page.tsx
β”‚   β”œβ”€β”€ login/
β”‚   β”‚   └── page.tsx
β”‚   β”œβ”€β”€ layout.tsx
β”‚   └── page.tsx
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ supabase/
β”‚   β”‚   β”œβ”€β”€ client.ts
β”‚   β”‚   └── server.ts
β”‚   └── twilio.ts
β”œβ”€β”€ .env.local
β”œβ”€β”€ .gitignore
β”œβ”€β”€ next.config.js
β”œβ”€β”€ package.json
└── tsconfig.json

2. Configuring Twilio WhatsApp Sandbox

Before writing code, set up Twilio WhatsApp Sandbox for testing message functionality.

2.1 Create Twilio Account and Get Credentials

  1. Sign up: Visit twilio.com/try-twilio and create a free account
  2. Verify phone number: Complete phone verification during signup
  3. Access Dashboard: Navigate to Twilio Console
  4. Copy credentials: Find your Account SID and Auth Token on the dashboard homepage

Important: Keep your Auth Token secure - it provides full access to your Twilio account.

2.2 Set Up WhatsApp Sandbox

  1. Navigate to WhatsApp: In Twilio Console, go to Messaging > Try it out > Send a WhatsApp message
  2. Activate Sandbox: Click Join Sandbox or acknowledge terms
  3. Connect your WhatsApp:
  • Scan the QR code with your phone's WhatsApp, OR
  • Send the join message (e.g., join <keyword>) to the displayed Sandbox number
  1. Confirm connection: You should receive a confirmation message in WhatsApp
  2. Note Sandbox number: Copy the Sandbox WhatsApp number (e.g., +1 415 523 8886)

Sandbox Limitations:

  • Messages only work with pre-approved phone numbers (those who joined via QR/keyword)
  • 1 message per 3 seconds rate limit
  • Pre-approved message templates only for business-initiated messages
  • For production, you'll need a WhatsApp Business Account (WABA)

2.3 Configure Webhook URLs (Return After ngrok Setup)

We'll configure these URLs in Step 5 after setting up ngrok:

  • Inbound URL: https://<your-ngrok-url>/api/webhook/inbound
  • Status URL: https://<your-ngrok-url>/api/webhook/status

3. Setting Up Supabase Database and Authentication

Configure Supabase for user authentication and message storage.

3.1 Create Supabase Project

  1. Sign up: Visit supabase.com and create account
  2. New Project: Click New Project in dashboard
  3. Configure project:
  • Name: twilio-whatsapp-app
  • Database Password: Generate secure password (save it!)
  • Region: Choose closest to your users
  • Pricing Plan: Free (sufficient for development)
  1. Wait for setup: Project creation takes 1-2 minutes

3.2 Get Supabase Credentials

  1. Navigate to Settings: Click Settings > API in project dashboard
  2. Copy credentials:
  • Project URL: https://<your-project>.supabase.co
  • Anon/Public Key: eyJ... (safe for client-side use)
  • Service Role Key: eyJ... (keep secure, server-side only)

3.3 Create Database Schema

Create tables for storing messages and user data.

  1. Open SQL Editor: Click SQL Editor in Supabase dashboard
  2. Create messages table: Run this SQL:
CREATE TABLE messages (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  from_number TEXT NOT NULL,
  to_number TEXT NOT NULL,
  message_body TEXT NOT NULL,
  message_sid TEXT UNIQUE,
  status TEXT DEFAULT 'sent',
  direction TEXT NOT NULL CHECK (direction IN ('inbound', 'outbound')),
  media_url TEXT,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX idx_messages_user_id ON messages(user_id);
CREATE INDEX idx_messages_created_at ON messages(created_at DESC);
CREATE INDEX idx_messages_message_sid ON messages(message_sid);

ALTER TABLE messages ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own messages"
  ON messages FOR SELECT
  USING (auth.uid() = user_id);

CREATE POLICY "Users can insert own messages"
  ON messages FOR INSERT
  WITH CHECK (auth.uid() = user_id);

CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_messages_updated_at
  BEFORE UPDATE ON messages
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();
  1. Create user profiles table (optional): For storing additional user data:
CREATE TABLE user_profiles (
  id UUID REFERENCES auth.users(id) ON DELETE CASCADE PRIMARY KEY,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  whatsapp_number TEXT,
  display_name TEXT,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

ALTER TABLE user_profiles ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own profile"
  ON user_profiles FOR SELECT
  USING (auth.uid() = id);

CREATE POLICY "Users can update own profile"
  ON user_profiles FOR UPDATE
  USING (auth.uid() = id);

3.4 Configure Authentication

  1. Enable Email Auth: Go to Authentication > Providers > Enable Email
  2. Configure settings:
  • Enable email confirmations: OFF (for development)
  • Minimum password length: 6 characters
  1. Optional: Enable OAuth providers (Google, GitHub) for social login

4. Environment Configuration

Create .env.local file in project root with all necessary credentials:

TWILIO_ACCOUNT_SID=AC################################
TWILIO_AUTH_TOKEN=################################
TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886

NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ########################
SUPABASE_SERVICE_ROLE_KEY=eyJ########################

NEXT_PUBLIC_APP_URL=http://localhost:3000

WEBHOOK_SECRET=your-secure-random-string-here

Environment Variable Explanations:

  • TWILIO_ACCOUNT_SID: Your Twilio account identifier from Console dashboard
  • TWILIO_AUTH_TOKEN: Secret authentication token for Twilio API requests (keep secure!)
  • TWILIO_WHATSAPP_NUMBER: Sandbox number in format whatsapp:+14155238886 (include whatsapp: prefix)
  • NEXT_PUBLIC_SUPABASE_URL: Your Supabase project URL (publicly accessible)
  • NEXT_PUBLIC_SUPABASE_ANON_KEY: Public anonymous key safe for client-side use
  • SUPABASE_SERVICE_ROLE_KEY: Service role key with admin privileges (server-side only, never expose!)
  • NEXT_PUBLIC_APP_URL: Your application URL (localhost for dev, production URL for deployment)
  • WEBHOOK_SECRET: Random string for validating webhook authenticity (generate with openssl rand -hex 32)

Security Notes:

  • Add .env.local to .gitignore (should be included by default)
  • Never commit credentials to version control
  • Use environment variables in production hosting (Vercel, Netlify environment settings)
  • Rotate credentials if accidentally exposed

5. Implementing Twilio Client and Supabase Utilities

Create helper modules for Twilio SDK and Supabase clients.

5.1 Create Twilio Client (lib/twilio.ts)

import twilio from 'twilio';

if (!process.env.TWILIO_ACCOUNT_SID || !process.env.TWILIO_AUTH_TOKEN) {
  throw new Error('Missing Twilio credentials in environment variables');
}

export const twilioClient = twilio(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

export const TWILIO_WHATSAPP_NUMBER = process.env.TWILIO_WHATSAPP_NUMBER;

export async function sendWhatsAppMessage(
  to: string,
  body: string,
  mediaUrl?: string
) {
  try {
    const message = await twilioClient.messages.create({
      from: TWILIO_WHATSAPP_NUMBER,
      to: `whatsapp:${to}`,
      body: body,
      ...(mediaUrl && { mediaUrl: [mediaUrl] }),
    });

    return {
      success: true,
      messageSid: message.sid,
      status: message.status,
    };
  } catch (error) {
    console.error('Twilio send error:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

export function validateTwilioSignature(
  signature: string,
  url: string,
  params: Record<string, any>
): boolean {
  const authToken = process.env.TWILIO_AUTH_TOKEN;
  if (!authToken) return false;

  return twilio.validateRequest(authToken, signature, url, params);
}

5.2 Create Supabase Server Client (lib/supabase/server.ts)

import { createServerClient, type CookieOptions } from '@supabase/ssr';
import { cookies } from 'next/headers';

export function createClient() {
  const cookieStore = cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value, ...options });
          } catch (error) {

          }
        },
        remove(name: string, options: CookieOptions) {
          try {
            cookieStore.set({ name, value: '', ...options });
          } catch (error) {

          }
        },
      },
    }
  );
}

export function createAdminClient() {
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    {
      cookies: {
        get() { return undefined; },
        set() {},
        remove() {},
      },
    }
  );
}

5.3 Create Supabase Client Component Client (lib/supabase/client.ts)

import { createBrowserClient } from '@supabase/ssr';

export function createClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );
}

6. Building API Routes for WhatsApp Messaging

Implement Next.js API routes for sending messages and handling webhooks.

6.1 Send Message API Route (app/api/send-message/route.ts)

import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { sendWhatsAppMessage } from '@/lib/twilio';

export async function POST(request: NextRequest) {
  try {

    const supabase = createClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();

    if (authError || !user) {
      return NextResponse.json(
        { error: 'Unauthorized - Please log in' },
        { status: 401 }
      );
    }


    const body = await request.json();
    const { to, message, mediaUrl } = body;


    if (!to || !message) {
      return NextResponse.json(
        { error: 'Missing required fields: to, message' },
        { status: 400 }
      );
    }


    const phoneRegex = /^\+?[1-9]\d{1,14}$/;
    if (!phoneRegex.test(to)) {
      return NextResponse.json(
        { error: 'Invalid phone number format. Use E.164 format (e.g., +1234567890)' },
        { status: 400 }
      );
    }


    const result = await sendWhatsAppMessage(to, message, mediaUrl);

    if (!result.success) {
      return NextResponse.json(
        { error: `Failed to send message: ${result.error}` },
        { status: 500 }
      );
    }


    const { data: messageData, error: dbError } = await supabase
      .from('messages')
      .insert({
        user_id: user.id,
        from_number: process.env.TWILIO_WHATSAPP_NUMBER || '',
        to_number: `whatsapp:${to}`,
        message_body: message,
        message_sid: result.messageSid,
        status: result.status || 'sent',
        direction: 'outbound',
        ...(mediaUrl && { media_url: mediaUrl }),
      })
      .select()
      .single();

    if (dbError) {
      console.error('Database insert error:', dbError);

      return NextResponse.json(
        {
          success: true,
          messageSid: result.messageSid,
          warning: 'Message sent but failed to save to database'
        },
        { status: 200 }
      );
    }

    return NextResponse.json({
      success: true,
      messageSid: result.messageSid,
      message: messageData,
    });

  } catch (error) {
    console.error('Send message error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

6.2 Inbound Webhook Handler (app/api/webhook/inbound/route.ts)

import { NextRequest, NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/server';
import { validateTwilioSignature } from '@/lib/twilio';

export async function POST(request: NextRequest) {
  try {

    const formData = await request.formData();
    const params: Record<string, any> = {};

    formData.forEach((value, key) => {
      params[key] = value.toString();
    });


    const signature = request.headers.get('x-twilio-signature') || '';
    const url = request.url;

    if (!validateTwilioSignature(signature, url, params)) {
      console.error('Invalid Twilio webhook signature');
      return NextResponse.json(
        { error: 'Invalid signature' },
        { status: 403 }
      );
    }


    const {
      MessageSid,
      From,
      To,
      Body,
      NumMedia,
      MediaUrl0,
    } = params;

    console.log('Inbound WhatsApp message:', { From, Body });



    const supabase = createAdminClient();

    const { error: dbError } = await supabase
      .from('messages')
      .insert({
        from_number: From,
        to_number: To,
        message_body: Body || '',
        message_sid: MessageSid,
        status: 'received',
        direction: 'inbound',
        media_url: NumMedia && parseInt(NumMedia) > 0 ? MediaUrl0 : null,


      });

    if (dbError) {
      console.error('Database insert error:', dbError);

    }







    return new NextResponse('Message received', { status: 200 });

  } catch (error) {
    console.error('Inbound webhook error:', error);

    return new NextResponse('Error processed', { status: 200 });
  }
}

6.3 Status Webhook Handler (app/api/webhook/status/route.ts)

import { NextRequest, NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/server';
import { validateTwilioSignature } from '@/lib/twilio';

export async function POST(request: NextRequest) {
  try {

    const formData = await request.formData();
    const params: Record<string, any> = {};

    formData.forEach((value, key) => {
      params[key] = value.toString();
    });


    const signature = request.headers.get('x-twilio-signature') || '';
    const url = request.url;

    if (!validateTwilioSignature(signature, url, params)) {
      console.error('Invalid status webhook signature');
      return NextResponse.json(
        { error: 'Invalid signature' },
        { status: 403 }
      );
    }


    const {
      MessageSid,
      MessageStatus,
      ErrorCode,
      ErrorMessage,
    } = params;

    console.log('Message status update:', { MessageSid, MessageStatus });


    const supabase = createAdminClient();

    const updateData: Record<string, any> = {
      status: MessageStatus,
    };


    if (ErrorCode) {
      updateData.error_code = ErrorCode;
      updateData.error_message = ErrorMessage;
    }

    const { error: dbError } = await supabase
      .from('messages')
      .update(updateData)
      .eq('message_sid', MessageSid);

    if (dbError) {
      console.error('Database update error:', dbError);
    }


    return new NextResponse('Status updated', { status: 200 });

  } catch (error) {
    console.error('Status webhook error:', error);
    return new NextResponse('Error processed', { status: 200 });
  }
}

7. Testing the Integration

Set up ngrok for local webhook testing and test the complete flow.

7.1 Start ngrok Tunnel

  1. Open new terminal window in your project directory
  2. Start ngrok to expose port 3000:
ngrok http 3000
  1. Copy HTTPS URL from ngrok output (e.g., https://abc123.ngrok.io)
  2. Keep ngrok running in background terminal

7.2 Configure Twilio Webhooks

  1. Return to Twilio Console > Messaging > Settings > WhatsApp Sandbox Settings
  2. Set webhook URLs:
  • When a message comes in: https://abc123.ngrok.io/api/webhook/inbound
  • Status callback URL: https://abc123.ngrok.io/api/webhook/status
  1. HTTP Method: POST (default)
  2. Click Save

7.3 Run Development Server

npm run dev

Server should start at http://localhost:3000

7.4 Test Message Sending

  1. Authenticate a test user (implement login page or use Supabase Auth UI)
  2. Send test message via your application frontend or using curl:
curl -X POST http://localhost:3000/api/send-message \
  -H "Content-Type: application/json" \
  -H "Cookie: your-auth-cookie" \
  -d '{
    "to": "+1234567890",
    "message": "Hello from my Next.js WhatsApp app!"
  }'
  1. Check your WhatsApp - you should receive the message
  2. Reply to the message from your WhatsApp
  3. Check terminal logs - you should see the inbound webhook data
  4. Check Supabase - verify messages are stored in database

For more information on testing webhooks, see our guide on debugging Twilio webhooks.

8. Security Best Practices

Implement production-ready security measures for your WhatsApp integration.

8.1 Webhook Signature Verification

Always validate Twilio webhook signatures to prevent unauthorized requests:

if (!validateTwilioSignature(signature, url, params)) {
  return NextResponse.json({ error: 'Invalid signature' }, { status: 403 });
}

Why it matters: Without signature validation, anyone could send fake webhook requests to your API.

8.2 Authentication and Authorization

Require authentication for all message-sending operations:

const { data: { user }, error } = await supabase.auth.getUser();
if (error || !user) {
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

8.3 Rate Limiting

Implement rate limiting to prevent abuse (example using Next.js middleware):

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const rateLimit = new Map<string, { count: number; resetTime: number }>();

export function middleware(request: NextRequest) {
  const ip = request.ip || 'unknown';
  const now = Date.now();
  const limit = 10;
  const window = 60000;

  const userLimit = rateLimit.get(ip);

  if (!userLimit || now > userLimit.resetTime) {
    rateLimit.set(ip, { count: 1, resetTime: now + window });
    return NextResponse.next();
  }

  if (userLimit.count >= limit) {
    return NextResponse.json(
      { error: 'Rate limit exceeded' },
      { status: 429 }
    );
  }

  userLimit.count++;
  return NextResponse.next();
}

export const config = {
  matcher: '/api/send-message/:path*',
};

8.4 Input Validation and Sanitization

Validate and sanitize all user inputs:

const phoneRegex = /^\+?[1-9]\d{1,14}$/;
if (!phoneRegex.test(to)) {
  return NextResponse.json({ error: 'Invalid phone number' }, { status: 400 });
}

const sanitizedMessage = message.trim().slice(0, 1600);

8.5 Environment Variable Security

  • Never commit .env.local to version control
  • Use different credentials for development/production
  • Rotate credentials regularly
  • Use secrets management (Vercel Secrets, AWS Secrets Manager) in production

For comprehensive security guidance, see our API security best practices guide.

9. Deployment to Production

Deploy your Next.js WhatsApp application to a production hosting platform.

Vercel is the recommended platform for Next.js applications:

  1. Install Vercel CLI:
npm install -g vercel
  1. Deploy application:
vercel
  1. Set environment variables in Vercel dashboard:
  • Go to Settings > Environment Variables
  • Add all variables from .env.local
  • Ensure NEXT\_PUBLIC\_APP\_URL uses your production domain
  1. Update Twilio webhooks with production URLs:
  • Inbound: https://your-app.vercel.app/api/webhook/inbound
  • Status: https://your-app.vercel.app/api/webhook/status

9.2 Alternative Hosting Options

Netlify:

npm run build
netlify deploy --prod

Railway:

railway login
railway up

AWS/Google Cloud/Azure: Deploy as containerized application using Docker

9.3 Production Checklist

  • Environment variables configured in hosting platform
  • Twilio webhook URLs updated to production domain
  • Supabase Row Level Security (RLS) policies enabled
  • HTTPS enabled on custom domain
  • Rate limiting implemented
  • Error tracking configured (Sentry, LogRocket)
  • Monitoring and logging set up
  • WhatsApp Business Account (WABA) configured for production messaging

For detailed deployment instructions, see our Next.js deployment guide.

10. Troubleshooting Common Issues

Issue: Webhooks not receiving data

Symptoms: Inbound messages not appearing in database, no logs in console

Solutions:

  1. Verify ngrok is running and URL matches Twilio webhook configuration
  2. Check Twilio webhook logs in Console > Monitor > Logs > Webhooks
  3. Ensure webhook URLs use HTTPS (not HTTP)
  4. Check firewall settings aren't blocking requests

Issue: "Invalid signature" errors

Symptoms: Webhook returns 403 Forbidden, "Invalid signature" in logs

Solutions:

  1. Verify TWILIO\_AUTH\_TOKEN in environment variables is correct
  2. Check webhook URL exactly matches what's configured in Twilio (including trailing slashes)
  3. Ensure request body isn't being modified by middleware
  4. For local development, ensure ngrok free plan limitations aren't affecting headers

Issue: Messages not sending

Symptoms: API returns error, messages don't appear in WhatsApp

Solutions:

  1. Verify Twilio credentials (ACCOUNT\_SID, AUTH\_TOKEN) are correct
  2. Check recipient number is allowlisted in WhatsApp Sandbox
  3. Verify phone number format includes country code (E.164: +1234567890)
  4. Check Twilio account balance/credits
  5. Review Twilio error codes in response for specific issues

Issue: Database not storing messages

Symptoms: Messages send successfully but don't appear in Supabase

Solutions:

  1. Check Supabase credentials in .env.local
  2. Verify Row Level Security (RLS) policies allow inserts
  3. Check database table schema matches insert query
  4. Review Supabase logs in Dashboard > Logs

Issue: Authentication failing

Symptoms: "Unauthorized" errors, can't send messages

Solutions:

  1. Verify user is logged in and session is valid
  2. Check createClient() is properly configured in API routes
  3. Ensure cookies are being set correctly (check browser DevTools)
  4. Verify NEXT\_PUBLIC\_SUPABASE\_ANON\_KEY is correct

For more troubleshooting help, visit our troubleshooting guide or contact support.

Conclusion

You've successfully built a production-ready WhatsApp messaging application integrating Twilio's WhatsApp API, Next.js serverless API routes, and Supabase for authentication and data persistence. Your application can now send and receive WhatsApp messages, authenticate users securely, and store conversation history in a PostgreSQL database.

Next Steps

Enhance your application:

  • Message templates: Implement Twilio WhatsApp templates for business-initiated messages
  • Rich media: Add support for images, videos, and documents
  • Chatbot integration: Connect AI chatbots or NLP services for automated responses
  • Real-time UI: Implement

Supabase real-time subscriptions for live message updates

  • Analytics: Add message tracking and analytics dashboards

Production migration:

  • Apply for WhatsApp Business Account (WABA)
  • Purchase

Twilio phone number with WhatsApp capability

  • Set up monitoring and alerting
  • Implement

advanced security measures

  • Twilio WhatsApp API Documentation
  • Next.js API Routes Guide
  • Supabase Authentication Docs
  • WhatsApp Business API Best Practices
  • Node.js SMS Integration Tutorial

Questions or issues? Join our developer community or contact support for assistance with your WhatsApp integration project.

Use the Vonage Messages API with the Node.js SDK and Express. Set up webhooks to receive incoming messages and send replies using the WhatsAppText object. The Vonage Node SDK simplifies interactions with the API and includes modules for messages and JWT verification.

The Vonage Messages API is a unified API for sending and receiving messages across multiple channels including WhatsApp, SMS, and MMS. It provides a single interface for integrating messaging functionality into your applications.

Vonage uses webhooks to deliver real-time updates about incoming messages and message status to your application. This allows your server to respond to events without constantly polling the API, improving efficiency.

Remove the apiHost option from the Vonage client initialization when transitioning from the Sandbox environment to a production setup with a purchased Vonage number and a WhatsApp Business Account.

Node.js version 18 LTS is generally compatible with the Vonage Messages API and SDK. However, testing is recommended, and using version 20 or higher is preferred for access to the latest features and better performance.

Use the @vonage/jwt library's verifySignature function with your Vonage API Signature Secret. This ensures incoming webhooks are genuinely from Vonage, enhancing security. Implement this as middleware in your Express routes.

ngrok creates a secure tunnel to expose your local development server to the internet, allowing Vonage to send webhooks to your application during development.

In the Vonage Dashboard, navigate to Developer Tools > Messages API Sandbox. Scan the QR code with your WhatsApp account or send the specified message to allowlist your number for testing.

The VONAGE_API_SIGNATURE_SECRET is crucial for verifying the authenticity of incoming webhooks. It confirms requests originate from Vonage, preventing unauthorized access to your application.

Create a POST route in your Express app (e.g., /webhooks/inbound) to handle incoming messages. Use the express.json() middleware to parse the request body containing the message data. The article provides an example of an Express route setup.

WhatsApp Message Templates are pre-approved message formats required for sending unsolicited notifications to users more than 24 hours after their last interaction. They are different from session messages and require separate setup.

The Vonage Application ID uniquely identifies your application within the Vonage platform. It's required when initializing the Vonage client in your code to link your code to your Vonage account and configuration.

In the Vonage Dashboard, under your application's settings, configure the Inbound and Status URLs for the Messages capability. These URLs should point to your application's endpoints for receiving message and status updates.

The dotenv module loads environment variables from a .env file into process.env, allowing you to store and manage sensitive configuration data like API keys and secrets securely.

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 β†’