Frequently Asked Questions
Standard SMS messages have a limit of 160 characters for GSM-7 encoding and 70 for UCS-2. Plivo automatically splits longer messages into segments, but be mindful of length as this affects cost. Plivo's smart encoding optimizes for these limitations.
Integrate the Plivo SMS API into a Next.js app by creating a serverless API route (/api/send-sms) that handles sending messages via the Plivo Node.js SDK. This route accepts POST requests with the recipient's number and message text, then uses your Plivo credentials to send the SMS through the Plivo API.
The Plivo Node.js SDK simplifies interaction with the Plivo API in your Next.js application. It provides convenient methods for sending SMS messages, making API calls, and handling responses, reducing the amount of boilerplate code you need to write.
Next.js API routes keep your Plivo credentials and sending logic secure on the server-side, away from the client-side browser. This prevents exposing sensitive information and protects your API keys.
Using a Plivo phone number as your Sender ID is mandatory when sending SMS to the US and Canada. For other countries, check Plivo's documentation, as some allow pre-registered alphanumeric Sender IDs, but these may not be able to receive replies.
While the US and Canada require Plivo numbers, some other countries permit alphanumeric Sender IDs (like "MyCompany"). However, these usually require prior registration with Plivo and might not be able to receive replies. Check Plivo's documentation for country-specific guidelines.
Implement a try...catch block around your Plivo API call in the Next.js API route to handle potential errors. Log the error details server-side, and return an appropriate HTTP status code and a user-friendly error message to the client, potentially including Plivo's specific error message.
Plivo requires destination phone numbers to be in E.164 format, which includes a plus sign (+) followed by the country code, area code, and local number (e.g., +14155551212). Ensure proper formatting to avoid errors.
Store your Plivo Auth ID, Auth Token, and Sender ID in a .env.local file in your project's root directory. This file is automatically ignored by Git. Access these values in your code via process.env.VARIABLE_NAME.
Use tools like curl, Postman, or Insomnia to send test POST requests to your /api/send-sms endpoint. Check for the expected 200 OK response and verify SMS delivery on the recipient's phone. Also, examine Plivo's logs for message status details.
Store credentials securely in environment variables within a .env.local file (included in .gitignore), perform server-side API interactions, implement input validation, and add rate limiting to protect your endpoint from abuse.
Double-check that your Plivo Auth ID and Auth Token in .env.local match those in the Plivo Console. Restart your Next.js server after any changes to .env.local. Ensure .env.local is at the project root and process.env can access its values in your API route.
Push your project to a Git repository, import it into Vercel, configure the project, and add your Plivo credentials as environment variables in Vercel's project settings. Vercel's Git integration then enables automatic CI/CD for seamless deployments.
Utilize Vercel Analytics for function invocation details if deployed there. Integrate error tracking services and set up centralized logging. Plivo console logs offer insights into message status and API request details for debugging.
This guide shows you how to integrate the Plivo SMS API into a Next.js application for sending text messages programmatically. You'll build a Next.js application with a serverless backend API route that securely handles SMS delivery through Plivo's communication platform.
By the end of this tutorial, you'll have a functional Next.js SMS sending application that accepts phone numbers and message text via an API endpoint and dispatches messages through Plivo. This foundation enables you to add SMS notifications, alerts, two-factor authentication, and messaging features to your web applications.
Project Overview and Goals
What You're Building: A Next.js application featuring a serverless API route (
/api/send-sms). This route accepts POST requests containing a destination phone number and a message body, then uses the Plivo Node.js SDK to send the SMS message.Problem Solved: Send SMS messages programmatically from a modern web application framework like Next.js, leveraging a reliable communication platform like Plivo. This guide provides a secure and straightforward method for server-side SMS dispatch.
When to Use This Pattern: Choose this serverless API route approach when you need transactional SMS (password resets, order confirmations, alerts) sent in response to user actions. For high-volume broadcast messaging or complex workflows, consider dedicated message queue systems (RabbitMQ, AWS SQS) or background job processors (Bull, Celery). For simple notification needs under 1,000 messages per hour, this direct API approach works well.
Cost Implications: Plivo charges per message segment. Standard SMS in the US costs approximately $0.0065–$0.0085 per message segment. Messages exceeding 160 GSM characters or 70 Unicode characters split into multiple segments, multiplying costs. Budget accordingly – 10,000 standard messages monthly costs roughly $65–$85. Trial accounts include $10 credit but restrict sending to verified numbers only.
Technologies Used:
System Architecture:
Prerequisites:
Compatibility: This guide uses Next.js 14+ with Pages Router. The App Router (Next.js 13+) requires minor adjustments to route structure (
app/api/send-sms/route.jsinstead ofpages/api/send-sms.js) but uses identical Plivo SDK code.1. Setting Up Your Next.js Project with Plivo
Create a new Next.js project and install the necessary dependencies.
Create a Next.js App: Open your terminal and run the following command. Replace
plivo-nextjs-smswith your desired project name. Follow the prompts – selecting defaults works fine for this guide (using Pages Router for simplicity here, but concepts apply to App Router).Navigate to Project Directory:
Install Plivo Node.js SDK: Add the Plivo helper library to your project dependencies.
or using yarn:
Set Up Environment Variables: Securely store your Plivo credentials. Create a file named
.env.localin the root of your project. Never commit this file to version control..env.localis Next.js's standard way to load these variables during development and is included in.gitignoreby default.Verify
.gitignore: Ensure that.env*.localis listed in your project's.gitignorefile (create-next-appusually adds this automatically). This prevents accidentally committing your secrets.Your basic project structure is now ready. You have Next.js set up, the Plivo SDK installed, and a secure way to manage API credentials.
Common Setup Issues:
npm cache clean --forceand retry.lsof -ti:3000 | xargs killon macOS/Linux) or specify a different port withnpm run dev -- -p 3001..jsfiles to.tsor.tsxand add type annotations as needed.2. Creating the SMS API Route
The core logic for sending SMS resides in a Next.js API route. This keeps your Plivo credentials and logic secure on the server-side.
Create the API Route File: Inside the
pagesdirectory, create a folder namedapi. Insideapi, create a file namedsend-sms.js.Implement the API Logic: Open
pages/api/send-sms.jsand add the following code:Code Explanation:
plivoSDK.to(destination phone number) andtext(message content) from the incoming JSON request body. Basic validation checks if they exist. Includes a note about further validation (like E.164).try...catchblock to handle the SMS sending process.client.messages.create()sends the actual request to Plivo.src: Your Plivo number or registered Sender ID (from env vars).dst: The recipient's number (from request body). Must be in E.164 format (e.g._ +12025551234).text: The message content (from request body).This API route now encapsulates the core SMS sending functionality securely on the server.
3. Building a Complete API Layer
The
pages/api/send-sms.jsfile is your API layer for this simple application. Let's refine the documentation and testing aspects.API Endpoint Documentation:
/api/send-smsPOSTapplication/jsonto: Required. Destination phone number in E.164 format.text: Required. The SMS message text.plivoResponseobject reflects the actual fields returned by the Plivo API_ which typically use snake_case likemessage_uuidandapi_id.)Testing Your SMS API with curl:
Replace placeholders with your actual data and run this in your terminal while your Next.js development server runs (
npm run dev).Replace
+1RECIPIENT_PHONE_NUMBERwith a valid phone number (if using a trial Plivo account_ it must be a number verified in your Plivo console under Phone Numbers > Sandbox Numbers).You should receive a JSON response indicating success or failure, and see logs in your Next.js development server console.
Frontend Integration Patterns:
Pattern 1: Direct Fetch from Client Component (Next.js Pages Router)
Pattern 2: Server-Side Trigger (Next.js Server Component or getServerSideProps)
Pattern 3: Background Job Queue (Production-Grade)
For high-volume or time-sensitive SMS, integrate a queue system like Bull or AWS SQS. Your API route adds jobs to the queue; worker processes consume and send messages asynchronously.
API Versioning Strategy:
This basic guide doesn't implement versioning. For production APIs expected to evolve, adopt a versioning strategy:
/api/v1/send-sms,/api/v2/send-sms– Explicit and easy to route. Recommended for public APIs.Accept: application/vnd.yourapp.v1+json– Cleaner URLs but less visible./api/send-sms?version=1– Simple but pollutes URLs.Maintain backward compatibility for at least one major version. Document deprecation timelines clearly.
4. Configuring Plivo Credentials and Authentication
Proper integration requires correctly obtaining and configuring your Plivo credentials.
Sign Up/Log In: Go to the Plivo Console.
Find Auth ID and Auth Token:
Obtain a Sender ID (Plivo Number):
+14155551212).Update
.env.local: Paste the copied Auth ID, Auth Token, and your Plivo Number (Sender ID) into the respective variables in your.env.localfile.Restart Development Server: Crucially, after modifying
.env.local, stop (Ctrl+C) and restart your Next.js development server (npm run devoryarn dev) for the changes to take effect.Environment Variable Summary:
PLIVO_AUTH_ID: Your unique Plivo account identifier. Used for authenticating API requests. Obtain from Plivo Console Dashboard.PLIVO_AUTH_TOKEN: Your secret Plivo API key. Used for authenticating API requests. Obtain from Plivo Console Dashboard. Treat this like a password.PLIVO_SENDER_ID: The identifier messages originate from. For US/Canada, this must be a Plivo phone number you own, in E.164 format. Obtain by buying a number in the Plivo Console.Security Best Practices for Credential Rotation:
Rotate your
PLIVO_AUTH_TOKENevery 90 days to minimize exposure risk. Plivo allows generating a new Auth Token from the Console. After rotation:.env.local(development) immediately.For production systems, use secret management tools like AWS Secrets Manager, HashiCorp Vault, or Doppler to automate rotation and centralize credential access.
5. Error Handling and Logging Best Practices
Our API route includes basic error handling and logging.
Error Handling Strategy:
to,text) early and return a400 Bad Request.500 Internal Server Error.plivo.Clientcall. Log the detailed error server-side. Return an appropriate status code (Plivo's if available, otherwise 500) and a user-friendly error message (including Plivo's specific error if helpful) to the client.Logging:
console.logfor successful Plivo responses andconsole.errorfor configuration issues and Plivo API errors.console.log/errorwith calls to your chosen logging library.Retry Mechanisms:
503 Service Unavailable,504 Gateway Timeout, network errors, rate limit errors (429).400 Bad Request(invalid phone number),401 Unauthorized(bad credentials),402 Payment Required(insufficient credit),403 Forbidden.async-retrylibrary to wrap Plivo API calls. Install withnpm install async-retry.Testing Error Scenarios:
curlrequest missing thetoortextfield. Expect a 400 response.PLIVO_AUTH_IDorPLIVO_AUTH_TOKENin.env.local_ restart the server_ and send a valid request. Expect a 401 or similar authentication error from Plivo (logged server-side_ likely resulting in a 500 response to the client).tonumber (e.g._ "12345"). Expect a Plivo error (logged server-side_ likely a 400 or 500 response to the client).6. Database Schema and Data Layer
This specific guide focuses solely on the immediate action of sending an SMS via an API call and does not require a database.
If you were building a more complex application_ you might use a database to:
When Database Integration Becomes Necessary:
Example Schema (PostgreSQL with Prisma):
Implementing a database would involve choosing a database (e.g._ PostgreSQL_ MongoDB)_ selecting an ORM or client library (e.g._ Prisma_ Mongoose_ node-postgres)_ defining schemas/models_ and writing data access logic. This is outside the scope of this basic sending guide.
7. Security Features and Phone Number Validation
While basic_ security is crucial.
PLIVO_AUTH_ID_PLIVO_AUTH_TOKEN) out of the codebase and in.env.local(and ensuring.env.localis in.gitignore) is the most critical security step.toandtextprevents trivial errors.tofield to ensure it resembles an E.164 formatted number before sending it to Plivo. Libraries likelibphonenumber-jscan help parse and validate phone numbers./^\+[1-9]\d{1_14}$/. This ensures the number starts with+_ followed by a country code (1-9)_ and has a maximum of 15 digits total.rate-limiter-flexibleor Vercel's built-in helpers can be used.rate-limiter-flexible:For broader CORS needs_ use the
corsmiddleware package.8. Understanding E.164 Format and Special Cases
dst) to be in E.164 format (e.g._+14155551212). E.164 numbers start with+_ followed by a country code (1-3 digits)_ and the subscriber number_ with a maximum total of 15 digits. Ensure any user input is correctly formatted before sending to the API. The validation examples in section 7 help here.src. Other countries may allow Alphanumeric Sender IDs_ but these often require pre-registration and cannot receive replies. Trial accounts cannot use alphanumeric sender IDs. Always check Plivo's documentation for the target country's regulations.9. Performance Optimizations
For this simple API route_ performance is typically bound by the Plivo API response time.
async/await_ ensuring the Node.js event loop isn't blocked during the Plivo API call.next build) and tree-shaking to reduce function size.10. Monitoring_ Observability_ and Analytics
/api/send-sms(using a HEAD or GET request_ though our current code only allows POST) or a dedicated/api/healthendpoint.console.errorwith calls to your error tracking SDK.11. Common Issues and Troubleshooting
PLIVO_AUTH_IDorPLIVO_AUTH_TOKENin.env.localis incorrect or missing. Environment variables are not loaded correctly..env.localagainst the Plivo Console. Restart the Next.js server after any changes to.env.local. Ensure.env.localis in the project root. Verifyprocess.env.PLIVO_AUTH_IDis accessible within the API route code (add temporaryconsole.log).toortextfield:curlcommand or frontend code is sending a valid JSON body with both fields. Check thereq.bodyobject in the API route usingconsole.log. EnsureContent-Type: application/jsonheader is set in the request.dstparameter / Number requires + prefix:tonumber provided is not in the required E.164 format.+and country code (e.g._+14155551212). Implement server-side validation (see section 7) to check the format before sending to Plivo..env.localrequire restarting the Next.js development server. In production deployments (like Vercel)_ ensure environment variables are set correctly in the deployment platform's settings.PLIVO_SENDER_IDis SMS-enabled for the destination country. Check capabilities in the Plivo Console under Phone Numbers > Your Numbers.12. Deploying to Vercel with CI/CD
Deploy your Next.js application easily, especially with platforms like Vercel (the creators of Next.js).
Deploying to Vercel:
.env*.localis in your.gitignore.PLIVO_AUTH_ID,PLIVO_AUTH_TOKEN, andPLIVO_SENDER_IDwith their corresponding values. Ensure they are set for "Production" (and "Preview"/"Development" if needed). This is critical for the deployed application to work.your-project-name.vercel.app). Your API endpoint is available athttps://your-project-name.vercel.app/api/send-sms.CI/CD (Continuous Integration/Continuous Deployment):
mainormaster), Vercel automatically triggers a new build and deployment.Environment-Specific Configuration Strategies:
Manage separate configurations for development, staging, and production:
Rollback Procedures:
Vercel keeps a history of deployments. In the Vercel dashboard for your project:
This rollback process takes seconds and requires no code changes or redeploys.
13. Testing and Verification
Manual Verification:
npm run dev).PLIVO_AUTH_ID,PLIVO_AUTH_TOKEN, andPLIVO_SENDER_IDare correctly set (in.env.localfor local, Vercel dashboard for deployed).curl(as shown in section 3) or a tool like Postman/Insomnia to send a POST request to your/api/send-smsendpoint (use the Vercel URL if deployed).200 OKstatus and the expected JSON success payload.Automated Testing (Examples):
While comprehensive testing setup is extensive, here are conceptual examples:
Unit Test (API Route Logic): Use a testing framework like Jest to test the API handler function. Mock the
plivoSDK to avoid actual API calls during tests.Integration Test Example (Testing Full API Flow):
Edge Cases to Test:
{ to: "", text: "" }should return 400.Next Steps and Related Tutorials
Now that you have a functional SMS sending API, consider exploring these related implementations:
For more advanced messaging features, explore our other guides on scheduling reminders, marketing campaigns, and WhatsApp integration.