How you can send messages to authenticate users with Next.js and Twilio integration?

Learn how to integrate Twilio with a Next.js app to send SMS messages seamlessly and enhance user communication.

Raisa Kanagaraj

Content Marketing Lead

In today’s digital world, integrating SMS functionality into web applications can significantly enhance user engagement and communication. Whether you're building an e-commerce platform, a SaaS product, or a personal project, the ability to send text messages directly from your app can be a game-changer.

In this tutorial, we’ll walk through how to integrate Twilio, a popular cloud communications platform, with a Next.js application to send SMS messages to phones. By the end of this guide, you'll have a fully functional setup that allows your Next.js app to communicate with users via SMS.

Prerequisites

Before we dive in, ensure you have the following:

  • Node.js installed on your machine (v14 or higher).
  • A Twilio account (sign up at twilio.com).
  • Basic knowledge of JavaScript, React, and Next.js.
  • A code editor like VS Code.

Step 1: Setting Up Your Twilio Account

1.1 Create a Twilio Account

If you haven’t already, head over to Twilio and create a free account. Once you’ve signed up, Twilio will provide you with:

Account SID: A unique identifier for your Twilio account.

Auth Token: A secret token used to authenticate API requests.

Twilio Phone Number: A phone number you can use to send SMS messages.

You can find these details in your Twilio console under the Dashboard section.

1.2 Install Twilio CLI (Optional)

While not necessary for this tutorial, installing the Twilio CLI can help you manage your Twilio resources more efficiently. You can install it using npm:

npm install -g twilio-cli

After installation, log in using:

twilio login

Step 2: Setting Up a Next.js Project

If you don’t already have a Next.js project, you can quickly set one up using the following commands:

npx create-next-app@latest twilio-nextjs-sms
cd twilio-nextjs-sms 
 

This will create a new Next.js project in the twilio-nextjs-sms directory.

Step 3: Installing Twilio SDK

To interact with Twilio's API, we need to install the Twilio Node.js SDK. Run the following command in your project directory:

npm install twilio

Step 4: Creating an API Route in Next.js

Next.js allows us to create serverless API routes, which are perfect for handling sensitive operations like sending SMS messages. We’ll create an API route that will handle the logic for sending SMS messages.

4.1 Create the API Route

Inside the pages/api directory, create a new file called send-sms.js. This file will contain the logic to send SMS messages using Twilio.

// pages/api/send-sms.js

import { Twilio } from 'twilio';

// Load environment variables
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;

// Initialize Twilio client
const client = new Twilio(accountSid, authToken);

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { to, body } = req.body;

    try {
      // Send SMS using Twilio
      const message = await client.messages.create({
        body: body,
        from: twilioPhoneNumber,
        to: to,
      });

      // Return success response
      res.status(200).json({ success: true, message: 'SMS sent successfully!', sid: message.sid });
    } catch (error) {
      console.error(error);
      res.status(500).json({ success: false, error: 'Failed to send SMS' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

4.2 Explanation of the Code

Twilio Client Initialization: We initialize the Twilio client using the accountSid, authToken, and twilioPhoneNumber loaded from environment variables.

POST Request Handling: The API route only accepts POST requests. It expects a JSON payload with to (the recipient's phone number) and body (the message content).

Sending SMS: The client.messages.create() method sends the SMS. If successful, it returns a response with the message SID.

Error Handling: If something goes wrong, the API returns a 500-status code with an error message.

4.3 Environment Variables

To keep your credentials secure, store them in environment variables. Create a .env.local file in the root of your project and add the following:

TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number

Make sure to replace your_account_sid, your_auth_token, and your_twilio_phone_number with the actual values from your Twilio dashboard.

Important: Add .env.local to your .gitignore file to prevent sensitive information from being committed to version control.

Step 5: Creating a Frontend Form to Send SMS

Now that we have our API route ready, let’s create a simple front-end form where users can input a phone number and message to send an SMS.

5.1 Create the Form Component

Create a new file called SendSMS.js inside the components directory:

 // components/SendSMS.js

import { useState } from 'react';

export default function SendSMS() {
  const [phoneNumber, setPhoneNumber] = useState('');
  const [message, setMessage] = useState('');
  const [response, setResponse] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const res = await fetch('/api/send-sms', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ to: phoneNumber, body: message }),
    });

    const data = await res.json();
    setResponse(data);
  };

  return (
    <div>
      <h1>Send SMS via Twilio</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="phoneNumber">Phone Number:</label>
          <input
            type="text"
            id="phoneNumber"
            value={phoneNumber}
            onChange={(e) => setPhoneNumber(e.target.value)}
            placeholder="+1234567890"
            required
          />
        </div>
        <div>
          <label htmlFor="message">Message:</label>
          <textarea
            id="message"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder="Enter your message here"
            required
          />
        </div>
        <button type="submit">Send SMS</button>
      </form>

      {response && (
        <div>
          <h3>Response:</h3>
          <p>{response.success ? 'SMS sent successfully!' : 'Failed to send SMS'}</p>
          {response.sid && <p>Message SID: {response.sid}</p>}
        </div>
      )}
    </div>
  );
}

5.2 Explanation of the Code

State Management: We use React's useState hook to manage the phone number, message, and API response.

Form Submission: When the form is submitted, we make a POST request to our /api/send-sms endpoint with the phone number and message as the payload.

Response Handling: After receiving a response from the API, we display whether the SMS was sent successfully or if there was an error.

5.3 Integrate the Form into a Page

Now, let’s integrate the form into one of our pages. Open pages/index.js and import the SendSMS component:

// pages/index.js

import SendSMS from '../components/SendSMS';

export default function Home() {
  return (
    <div>
      <SendSMS />
    </div>
  );
}

Step 6: Testing the Integration

Start your Next.js development server:

npm run dev 

Navigate to http://localhost:3000 in your browser. You should see the form where you can enter a phone number and message. Submit the form, and if everything is set up correctly, you should receive an SMS on the specified phone number.

Conclusion

In this tutorial, we learned how to integrate Twilio with a Next.js application to send SMS messages. We created an API route to handle the SMS sending logic securely and built a simple frontend form to interact with this API.

With this setup, you can now extend the functionality to include features like user authentication, message templates, or even scheduling SMS messages. Twilio offers a wide range of capabilities beyond SMS, such as voice calls, WhatsApp messages, and more, so feel free to explore further!

Written by Raisa Kanagaraj

Tags

Other blogs

You may also like


Your one-stop shop for expert RoR services

join 250+ companies achieving top-notch RoR development without increasing your workforce.