Bulk SMS

Send and Receive SMS with Delivery Receipts using Next.js and Vonage

A guide on building a Next.js app to send SMS via Vonage, handle delivery receipts, and receive inbound messages using webhooks, Server Actions, and Route Handlers.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 4, 2026 β€’ 16 min read

Developer Quick-Start: A guide on building a Next.js app to send SMS via Vonage, handle delivery receipts, and receive inbound messages using webhooks, Server Actions, and Route Handlers. 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 Next.js application capable of sending SMS messages via the Vonage SMS API and handling incoming messages and delivery receipts (DLRs) through webhooks. We will cover project setup, core implementation, deployment, and essential production considerations like error handling and security.

By the end of this guide, you will have a functional Next.js application deployed on Vercel that can:

  1. Send SMS messages programmatically using a simple web form.
  2. Receive delivery status updates (delivery receipts) for sent messages.
  3. Receive incoming SMS messages sent to your Vonage virtual number.

This implementation leverages the power of Next.js App Router features like Server Actions for form handling and Route Handlers for creating webhook endpoints, alongside the robust Vonage SMS API.

Project Overview and Goals

Problem: Businesses often need to integrate SMS functionality into their applications for notifications, alerts, marketing campaigns, or two-way communication. Implementing this requires sending messages reliably and understanding their delivery status, as well as processing inbound messages from users.

Solution: We will build a Next.js application that uses the Vonage SMS API to send messages. We'll implement webhook endpoints using Next.js Route Handlers to receive delivery receipts (DLRs) and inbound SMS messages from the Vonage platform, providing a complete SMS communication loop.

Technologies:

  • Next.js: A React framework for building full-stack web applications. We'll use the App Router, Server Actions, and Route Handlers.
  • Vonage SMS API: A RESTful API for sending and receiving SMS messages globally.
  • Vonage Node.js SDK: Simplifies interaction with the Vonage APIs within a Node.js environment.
  • Vercel: A platform for deploying frontend applications and serverless functions, ideal for hosting our Next.js app and its API routes (webhooks).
  • (Optional) Zod: A schema declaration and validation library for validating form input.

System Architecture:

graph LR
    A[User Browser] -- 1. Submits Form --> B(Next.js App / Vercel);
    B -- 2. Calls Send API --> C(Vonage SMS API);
    C -- 3. Sends SMS --> D[User Phone];
    C -- 4. Posts DLR --> E[Next.js Webhook /webhook/status / Vercel];
    D -- 5. Sends Reply --> C;
    C -- 6. Posts Inbound SMS --> F[Next.js Webhook /webhook/inbound / Vercel];
    E -- Logs DLR --> G[Vercel Logs / Database];
    F -- Logs Inbound SMS --> G;

    style B fill:#f9f,stroke:#333,stroke-width:2px
    style E fill:#ccf,stroke:#333,stroke-width:2px
    style F fill:#ccf,stroke:#333,stroke-width:2px
    style C fill:#ffa,stroke:#333,stroke-width:2px

Diagram Explanation:

  1. The user interacts with the Next.js frontend hosted on Vercel.
  2. Submitting the send SMS form triggers a Server Action that uses the Vonage SDK to call the Vonage API.
  3. Vonage delivers the SMS to the recipient's phone.
  4. Vonage sends a Delivery Receipt (DLR) back to a specific webhook endpoint in our Next.js app.
  5. The user can reply to the SMS.
  6. Vonage forwards the inbound SMS to another webhook endpoint in our Next.js app.
  7. Both webhooks log the received data (e.g., to Vercel logs or a database).

Prerequisites:

  • Vonage API Account: Sign up at Vonage.com. You'll need your API Key and API Secret from the API Dashboard.
  • Vonage Virtual Number: Rent a virtual phone number with SMS capabilities from the Numbers section of the dashboard.
  • Node.js: Version 18.17 or later installed. (Download Node.js)
  • npm or yarn: Package manager for Node.js.
  • Git: For version control and deployment via GitHub. (Install Git)
  • GitHub Account: Required for deploying via Vercel's Git integration. (Sign up for GitHub)
  • Vercel Account: For deployment. Sign up with your GitHub account. (Sign up for Vercel)

1. Setting up the Project

Let's initialize a new Next.js project and install the necessary dependencies.

  1. Create Next.js App: Open your terminal and run the following command:
   npx create-next-app@latest
  1. Configure Project: You'll be prompted for project settings. Use these selections for this guide:
   What is your project named? vonage-nextjs-sms
   Would you like to use TypeScript? No
   Would you like to use ESLint? Yes
   Would you like to use Tailwind CSS? Yes
   Would you like to use `src/` directory? No
   Would you like to use App Router? (recommended) Yes
   Would you like to customize the default import alias (@/*)? No
  1. Navigate to Project Directory:
   cd vonage-nextjs-sms
  1. Install Dependencies: Install the Vonage Node.js SDK and optionally Zod for validation.
   npm install @vonage/server-sdk
   npm install zod
  1. Set Up Environment Variables: Create a file named .env.local in the root of your project. This file stores sensitive credentials and should not be committed to Git.
  • Find your API Key and API Secret on the main page of your Vonage API Dashboard.
  • Find your Vonage Virtual Number under Numbers > Your numbers. Make sure it has SMS capability. Enter the number in E.164 format (country code + number, no leading +, spaces, or dashes, e.g., 14155550100).

Add the following lines to .env.local, replacing the placeholder values:

   # .env.local

   VONAGE_API_KEY=YOUR_VONAGE_API_KEY
   VONAGE_API_SECRET=YOUR_VONAGE_API_SECRET
   VONAGE_VIRTUAL_NUMBER=YOUR_VONAGE_VIRTUAL_NUMBER
  • VONAGE\_API\_KEY: Your Vonage account API key.
  • VONAGE\_API\_SECRET: Your Vonage account API secret.
  • VONAGE\_VIRTUAL\_NUMBER: The Vonage number you rented (in E.164 format), used as the 'from' number for sending SMS.
  1. Update .gitignore: Ensure .env.local is listed in your .gitignore file (create-next-app usually adds it by default) to prevent accidentally committing secrets.
   # .gitignore (ensure this line exists)
   .env*.local

Project Structure Explanation:

  • /app: Contains the core application code using the Next.js App Router.
  • /app/page.js: The main page component for our UI.
  • /app/layout.js: The root layout for the application.
  • /app/lib: A conventional place for utility functions and server-side logic (like our Vonage interaction).
  • /app/webhook: Will contain our API Route Handlers for receiving data from Vonage.
  • /public: Static assets (images, etc.).
  • .env.local: Environment variables for local development.
  • package.json: Project dependencies and scripts.
  • next.config.js: Next.js configuration.

This structure separates UI components, server-side logic, and API routes cleanly, aligning with Next.js conventions.

2. Implementing Core Functionality (Sending SMS)

We'll create a form that uses a Next.js Server Action to send an SMS message via the Vonage API.

  1. Create the Server Action (app/lib/send-sms.js): This file contains the server-side logic to interact with the Vonage SDK. Create a lib directory inside app if it doesn't exist.
   'use server';

   import { Vonage } from '@vonage/server-sdk';
   import { z } from 'zod';
   import { revalidatePath } from 'next/cache';

   const vonage = new Vonage({
     apiKey: process.env.VONAGE_API_KEY,
     apiSecret: process.env.VONAGE_API_SECRET,
   });

   const fromNumber = process.env.VONAGE_VIRTUAL_NUMBER;

   const smsSchema = z.object({


     number: z
       .string()
       .regex(/^[1-9]\d{6,14}$/, { message: 'Invalid phone number format (must be E.164).' }),
     text: z
       .string()
       .min(1, { message: 'Message cannot be empty.' })
       .max(1600, { message: 'Message too long.' }),
   });

   export async function sendSMS(prevState, formData) {
     let isError = false;
     try {

       const validatedData = smsSchema.parse({
         number: formData.get('number'),
         text: formData.get('text'),
       });

       console.log(`Sending SMS from ${fromNumber} to ${validatedData.number}`);


       const vonageResponse = await vonage.sms.send({
         to: validatedData.number,
         from: fromNumber,
         text: validatedData.text,
       });


       revalidatePath('/');


       if (vonageResponse.messages[0].status === '0') {
         console.log('Message sent successfully:', vonageResponse.messages[0]);
         return {
           response: `Message sent successfully to ${validatedData.number}. Message ID: ${vonageResponse.messages[0]['message-id']}`,
           isError: false,
         };
       } else {
         console.error('Error sending SMS:', vonageResponse.messages[0]['error-text']);
         isError = true;
         return {
           response: `Error sending SMS: ${vonageResponse.messages[0]['error-text']}`,
           isError: true,
         };
       }
     } catch (error) {
       isError = true;

       if (error instanceof z.ZodError) {
         console.error('Validation Error:', error.flatten().fieldErrors);

          const errorMessages = Object.entries(error.flatten().fieldErrors)
           .map(([field, messages]) => `${field}: ${messages.join(', ')}`)
           .join('; ');
         return { response: `Validation failed: ${errorMessages}`, isError: true };
       }

       console.error('Failed to send SMS:', error);
       return {
         response: `Failed to send SMS. Error: ${error.message}`,
         isError: true,
       };
     }
   }
  • 'use server': Directive required for Server Actions.
  • Vonage Initialization: Creates a Vonage client instance using credentials from .env.local.
  • Zod Schema: Defines rules for the recipient number (E.164 format) and message text.
  • sendSMS Function:
  • Takes prevState (from useFormState) and formData.
  • Uses smsSchema.parse to validate input. Throws an error if validation fails.
  • Calls vonage.sms.send with the validated data and the from number.
  • revalidatePath('/'): Tells Next.js to clear the cache for the root path, useful if the page displays sent message status (though not implemented here).
  • Checks the status field in the Vonage response ('0' means success).
  • Returns an object with a response message and an isError flag indicating success or failure.
  • Includes try...catch to handle validation errors (ZodError) and API/network errors gracefully.
  1. Create the Form Component (app/send-form.jsx): This client component renders the form and uses React hooks to manage state and submission.
   'use client';

   import { useFormState, useFormStatus } from 'react-dom';
   import { sendSMS } from '@/app/lib/send-sms';

   const initialState = {
     response: null,
     isError: false,
   };

   function SubmitButton() {
     const { pending } = useFormStatus();

     return (
       <button
         type=""submit""
         aria-disabled={pending}
         className=""bg-blue-600 text-white font-semibold py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed flex justify-center items-center""
         disabled={pending}
       >
         {pending ? (
           <>
             <svg className=""animate-spin -ml-1 mr-3 h-5 w-5 text-white"" xmlns=""http://www.w3.org/2000/svg"" fill=""none"" viewBox=""0 0 24 24"">
               <circle className=""opacity-25"" cx=""12"" cy=""12"" r=""10"" stroke=""currentColor"" strokeWidth=""4""></circle>
               <path className=""opacity-75"" fill=""currentColor"" d=""M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z""></path>
             </svg>
             Sending...
           </>
         ) : (
           'Send SMS'
         )}
       </button>
     );
   }

   export function SendForm() {

     const [state, formAction] = useFormState(sendSMS, initialState);

     return (
       <form action={formAction} className=""flex flex-col gap-y-4"">
         <div>
           <label htmlFor=""number"" className=""block text-sm font-medium text-gray-700 mb-1"">
             Phone Number (E.164 format, e.g., 14155550100):
           </label>
           <input
             name=""number""
             id=""number""
             type=""tel"" // Use type=""tel"" for phone numbers
             placeholder=""Enter recipient number (e.g. 14155550100)""
             autoComplete=""tel""
             className=""border border-gray-300 rounded-md p-2 w-full focus:ring-blue-500 focus:border-blue-500""
             required
           />
         </div>

         <div>
           <label htmlFor=""text"" className=""block text-sm font-medium text-gray-700 mb-1"">
             Message:
           </label>
           <textarea
             name=""text""
             id=""text""
             rows={4}
             placeholder=""Enter your message here...""
             className=""border border-gray-300 rounded-md p-2 w-full focus:ring-blue-500 focus:border-blue-500""
             required
           ></textarea>
         </div>

         <SubmitButton />

         {/* Display the response message from the Server Action */}
         {state?.response && (
            <p aria-live=""polite"" className={`mt-2 text-sm ${state.isError ? 'text-red-600' : 'text-green-600'}`}>
              {state.response}
            </p>
          )}
       </form>
     );
   }
  • 'use client': Required for components using React hooks like useFormState and useFormStatus.
  • useFormState: Manages form state. It takes the Server Action (sendSMS) and an initial state. It returns the current state (state) and a dispatch function (formAction) to be passed to the <form>'s action prop.
  • useFormStatus: Used in the SubmitButton to get the pending status of the form submission, enabling UI feedback (disabling button, showing spinner). It must be used in a component rendered inside the <form>.
  • Form Structure: Standard HTML form elements. name attributes must match the keys expected by the Server Action (formData.get('name')). required provides basic client-side validation. E.164 format explicitly mentioned.
  • Response Display: Uses the isError flag from the state to conditionally apply CSS classes for success/error styling.
  1. Integrate Form into Page (app/page.js): Import and render the SendForm component on the main page.
   import { SendForm } from './send-form';

   export default function Home() {
     return (
       <main className=""mx-auto max-w-2xl my-8 p-6 border border-gray-200 shadow-md rounded-lg"">
         <header className=""mb-6 pb-4 border-b border-gray-200"">
           {/* You can add a Vonage logo here if desired */}
           {/* <img src=""/vonage-logo.svg"" alt=""Vonage Logo"" className=""h-8 mb-2"" /> */}
           <h1 className=""text-2xl font-semibold text-gray-800"">
             Send SMS with Next.js & Vonage
           </h1>
         </header>

         <section>
           <SendForm />
         </section>
       </main>
     );
   }

(Note: Add a vonage-logo.svg to the /public directory if you want to display it).

  1. Run Development Server:
   npm run dev

Open your browser to http://localhost:3000. You should see the form. Try sending an SMS to your own phone number (use the E.164 format, e.g., 14155550100). Check the browser for success/error messages and your terminal console for logs from the Server Action.

3. Building API Layer (Receiving Webhooks)

Vonage uses webhooks to send data to your application. We need endpoints to receive Delivery Receipts (DLRs) and inbound SMS messages. We'll use Next.js Route Handlers for this.

  1. Create Webhook Directory Structure:
   mkdir -p app/webhook/status
   mkdir -p app/webhook/inbound
  1. Create Delivery Receipt Handler (app/webhook/status/route.js): This endpoint will receive status updates for messages you've sent.
   import { NextResponse } from 'next/server';

   export async function POST(request) {
     try {
       const data = await request.json();
       console.log('--- Delivery Receipt Received ---');
       console.log(JSON.stringify(data, null, 2));
       console.log(`Message ID: ${data.messageId}, Status: ${data.status}`);




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

     } catch (error) {
       console.error('Error processing delivery receipt:', error);

       return new NextResponse('Error processing webhook', { status: 500 });
     }
   }

   export async function GET(request) {
       console.log('Received GET request on /webhook/status');
       return new NextResponse('Status webhook endpoint is active.', { status: 200 });
   }
  1. Create Inbound SMS Handler (app/webhook/inbound/route.js): This endpoint receives messages sent to your Vonage number.
   import { NextResponse } from 'next/server';

   export async function POST(request) {
     try {
       const data = await request.json();
       console.log('--- Inbound SMS Received ---');
       console.log(JSON.stringify(data, null, 2));
       console.log(`From: ${data.msisdn}, To: ${data.to}, Text: ${data.text}`);




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

     } catch (error) {
       console.error('Error processing inbound SMS:', error);
       return new NextResponse('Error processing webhook', { status: 500 });
     }
   }

   export async function GET(request) {
       console.log('Received GET request on /webhook/inbound');
       return new NextResponse('Inbound SMS webhook endpoint is active.', { status: 200 });
   }
  • Route Handlers: These files export functions named after HTTP methods (POST, GET). Next.js automatically routes requests to /webhook/status and /webhook/inbound to these handlers.
  • request.json(): Parses the incoming JSON payload from Vonage.
  • Logging: We log the received data. In a real application, you'd process this data (e.g., update a database, trigger other actions).
  • NextResponse('OK', { status: 200 }): Crucially, you must return a 200 OK (or 204 No Content) response quickly. If Vonage doesn't receive this, it will assume the webhook failed and retry sending the data, potentially leading to duplicate processing.
  • Error Handling: Basic try...catch logs errors. Returning a 500 might cause Vonage to retry, which could be desirable or not depending on the error type.
  • GET Handlers: Added for basic testing to confirm the endpoints are reachable.

These endpoints currently just log the data. Authentication/validation are discussed in Section 7 (Security).

4. Integrating with Vonage (Webhook Configuration)

Now that the endpoints exist, you need to tell Vonage where to send the data. This requires deploying the application first, as Vonage needs publicly accessible URLs. We'll cover deployment conceptually now, assuming you will deploy later.

  1. Obtain Deployment URL: After deploying to Vercel (or another hosting provider), you will get a public URL (e.g., https://your-app-name.vercel.app).
  2. Configure Vonage Dashboard:
  • Navigate to your Vonage API Dashboard Settings.
  • Scroll down to the ""SMS settings"" section.
  • Delivery receipts (DLRs) / Webhook URL for DLR: Enter your deployed application URL appended with the status webhook path: https://your-app-name.vercel.app/webhook/status
  • Inbound messages / Webhook URL for Inbound Message: Enter your deployed application URL appended with the inbound webhook path: https://your-app-name.vercel.app/webhook/inbound
  • Set the HTTP Method for both to POST.
  • Click Save changes.

Environment Variable Recap:

  • VONAGE\_API\_KEY: (Required for sending) Found in Vonage Dashboard. Used by the SDK.
  • VONAGE\_API\_SECRET: (Required for sending) Found in Vonage Dashboard. Used by the SDK.
  • VONAGE\_VIRTUAL\_NUMBER: (Required for sending) Found in Vonage Dashboard > Numbers. Used as the from number.

These variables need to be set both in .env.local for local development and in your Vercel project settings (or equivalent) for the deployed application.

5. Implementing Error Handling and Logging

We've added basic try...catch blocks and console.log statements. Let's refine this.

Error Handling Strategy:

  • Sending SMS (app/lib/send-sms.js):
  • Validation Errors: Zod handles input validation before calling the API. Errors are caught, logged, and returned to the UI via the response and isError state.
  • API Errors: The Vonage SDK might throw errors (network issues, invalid credentials). These are caught, logged, and a generic message returned. The Vonage response can also indicate errors (status !== '0'). These specific error-text messages from Vonage are logged and returned to the UI.
  • Receiving Webhooks (app/webhook/.../route.js):
  • Parsing Errors: If request.json() fails (invalid JSON), the catch block handles it.
  • Processing Errors: Any errors during your custom logic (e.g., database updates) should be caught.
  • Crucial: Always aim to return a 200 OK to Vonage unless the request itself is malformed in a way that prevents any processing. Log internal errors thoroughly for debugging but acknowledge receipt to Vonage.

Logging:

  • Development: console.log and console.error are sufficient. Output appears in the terminal running npm run dev.
  • Production (Vercel): console.log/error statements in Server Actions and Route Handlers are automatically captured by Vercel Logs. You can view these in your Vercel project dashboard under the ""Logs"" tab.
  • Structured Logging: For better analysis, consider using a library like pino to output logs in JSON format, including timestamps, request IDs, severity levels, etc. This makes filtering and querying logs much easier, especially with log management platforms.

Retry Mechanisms:

  • Sending: If the initial vonage.sms.send call fails due to a temporary network issue or a Vonage server error (e.g., 5xx status code from the API), you could implement a retry mechanism with exponential backoff (e.g., using a library like async-retry). However, be cautious about retrying errors related to invalid input or credentials. For this guide, we rely on surfacing the error to the user.
  • Receiving Webhooks: Vonage automatically retries sending webhooks if it doesn't receive a 2xx response within a certain timeout (usually a few seconds). It will typically retry several times over a period (e.g., 24 hours) with increasing intervals. Your webhook endpoint must be idempotent – processing the same webhook data multiple times should not cause unintended side effects (e.g., don't increment a counter twice for the same delivery receipt).

6. Creating a Database Schema (Optional Extension)

Storing message details, statuses, and inbound messages is often necessary. This section outlines a conceptual approach using Prisma (a popular ORM). Integrating a database is beyond the scope of the core Vonage tutorial but is a common next step.

  1. Install Prisma:
   npm install prisma --save-dev
   npm install @prisma/client
   npx prisma init --datasource-provider postgresql
  1. Define Schema (prisma/schema.prisma):

Prisma

   // prisma/schema.prisma
   datasource db {
     provider = ""postgresql"" // Or ""mysql"", ""sqlite"", etc.
     url      = env(""DATABASE_URL"")
   }

   generator client {
     provider = ""prisma-client-js""
   }

   model MessageLog {
     id            String   @id @default(cuid())
     createdAt     DateTime @default(now())
     updatedAt     DateTime @updatedAt

     vonageMessageId String?  @unique // From send response & DLR
     direction     Direction // INBOUND or OUTBOUND
     fromNumber    String
     toNumber      String
     text          String?
     status        String?  // e.g., ""submitted"", ""delivered"", ""failed""
     errorCode     String?  // From DLR
     price         String?  // From DLR
     networkCode   String?  // From DLR
     rawWebhookData Json?    // Store the full webhook payload
   }

   enum Direction {
     INBOUND
     OUTBOUND
   }
  1. Set DATABASE_URL: Add your database connection string to .env.local (and Vercel environment variables).
  2. Apply Schema:
   npx prisma db push
  1. Integrate with Code:
  • Instantiate Prisma Client (e.g., in lib/prisma.js).
  • In sendSMS: After successful sending, create a MessageLog record with direction: 'OUTBOUND', vonageMessageId, numbers, text, and status: 'submitted'.
  • In app/webhook/status/route.js: Find the MessageLog by vonageMessageId and update its status, errorCode, price, etc., based on the DLR data.
  • In app/webhook/inbound/route.js: Create a MessageLog record with direction: 'INBOUND', numbers, text, and store the raw data.

This provides persistent storage for analysis and tracking. Remember to handle potential database errors within your try...catch blocks.

7. Adding Security Features

Protecting your application and user data is critical.

  • Input Validation & Sanitization:
  • We used Zod in sendSMS for validating the phone number format and message length. This prevents malformed requests from even reaching the Vonage API.
  • Next.js and React generally help prevent Cross-Site Scripting (XSS) by default when rendering data, but be cautious if using dangerouslySetInnerHTML.
  • Sanitize any data before storing it in a database if it might be displayed later, although Prisma helps prevent SQL injection.
  • Webhook Security (Signature Verification):
  • Problem: Anyone could potentially send fake data to your webhook endpoints.
  • Solution: Vonage can sign its webhook requests. You can verify this signature using your Vonage Signature Secret.
  • Implementation:
  1. Retrieve your Signature Secret from the Vonage API Dashboard Settings (it's different from your API Secret). Store it securely as an environment variable (e.g., VONAGE\_SIGNATURE\_SECRET).
  2. Install the necessary Vonage SDK components or JWT libraries if not already present.
  3. In your webhook handlers (POST functions), before processing the main logic, you need to:
  • Get the raw request body. Accessing the raw body alongside request.json() can be tricky in Next.js depending on the runtime (Node.js vs. Edge) and might require specific handling or middleware. await request.text() is one way, but ensure it doesn't conflict with later parsing if not handled carefully.
  • Get the Authorization header (which contains the JWT, typically Bearer <token>).
  • Use the appropriate Vonage SDK method (like verifySignature, check the SDK documentation for the exact method signature and required parameters) or standard JWT verification logic with the JWT, the raw body (or potentially a parsed version depending on the SDK function), and your Signature Secret.
  • If verification fails, return a 401 Unauthorized status immediately and do not process the request. Only parse and process the body after successful verification.
    const signatureSecret = process.env.VONAGE_SIGNATURE_SECRET;
    const authHeader = request.headers.get('Authorization');
    const jwt = authHeader?.split(' ')[1];

    let data;
    try {

      const rawBody = await request.text();





      const isValid = true;

      if (!isValid) {
         console.warn('Webhook signature verification failed!');
         return new NextResponse('Invalid signature', { status: 401 });
      }




      data = JSON.parse(rawBody);

    } catch (error) {
       console.error('Error during webhook signature verification or body parsing:', error);

       return new NextResponse('Webhook processing error', { status: 400 });
    }

    console.log('--- Webhook Received (Signature Verified) ---');
    console.log(JSON.stringify(data, null, 2));

    return new NextResponse('OK', { status: 200 });
  • Refer to the Vonage documentation on Signed Webhooks for detailed implementation specifics for your SDK version. This is highly recommended for production.
  • Rate Limiting:
  • Prevent abuse of your SMS sending form or webhooks.
  • Implement rate limiting based on IP address or user session for the sending form. Libraries like rate-limiter-flexible or Vercel Edge Middleware can help.
  • While less common for incoming webhooks (as they originate from Vonage), ensure your processing logic can handle bursts of traffic.
  • Environment Variable Security:
  • Never commit .env.local or files containing secrets to Git. Use .gitignore.
  • Store production secrets securely in your hosting provider's environment variable settings (e.g., Vercel Environment Variables).
  • Dependency Management: Keep dependencies up-to-date (npm update or yarn upgrade) to patch security vulnerabilities. Use tools like npm audit or yarn audit.

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