Back to Blog
Integration Guides

How to Send SMS with Twilio and Next.js: Step-by-Step Tutorial

Add Twilio SMS to your Next.js application using API routes as secure backend endpoints so credentials never reach the browser.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
7 min read
Twilio
Integration
SDK
Mobile
How to Send SMS with Twilio and Next.js: Step-by-Step Tutorial

Twilio SMS and Next.js integrate through Next.js API routes in the App Router or Pages Router, which run exclusively on the server and can safely import the Twilio Node.js library with credentials from environment variables that Next.js never bundles into the client-side JavaScript. This integration is used by Next.js developers building full-stack applications that need SMS for OTP verification, contact form notifications, booking confirmations, or alert broadcasting, and who want to use Next.js's built-in API route system to eliminate a separate backend while maintaining clean credential separation enforced by Next.js's module boundary between server and client code. The Next.js API route imports the Twilio client, reads credentials from process.env variables available server-side only, and returns the message SID to the Next.js React component via a fetch call.

What You Need Before You Start

Install the Twilio Node.js library in your Next.js project by running npm install twilio. Create a .env.local file at the Next.js project root with TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM_NUMBER. In Next.js, environment variables without the NEXT_PUBLIC_ prefix are available only in server-side code including API routes, Server Components, and getServerSideProps, and are never included in the client bundle. Confirm that none of your Twilio credential variable names start with NEXT_PUBLIC_ as this would expose them to the browser. Provision a Twilio SMS-capable phone number, note your credentials from the Twilio Console, and complete A2P 10DLC Brand and Campaign registration for US recipients.

Step-by-Step Integration Guide

For the App Router, create the file app/api/send-sms/route.ts. Import twilio from 'twilio' and NextResponse from 'next/server'. Export an async POST function that calls req.json() to parse the body, constructs the Twilio client with process.env.TWILIO_ACCOUNT_SID and process.env.TWILIO_AUTH_TOKEN, calls await client.messages.create({ to, from: process.env.TWILIO_FROM_NUMBER, body }) wrapped in try/catch, and returns NextResponse.json({ sid: message.sid }) on success or NextResponse.json({ error: err.message }, { status: 500 }) on failure. For the Pages Router, create pages/api/send-sms.ts, export a default async handler function accepting req and res, check req.method equals POST returning 405 for other methods, extract to and body from req.body, call the Twilio API in try/catch, and call res.status(200).json({ sid }) or res.status(500).json({ error }). In your React component, define a handleSend async function that calls fetch('/api/send-sms', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ to: phone, body: message }) }), awaits the response JSON, and updates React state with the returned SID or error.

Common Issues and How to Fix Them

The Next.js API route throws 'Cannot read properties of undefined' when constructing the Twilio client because process.env.TWILIO_ACCOUNT_SID is undefined at runtime in production, caused by the environment variables being set in .env.local which is not loaded in production deployments on Vercel or other platforms. Set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM_NUMBER as environment variables in the Vercel project dashboard under Settings, then Environment Variables, and redeploy so the Next.js server process has access to them. The API route accidentally exposes TWILIO_AUTH_TOKEN to the client when a developer prefixes it with NEXT_PUBLIC_ to try to make it available in a component, which causes Next.js to embed it in the JavaScript bundle. Always keep Twilio credentials in non-NEXT_PUBLIC_ variables and access them only in API routes, Server Components, or getServerSideProps. The fetch call to the API route fails in development with a CORS error when the React component runs in the browser and makes the call to a different port. This should not happen since Next.js API routes are served from the same origin as the frontend during development; verify the fetch URL uses a relative path starting with /api/ and not an absolute URL pointing to a different host.

How to Get More from This Integration

Build a Next.js Server Action for SMS sending by creating a server action in a file marked with 'use server', importing twilio and reading credentials from process.env, calling client.messages.create, and invoking the action directly from a React component's form action prop or onClick handler without a manually written fetch call, letting Next.js handle the serialization and client-server communication automatically. Add Twilio Verify OTP to Next.js authentication by creating /api/verify-send and /api/verify-check API routes, calling verify.v2.services(sid).verifications.create and verificationChecks.create respectively, and storing the verified phone in a next-auth session or a server-side cookie using the cookies() helper from next/headers, gating protected pages using Next.js middleware that reads the cookie and redirects unverified users. Implement webhook handling for inbound SMS and status callbacks by creating API routes at /api/webhook/sms and /api/webhook/status, reading the Twilio request signature from headers, validating with twilio.validateRequest, and returning a TwiML XML string using the twilio TwiML builder for the inbound route and HTTP 200 for the status route.

Conclusion

Next.js and Twilio together provide a credential-safe, full-stack SMS integration using built-in API routes that run on the server and never expose secrets to the browser. Reach out to Telphi Consulting to implement the Twilio SMS API routes and React integration for your Next.js application.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.