How can I create an API endpoint in a Payload CMS project to send SMS messages using Twilio?

To create an API endpoint in Payload CMS that sends SMS messages using Twilio, follow the steps below. This implementation also includes error handling to ensure smooth operation.

Install the Twilio SDK:

Make sure the Twilio Node.js SDK is installed in your project:

npm install twilio

Set up Environment Variables:

Add your Twilio credentials to your environment variables:

TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number

Create the API Endpoint:

In your Payload CMS project, create a custom API endpoint to handle the message sending. Here’s a sample implementation:

import type { PayloadHandler } from 'payload/config';
import twilio from 'twilio';


interface CustomPayloadHandler extends PayloadHandler {
  (req: any, res: any): Promise<void | any>;
}


export const sendTwilioMessage: CustomPayloadHandler = async (req, res): Promise<void> => {
  const { payload } = req;


  try {
    const { body } = req;
    const { to, message } = body; // Extract the recipient's phone number and the message from the request body


    // Load Twilio credentials from environment variables
    const accountSid = process.env.TWILIO_ACCOUNT_SID || '';
    const authToken = process.env.TWILIO_AUTH_TOKEN || '';
    const fromPhoneNumber = process.env.TWILIO_PHONE_NUMBER || '';


    // Create Twilio client
    const client = twilio(accountSid, authToken);


    // Send the message using Twilio
    const messageResponse = await client.messages.create({
      body: message,
      from: fromPhoneNumber,
      to: to,
    });


    // Respond with success and the message SID
    res.status(200).json({ success: true, messageSid: messageResponse.sid });
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    payload.logger.error(message);
    res.status(500).json({ error: message });
  }
};

Use the Endpoint:

Once the endpoint is set up, you can trigger it by sending a POST request with the to and message fields in the request body. For example:

POST /api/send-twilio-message
{
  "to": "+1234567890",
  "message": "Hello, this is a test message."
}

Leave a comment

Your email address will not be published. Required fields are marked *