@hdriel/whatsapp-socket
v1.2.0
Published
A TypeScript/JavaScript wrapper library for WhatsApp Web Socket communication, built on top of [@fadzzzslebew/baileys](https://github.com/fadzzzslebew/baileys). This package provides a simplified, high-level API for interacting with WhatsApp Web with supp
Maintainers
Readme
@hdriel/whatsapp-socket
A TypeScript/JavaScript wrapper library for WhatsApp Web Socket communication, built on top of @fadzzzslebew/baileys. This package provides a simplified, high-level API for interacting with WhatsApp Web with support for multi-device connections.
⚠️ Disclaimer
This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or affiliates. The official WhatsApp website can be found at https://whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
Use at your own risk. WhatsApp does not allow bots or unofficial clients on their platform. Using this library may result in your WhatsApp account being banned.
Features
- 🚀 WebSocket-based communication with WhatsApp Web (powered by Baileys)
- 📱 QR code authentication or pairing code authentication
- 💬 Send text messages
- 🔗 Send interactive button messages (URL, call, copy, ~~email~~, ~~reminder~~)
- 🔂 Send reply buttons messages
- 🖼️ Send images with captions
- 🎥 Send videos
- 🎵 Send audio messages
- 📄 Send documents/files
- 🎨 Send stickers (WebP format, up to 5MB)
- 💾 Session persistence (file-based or MongoDB)
- 🔂 Singleton instances to prevent multiple connection for same WhatsApp Web token (by one of props: appName/pairingPhone/mongoCollection/fileAuthStateDirectoryPath)
- 📝 Full TypeScript support
- 🎬 FULL DEMO SERVER & CLIENT: github repo
demo-server directory run
npm startopen browser
http://localhost:1010
⚠️ Important: Server Requirements
This service MUST run on a persistent server (e.g., VPS, dedicated server, or container) and NOT on serverless platforms like AWS Lambda, Google Cloud Functions, or Vercel Serverless Functions.
The WhatsApp socket connection requires a persistent, stateful connection that stays alive and maintains session state. Serverless functions:
- Have short execution timeouts (typically 15-900 seconds)
- Cannot maintain long-lived WebSocket connections
- Restart frequently, losing connection state
- Will cause multiple connection attempts, which WhatsApp may flag as suspicious behavior
Recommended hosting options:
- VPS (DigitalOcean, Linode, Vultr)
- Dedicated servers
- Docker containers on persistent infrastructure
- AWS EC2/ECS, Google Compute Engine, or Azure VM (not Lambda/Cloud Functions)
Installation
npm install @hdriel/whatsapp-socketor
yarn add @hdriel/whatsapp-socketFor MongoDB session storage (optional):
npm install mongodbQuick Start
import { WhatsappSocket } from '@hdriel/whatsapp-socket';
import path from 'path';
const client = new WhatsappSocket({
// File-based session storage (recommended for development)
fileAuthStateDirectoryPath: path.resolve(__dirname, './authState/my-profile'),
// Or use MongoDB for production (optional)
// mongoURL: 'mongodb://localhost:27017/whatsapp-sessions-app',
// logger, // Custom logger (npm stack-trace-logger) instance (optional)
// Print QR code in terminal
printQRInTerminal: true,
// Enable debug mode
debug: true,
// When failed to connecting before sending messages
onPreConnectionSendMessageFailed: (error: Error) => {...}
// Connection status callback
onConnectionStatusChange: (status: 'open' | 'close' | 'connecting') => {
console.log('Connection status:', status);
},
// QR code callback
onQR: async (qr, qrCode) => {
console.log('QR Code received');
// Convert QR string to image
const qrImage = await WhatsappSocket.qrToImage(qr);
// Display qrImage to user for scanning
},
// Connection opened
onOpen: async () => {
console.log('WhatsApp connection opened!');
},
// Connection closed
onClose: async () => {
console.log('WhatsApp connection closed');
}
});
// Start the connection
await client.startConnection();
// Check if connected
if (client.isConnected()) {
// Send a text message
await client.sendTextMessage('050-000-0000', 'Hello World!');
}API Reference
Connection Management
startConnection()
Start the WhatsApp connection. This will trigger QR code generation if not authenticated.
await client.startConnection();closeConnection()
Close the WhatsApp connection.
await client.closeConnection();resetConnection(options?)
Reset the connection and generate a new QR code or use phone pairing.
// Generate new QR code
await client.resetConnection();
// Or use phone number pairing
await client.resetConnection({ pairingPhone: '050-000-0000' });isConnected()
Check if the client is currently connected.
const connected = client.isConnected();
console.log('Connected:', connected);Messaging Methods
sendTextMessage(jid, text)
Send a plain text message.
await client.sendTextMessage(
'0500000000',// or 050-000-0000 converted to 972500000000 , or define DEFAULT_COUNTRY to change 972 to your country
'Hello, this is a test message!'
);sendButtonsMessage(jid, options)
Send an interactive message with action buttons.
await client.sendButtonsMessage('[email protected]', {
title: 'Welcome to our service!',
subtitle: 'Please choose an action below',
buttons: [
{ label: 'Visit Website', url: 'https://example.com' },
{ label: 'Call Us', tel: '050-123-4567' },
{ label: 'Copy Code', copy: 'PROMO2024' },
// { label: 'Email Us', email: '[email protected]' }, // not supported
// not supported
// {
// label: 'Set Reminder',
// reminderName: 'Follow up call',
// reminderOn: '20m' // or use reminderDate
// }
]
});sendReplyButtonsMessage(jid, options)
Send a message with reply buttons (quick reply options).
await client.sendReplyButtonsMessage('[email protected]', {
title: 'Choose your preferred time',
subtitle: 'Click one of the options below',
buttons: [
'Morning (9-12)',
'Afternoon (12-5)',
'Evening (5-9)'
]
});sendImageMessage(jid, buffer, options?)
Send an image message.
import fs from 'fs';
const imageBuffer = fs.readFileSync('./photo.jpg');
await client.sendImageMessage('050-000-0000', imageBuffer, {
caption: 'Check out this photo!',
filename: 'photo.jpg'
});sendVideoMessage(jid, buffer, caption?)
Send a video message.
const videoBuffer = fs.readFileSync('./video.mp4');
await client.sendVideoMessage(
'050-000-0000',
videoBuffer,
{ caption: 'Amazing video!' }
);sendAudioMessage(jid, buffer, options?)
Send an audio message.
const audioBuffer = fs.readFileSync('./audio.mp3');
await client.sendAudioMessage('050-000-0000', audioBuffer, {
filename: 'audio.mp3',
mimetype: 'audio/mpeg'
});sendFileMessage(jid, buffer, options?)
Send a document/file message.
const fileBuffer = fs.readFileSync('./document.pdf');
await client.sendFileMessage('050-000-0000', fileBuffer, {
filename: 'document.pdf',
mimetype: 'application/pdf',
caption: 'Here is the requested document'
});sendStickerMessage(jid, buffer)
Send a sticker message (must be WebP format).
const stickerBuffer = fs.readFileSync('./sticker.webp');
await client.sendStickerMessage('050-000-0000', stickerBuffer);Utility Methods
WhatsappSocket.qrToImage(qr)
Convert QR code string to base64 image.
const qrImage = await WhatsappSocket.qrToImage(qrString);
console.log(qrImage); // data:image/png;base64,...
// In client side <img src={qrImage} />WhatsappSocket.randomPairingCode(pattern)
Generate a random pairing code.
// Generate 6-digit numeric code
const code = WhatsappSocket.randomPairingCode('[0-9]');
// Generate alphanumeric code
const alphaCode = WhatsappSocket.randomPairingCode('[a-z0-9]');Phone Number Format
Support normal format and converters to expected format for example:
- Individual chats: 050-111-2222 || 0501112222 =>
[email protected] - Group chats: Not handle yet group chats implementations
Note: WhatsApp uses JID (Jabber ID) format for phone numbers
- Individual chats:
{phone_number}@s.whatsapp.net - Group chats:
{group_id}@g.us
Default Country Code
Changing the default country code it using on the static field like:
WhatsappSocket.DEFAULT_COUNTRY_CODE = '510';Complete Express.js Example
Here's a complete example of an Express.js server with Socket.IO integration:
import express from 'express';
import http from 'http';
import { Server as SocketIO } from 'socket.io';
import { WhatsappSocket } from '@hdriel/whatsapp-socket';
import path from 'path';
const app = express();
const server = http.createServer(app);
const io = new SocketIO(server);
app.use(express.json());
// Initialize WhatsApp client
const client = new WhatsappSocket({
fileAuthStateDirectoryPath: path.resolve(__dirname, './authState/my-profile-data'),
printQRInTerminal: true,
debug: true,
onConnectionStatusChange: (status) => {
io.emit('connection-status', status);
},
onQR: async (qr, qrCode) => {
const qrImage = await WhatsappSocket.qrToImage(qr);
io.emit('qr', { qrImage, qrCode });
},
onOpen: () => io.emit('qr-connected'),
onClose: () => io.emit('qr-disconnected')
});
// Start connection on server start
client.startConnection();
// Socket.IO connection
io.on('connection', (socket) => {
console.log('Client connected');
socket.emit('connected');
});
// API Routes
app.post('/api/connect', async (req, res) => {
await client.startConnection();
res.json({ message: 'OK' });
});
app.post('/api/disconnect', async (req, res) => {
await client.closeConnection();
res.json({ message: 'OK' });
});
app.post('/api/generate-qr', async (req, res) => {
const { phone } = req.body;
await client.resetConnection({ pairingPhone: phone });
res.json({ message: 'OK' });
});
app.post('/api/send-message', async (req, res) => {
const { phoneTo, message } = req.body;
await client.sendTextMessage(phoneTo, message);
res.json({ message: 'OK' });
});
app.post('/api/send-buttons', async (req, res) => {
const { phoneTo, title, subtitle, buttons } = req.body;
await client.sendButtonsMessage(phoneTo, { title, subtitle, buttons });
res.json({ message: 'OK' });
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});File Upload Example with Multer
import multer from 'multer';
import bytes from 'bytes';
const storage = multer.memoryStorage();
const uploadImage = multer({
storage,
limits: { fileSize: bytes('50MB') },
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed'));
}
}
});
app.post('/api/upload-image', uploadImage.single('image'), async (req, res) => {
const imageFile = req.file;
if (!imageFile) {
return res.status(400).json({ message: 'No image file provided' });
}
const { phoneTo, caption } = req.body;
await client.sendImageMessage(phoneTo, imageFile.buffer, {
caption,
filename: imageFile.originalname
});
res.json({ message: 'OK' });
});Session Storage
File-Based Storage (Recommended for Development)
const client = new WhatsappSocket({
fileAuthStateDirectoryPath: path.resolve(__dirname, './authState/my-profile')
});Session files will be stored in the specified directory and automatically loaded on subsequent connections.
MongoDB Storage (Recommended for Production)
const client = new WhatsappSocket({
mongoURL: 'mongodb://localhost:27017/whatsapp-sessions'
});For MongoDB storage, install the peer dependency:
npm install mongodbBest Practices
Session Management: Always store session data securely. For production, use MongoDB or encrypted file storage.
Rate Limiting: Implement rate limiting to avoid sending too many messages in a short period, which could result in being banned.
Error Handling: Always wrap API calls in try-catch blocks:
try { await client.sendTextMessage(jid, message); } catch (error) { console.error('Failed to send message:', error); }Testing: Test with a secondary phone number before using with your primary account
TypeScript Support
The library is written in TypeScript and includes complete type definitions:
import { WhatsappSocket } from '@hdriel/whatsapp-socket';
// All methods and options are fully typed
const client: WhatsappSocket = new WhatsappSocket({
fileAuthStateDirectoryPath: './authState',
debug: true
});Troubleshooting
QR Code Not Generating
- Ensure
printQRInTerminalis set totrueor handle theonQRcallback - Check that the session directory has write permissions
- Try calling
resetConnection()to generate a new QR code
Connection Keeps Dropping
- Check your internet connection
- Verify that session data is being saved correctly
- Ensure MongoDB is accessible if using MongoDB storage
- Check WhatsApp Web's status (sometimes WhatsApp blocks certain IPs)
Messages Not Sending
- Verify the phone number format / default country set correctly
- Check if the number is registered on WhatsApp
- Ensure the connection is active using
isConnected() - Check for rate limiting
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see the LICENSE file for details.
Dependencies
- @fadzzzslebew/baileys - Core WhatsApp Web API
- qrcode - QR code generation
- pino - Logging
- music-metadata - Audio metadata extraction
- ms - Time string parsing
Author
Hadriel Benjo
- GitHub: @hdriel
- LinkedIn: Hadriel Benjo
- YouTube: @Just-Like-That
Remember: This is an unofficial library. Use responsibly and at your own risk. Always respect WhatsApp's Terms of Service.
🔗 Links
- GitHub fadzzzslebew/Baileys
- GitHub Demo Repository
- @hdriel/whatsapp-socket npm package
- Automating WhatsApp
Made with ❤️ for developers who want powerful Whatsapp Bot utilities without the complexity, ⭐ me on GitHub
