Categories: FAANG

Integrating Twilio WhatsApp API with a Node.js Application

In this article, we will be exploring how to integrate the Twilio WhatsApp API with a Node.js application. Twilio provides an easy-to-use API for integrating messaging services such as WhatsApp into your applications. By the end of this tutorial, you’ll have a functioning Node.js application that can send and receive messages using the Twilio WhatsApp API.

Table of Contents

  1. Prerequisites
  2. Setting up a Twilio Account
  3. Installing the Twilio SDK
  4. Sending WhatsApp Messages using Twilio
  5. Receiving WhatsApp Messages using Twilio
  6. Implementing a Basic Echo Bot
  7. Conclusion

1. Prerequisites

Before we begin, ensure that you have the following installed on your system:

  • Node.js (version 12 or higher)
  • npm (Node.js package manager)
  • A code editor (e.g., Visual Studio Code)

2. Setting up a Twilio Account

To start using the Twilio API, you need to create an account on their platform. Visit the Twilio website and sign up for a free account. After signing up, follow the instructions to enable the WhatsApp Sandbox. Note down the following details:

  • Account SID
  • Auth Token
  • Sandbox Number

You’ll need these to authenticate your application with Twilio.

3. Installing the Twilio SDK

Create a new directory for your Node.js application and navigate to it in your terminal. Run the following command to initialize a new Node.js project:

npm init -y

Next, install the Twilio SDK by running:

npm install twilio

4. Sending WhatsApp Messages using Twilio

Create a new file called sendWhatsAppMessage.js and open it in your code editor. First, import the Twilio module and initialize a Twilio client using your Account SID and Auth Token:

const twilio = require('twilio');
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = new twilio(accountSid, authToken);

Replace ‘your_account_sid’ and ‘your_auth_token’ with the respective values from your Twilio account.

Now, create a function to send WhatsApp messages using the Twilio client:

async function sendWhatsAppMessage(to, message) {
try {
const response = await client.messages.create({
body: message,
from: 'whatsapp:+14155238886', // Your Twilio Sandbox Number
to: `whatsapp:${to}`,
});
console.log(`Message sent to ${to}: ${response.sid}`);
} catch (error) {
console.error(`Failed to send message: ${error}`);
}
}

sendWhatsAppMessage('+1234567890', 'Hello from Twilio WhatsApp API!'); // Replace with your phone number

Replace +1234567890 with your own phone number, including the country code, and run the script:

node sendWhatsAppMessage.js

You should receive a WhatsApp message from the Twilio Sandbox number.

5. Receiving WhatsApp Messages using Twilio

To receive WhatsApp messages, you need to set up a webhook for incoming messages. We’ll use the express framework for our web server and ngrok to expose our local server to the internet. Install the required packages:

npm install express ngrok

Create a new file called receiveWhatsAppMessage.js and open it in your code editor. Set up a basic express server

const express = require('express'); 
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: false }));

app.post('/incoming', (req, res) => {
const message = req.body;
console.log(Received message from ${message.From}: ${message.Body});
res.status(200).send('OK');
});

app.listen(port, () => {
console.log(Server running on http://localhost:${port});
});

In this code, we create an Express server and define a route for incoming messages at `/incoming`. When a message is received, we log the sender’s phone number and message content to the console. Next, expose your local server to the internet using `ngrok`.

Create a new file called `start.js` and add the following code:

const ngrok = require('ngrok'); 
const { spawn } = require('child_process');

(async () => {
const url = await ngrok.connect(3000);
console.log(`ngrok tunnel opened at ${url}`);
const receiveWhatsAppMessageProcess = spawn('node', ['receiveWhatsAppMessage.js'], { stdio: 'inherit', });
process.on('SIGINT', async () => {
console.log('Shutting down…');
await ngrok.kill();
receiveWhatsAppMessage
Process.kill('SIGINT');
process.exit(0);
});
})();

This script starts the ngrok tunnel and runs our receiveWhatsAppMessage.js script as a child process. When the script is terminated, it will close the ngrok tunnel and child process.

Run the start.js script:

node start.js

You should see the ngrok tunnel URL in your console. Copy this URL and add /incoming to the end of it. Update the webhook URL for your Twilio Sandbox number by going to your Twilio Console, selecting your Sandbox number, and pasting the ngrok URL into the “A MESSAGE COMES IN” field. Save the changes.

Now, send a message to your Twilio Sandbox number, and you should see the message details logged in your console.

6. Implementing a Basic Echo Bot

As a practical example, let’s create a simple echo bot that replies to incoming messages. Update the /incoming route in your receiveWhatsAppMessage.js file:

const MessagingResponse = require('twilio').twiml.MessagingResponse;

app.post('/incoming', (req, res) => {
const message = req.body;
console.log(`Received message from ${message.From}: ${message.Body}`);
const twiml = new MessagingResponse();
twiml.message(`You said: ${message.Body}`);
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});

This code creates a TwiML response using the Twilio SDK’s MessagingResponse class. The response contains a new message with the original message’s content. When Twilio receives the response, it will send the reply to the sender.

Restart your start.js script, and send another message to your Twilio Sandbox number. You should receive a reply with the message content.

Conclusion

In this article, we’ve shown you how to integrate the Twilio WhatsApp API with a Node.js application. You learned how to send and receive messages using the Twilio API, and we demonstrated a simple echo bot example. With these building blocks, you can now create more complex chatbots and integrate WhatsApp messaging into your applications using Node.js and Twilio, In the next article, I’ll explain how to integrate WhatsApp API with ChatGPT.


Integrating Twilio WhatsApp API with a Node.js Application was originally published in Chatbots Life on Medium, where people are continuing the conversation by highlighting and responding to this story.

AI Generated Robotic Content

Recent Posts

RELEASE – The model you’ve all been waiting for – Smartphone Snapshot Photo Reality v13 – OMEGA

This is a LoRA for FLUX Klein Base 9b. **Link: https://civitai.red/models/2381927/flux2-klein-base-9b-smartphone-snapshot-photo-reality-style** All infos on how…

4 hours ago

Asus Zenbook A16 (2026) Review: Savor the Power, Ignore the Beige

This $2,000 Asus laptop delivers breathtaking performance thanks to Qualcomm's Snapdragon X2 Elite Extreme, but…

5 hours ago

The realism is getting out of hand

ComfyUI with ZIT submitted by /u/Ferwien [link] [comments]

1 day ago

Tovala Family Meals Review: Good Food, Lots of Salt

Tovala is a meal kit that comes with a smart oven, or a smart oven…

1 day ago

Open weight (and closed) Models with character sheet inputs

Now that we have some open weight models available to us that work with character…

2 days ago

Reinforced Agent: Inference-Time Feedback for Tool-Calling Agents

This paper was accepted at the Fifth Workshop on Natural Language Generation, Evaluation, and Metrics…

2 days ago