How to Send a WhatsApp Message with Node.js (Tutorial)
Published on November 7, 2023

Post updated by Amanda Cavallaro

Traditionally, businesses contact customers by phone or SMS. But sometimes you really want to communicate with your customers via WhatsApp.

Connecting with customers via WhatsApp is easy thanks to the Vonage Messages API. With Vonage, you can send WhatsApp in a variety of programming languages, including Node.js. In this tutorial, we’ll show you how to send and receive WhatsApp messages using Node.js, with help from the Vonage Messages API.

Prerequisites

To start sending WhatsApp messages with Node.js, you’ll need the following prerequisites:

How to Send WhatsApp Messages With Node (5 Steps)

In this tutorial, we’ll show you how to send WhatsApp in Node.js with the following five steps:

  1. (Set up a WhatsApp sandbox)[1-set-up-a-whatsapp-sandbox]

  2. (Create your WhatsApp data)[2-create-your-whatsapp-data]

  3. (Create a POST Request in Node)[3-create-a-post-request-in-node]

  4. (Make the Node Request)[4-make-the-node-request]

  5. (Test Your Code by Sending a Message to WhatsApp)[5-test-your-code-by-sending-a-message-to-whatsapp]

1. Set Up a WhatsApp Sandbox

To get started, navigate to Messages Sandbox in your dashboard to set up your WhatsApp sandbox. This sandbox will allow you to send messages to WhatsApp through the Messages API.

Screenshot of Vonage Messages SandboxScreenshot of Vonage Messages Sandbox

The quickest way to set up the sandbox is to take your device with WhatsApp installed and center the camera on the QR code supplied. Sending the custom message generated will allowlist your number.

You'll see several additional options for joining the allowlist, including manually creating a message to the number supplied with a unique passphrase. If none of the others will work for your setup, that one should.

Screenshot of WhatsApp message that says Hi! Your luck number is 31Screenshot of WhatsApp message that says Hi! Your luck number is 31

2. Create Your WhatsApp Data

To make a call to the sandbox API, you'll need to supply a unique username, password, and to and from WhatsApp numbers.

The username and password will be the two halves of the u argument in the cURL command from your dashboard. Copy the masked value, which will look like 12ab3456:123AbcdefghIJklM. The part before the colon is your username, and the part after is your password. They're the same as your Vonage API key and secret, which are also available from Getting Started in the dashboard.

You can also copy the data for your request straight from the cURL command and stringify it. This tells the API to send a text message from the sandbox number to your allowlisted number. You can change the text of the message to whatever you like, including generating it programmatically:

const user = '12ab3456';
const password = '123AbcdefghIJklM';
const from_number = '14151234567';
const to_number = '441234567890';

const data = JSON.stringify({
  "from": { "type": "whatsapp", "number": from_number },
  "to": { "type": "whatsapp", "number": to_number },
  "message": {
    "content": {
      "type": "text",
      "text": "Hi! Your lucky number is " + Math.floor(Math.random() * 100)
    }
  }
});

Create a POST Request in Node

Now that you’ve set up a sandbox and created your WhatsApp data, the next step is to create a POST request in Node. The code to send a POST request with Node's https module is verbose might seem complicated, but it's just listing the ordinary parts of an HTTP request. First, you'll require the module. Then, you’ll and then construct an object with the request options.

Most of the options, like the hostname, port, and method, would be the same for any request to the sandbox API. All you'll need to provide besides those are your authorization variables:

const https = require('https');

const options = {
  hostname: 'messages-sandbox.nexmo.com',
  port: 443,
  path: '/v0.1/messages',
  method: 'POST',
  authorization: {
    username: user,
    password: password
  },
  headers: {
    'Authorization': 'Basic ' + btoa(`${user}:${password}`),
    'Content-Type': 'application/json'
  }
};

4. Make the Node Request

With your request options defined, you can go ahead and make the request using the https module's request function. You'll pass in your options and a callback, which gets any response to your request. The response contains an HTTP status code, and you can listen for any additional data sent back, which should be a message UUID if everything works correctly.

You can also create an error listener on the request itself.

Once you've created your request, you can write your data object to the request. This tells the API to send the WhatsApp message. Then you can close the request and end your code:

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', (d) => {
    process.stdout.write(d)
  })
});

req.on('error', (e) => {
  console.error(e);
});

req.write(data);
req.end();

5. Test Your Code by Sending a Message to WhatsApp

Now you can save your code in a file called app.js. After that, you can test sending a message from your WhatsApp sandbox to your whitelisted WhatsApp number.

From the directory where the file is saved, run:

> node app.js

If you’ve followed the instructions in this post, your Node file should successfully send a message from the WhatsApp sandbox. At this point, the test message should appear in WhatsApp on your allowlisted device.

Troubleshooting: If your message was sent successfully and you received a 202 status, but the message never showed up, your permissions may have expired. An easy fix is to send your allowlisting passphrase again. To understand more about WhatsApp policies and charges, check out the WhatsApp concepts document.

Conclusion

Congratulations! By following the steps in this tutorial, you’ve created a basic Node.js app that sends messages via WhatsApp.

You can find the code for this example on GitHub. Hope you enjoyed this tutorial, and feel free to send a message to us from Vonage on X, previously known as Twitter, or join the Vonage Community Slack.

Further Reading

How to Send and Receive SMS Messages With Node.js

How to Send WhatsApp Messages With Laravel

Messages API Technical Details

Understanding WhatsApp messaging

Messages API Sandbox Concepts

Garann MeansDeveloper Educator

I'm a JavaScript developer and a Developer Educator at Vonage. Over the years I’ve been really excited about templates, Node.js, progressive web apps, and offline-first strategies, but what I’ve always really loved is a useful, well-documented API. My goal is to make your experience using our APIs the very best I can help it be.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.