Published on

Getting Started with whatsapp_web.js — Build WhatsApp Bots with Node.js

Authors

Introduction

whatsapp-web.js is a powerful Node.js library that automates WhatsApp Web using Puppeteer, letting you create bots and automation workflows easily. You can build bots that send/receive messages, handle media, and even manage groups — all from your code.

⚠️ Important: Use responsibly. Automating WhatsApp via unofficial APIs can violate WhatsApp’s Terms of Service if misused (spam, scraping, etc.). Always use for educational or controlled use cases.


🧠 What You’ll Learn

In this guide, you’ll:

  • Build a WhatsApp bot with Node.js.
  • Scan a QR code to log in and persist session data.
  • Reply automatically to incoming messages.
  • Send and receive media (images, videos, etc.).
  • Learn best practices for running your bot safely.

🧰 Prerequisites

Make sure you have:

  • Node.js 16+ and npm/yarn
  • Basic JavaScript knowledge
  • WhatsApp account (to scan QR)
  • Desktop/laptop environment with Chromium (Puppeteer will handle it)

📦 Project Setup

Create a new project and install dependencies:

mkdir whatsapp-bot
cd whatsapp-bot
npm init -y
npm install whatsapp-web.js qrcode-terminal
  • whatsapp-web.js: Main library for interacting with WhatsApp
  • qrcode-terminal: Prints QR codes in your terminal

⚙️ Create Your First Bot

Create a file called index.js:

const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');

const client = new Client({
  authStrategy: new LocalAuth(),
  puppeteer: { headless: true },
});

client.on('qr', qr => {
  qrcode.generate(qr, { small: true });
  console.log('Scan the QR code above with WhatsApp mobile app');
});

client.on('ready', () => {
  console.log('✅ Client is ready!');
});

client.on('message', async msg => {
  console.log(`📩 Message from ${msg.from}: ${msg.body}`);

  if (msg.body.toLowerCase() === 'ping') {
    msg.reply('pong 🏓');
  }
});

client.initialize();

Run the bot:

node index.js

Scan the QR code displayed in the terminal via WhatsApp → Linked devices → Link a device.
Your session will be saved automatically using LocalAuth.


🔐 Session Persistence

LocalAuth stores authentication data inside ./.wwebjs_auth.
It ensures that you don’t have to scan the QR code every time you restart the bot.

If you’re deploying to cloud services (like Render, Railway, or VPS), make sure this folder is stored persistently.


💬 Sending Messages

// Send text message
await client.sendMessage('919876543210@c.us', 'Hello from my WhatsApp bot!');

💡 Format: @c.us for contacts, @g.us for groups.

You can also fetch contacts:

const chats = await client.getChats();
console.log(chats.map(c => c.name));

🖼️ Sending Media

const { MessageMedia } = require('whatsapp-web.js');

const media = MessageMedia.fromFilePath('./assets/image.jpg');
await client.sendMessage('919876543210@c.us', media, { caption: 'Here’s your image 📸' });

Or send a base64-encoded file:

const base64 = 'data:image/png;base64,iVBORw0K...';
const media2 = MessageMedia.fromDataUri(base64);
await client.sendMessage('919876543210@c.us', media2);

📥 Download Incoming Media

client.on('message', async msg => {
  if (msg.hasMedia) {
    const media = await msg.downloadMedia();
    const fs = require('fs');
    const buffer = Buffer.from(media.data, 'base64');
    fs.writeFileSync(`downloads/${msg.id.id}.jpg`, buffer);
    console.log('Media saved successfully ✅');
  }
});

Make sure to create a downloads/ directory before running.


🔍 Common Events

EventDescription
qrTriggered when QR code is generated
readyWhen the client is ready
messageIncoming message
message_createWhen you or bot send a message
auth_failureAuthentication failed
disconnectedSession lost or disconnected

🧩 Tips & Tricks

  • Disable headless mode in development:
    puppeteer: { headless: false }
    
  • Avoid spam: Don’t send too many messages in a short time.
  • Use test accounts: Avoid using your main number.
  • Logging: Use console.log wisely to debug message flow.

☁️ Deployment Notes

For persistent sessions in cloud hosting:

  • Use mounted storage (volume) or save session data to S3, Firebase, or Redis.
  • Re-initialize from stored session on startup.
  • If deploying with Docker, ensure Chromium dependencies are installed.

Automating WhatsApp unofficially can risk account bans if abused.
For enterprise or production-grade messaging, consider the WhatsApp Business API through Meta-approved providers.


📁 Project Structure Example

whatsapp-bot/
├─ index.js
├─ package.json
├─ .wwebjs_auth/
├─ downloads/
└─ assets/

🚀 Next Steps

  • Add custom commands like /help or /quote.
  • Store message history in MongoDB or PostgreSQL.
  • Build a dashboard using Express or Next.js.
  • Add error handling and logging using Winston or Pino.

✅ Conclusion

You now have a working WhatsApp bot running with whatsapp-web.js.
With just a few lines of code, you can send, receive, and automate tasks inside WhatsApp — perfect for learning automation, prototyping chat systems, or building educational tools.

Next goal: Add AI or NLP integrations (like OpenAI API or LangChain) to make your bot truly smart!