Send Images and Other Media via WhatsApp Using Node.js

April 16, 2019
Written by

Decorative header image for

The Twilio API for WhatsApp allows you to not only send text-based messages to WhatsApp numbers but also send and receive media messages. This allows you to send images (JPG, JPEG, PNG), audio files and even PDFs up to 5MB. Let's see how we can do this using Node.js.

If you prefer watching a video tutorial instead, check out this video on our YouTube channel:

 

First Things First

Before we get started, make sure you have:

If you want to try this out make sure to set up a new project by running:

mkdir whatsapp-media-messages
cd whatsapp-media-messages
npm init -y

Sending Your First Media Message

Install the twilio helper library by running:

npm install twilio

Create a new file called index.js and place the following code in it:

const twilio = require('twilio');
const client = twilio(
 process.env.TWILIO_ACCOUNT_SID,
 process.env.TWILIO_AUTH_TOKEN
);

client.messages
 .create({
   from: 'whatsapp:+WHATSAPP_SANDBOX_NUMBER',
   to: 'whatsapp:+YOUR_NUMBER',
   body: 'Ahoy from Twilio',
   mediaUrl: 'https://bit.ly/whatsapp-image-example',
 })
 .then(message => {
   console.log(message.sid);
 })
 .catch(err => {
   console.error(err);
 });

This will initialize a Twilio Client using the twilio helper library and then create a new message to your WhatsApp number. Make sure to change the WHATSAPP_SANDBOX_NUMBER and YOUR_NUMBER with the respective numbers and feel free to change the value of mediaUrl with a URL to any other image, sound snippet or PDF.

Afterwards run your code:

node index.js

You should receive a message with your media and the text you sent.

image of twilio sandbox chat

What's Next?

There are some differences between MMS and WhatsApp media messages. Media messages can only be sent to WhatsApp users if there is an active session established. Sessions are created when a user responds to a template message or the user initiates the conversation by sending in a message. A session lasts for 24h since the last message from the user. WhatsApp media messages also do not support some of the file types that MMS does. For more information on file type support check out the FAQs.

If you want to check out other things that are possible with the Twilio for WhatsApp API, check out the following posts:

I would love to see what you build. Feel free to ping me and tell me about it or let me know if you have any questions: