A powerful, enterprise-grade REST API for WhatsApp Web built with Express.js and whatsapp-web.js. This fully containerized solution provides comprehensive WhatsApp automation with advanced features including bulk messaging, real-time webhooks, database persistence, message queuing, and much more.
- Rate Limiting: Protection against API abuse with configurable limits
- Request Validation: Joi-based schema validation for all endpoints
- Response Compression: Gzip compression for faster API responses
- Security Headers: Helmet.js integration for enhanced security
- CORS Configuration: Flexible cross-origin resource sharing setup
- Error Logging: Winston-based structured logging with daily rotation
- Database Integration: MongoDB for message/contact persistence
- Message Queue: Bull/Redis-based queue for bulk operations
- Bulk Messaging: Send messages to multiple recipients with queue management
- Message Reactions: Send and receive emoji reactions
- Polls: Create and manage polls in chats
- Status/Stories: Post and manage WhatsApp statuses
- Contact Management: Block/unblock contacts
- Typing Indicators: Show typing status in chats
- Always Online: Keep WhatsApp presence always available
- Enhanced Webhooks: Retry logic and database logging for webhook events
- Message Operations
- Send text messages to individuals and groups
- Send media files (images, videos, audio, documents)
- Send voice messages with automatic audio conversion
- Send videos as GIFs
- Support for multipart file uploads
- NEW: Bulk message sending with queue management
- NEW: Message reactions
- Get all chats and contacts
- Fetch chat messages with customizable limits
- Archive/unarchive chats
- Pin/unpin chats
- Mute/unmute chats (with custom duration)
- Mark chats as read/unread
- Delete chats and clear messages
- NEW: Typing indicators
- Create new groups
- Get group information and participants
- Add/remove participants
- Promote/demote admins
- Configure group settings (message permissions, info permissions)
- Leave groups
- NEW: Create and manage polls
- Block/unblock contacts
- Get contact information
- Track blocked contacts in database
- Post text statuses
- Post media statuses
- Custom status styling options
- Webhook support with automatic retry logic
- Database logging of all webhook deliveries
- Message received/sent events
- Message acknowledgment tracking
- NEW: Message reaction events
- Group join/leave notifications
- Call notifications
- Authentication status updates
- Contact change events
- MongoDB integration for data persistence
- Message history storage
- Contact information tracking
- Webhook delivery logs
- Automatic data synchronization
- Redis-based message queue for bulk operations
- Rate limiting and request throttling
- Structured logging with daily rotation
- Health check endpoints with detailed status
- Graceful shutdown handling
- Docker Compose orchestration
- Docker and Docker Compose (recommended)
- Node.js 20+ (if running without Docker)
- MongoDB 7.0+ (provided via Docker)
- Redis 7+ (provided via Docker)
cd /opt/containers/whatsapp-web
Edit .env
file:
# Server Configuration
PORT=3000
NODE_ENV=production
# API Authentication
API_KEY=your-secret-api-key-change-this
# Webhook Configuration
WEBHOOK_URL=https://your-webhook-endpoint.com/webhook
WEBHOOK_RETRY_ATTEMPTS=3
WEBHOOK_RETRY_DELAY=5000
# Database Configuration
MONGODB_URI=mongodb://mongodb:27017/whatsapp-api
# Redis Configuration
REDIS_HOST=redis
REDIS_PORT=6379
# Rate Limiting
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_REQUESTS=100
# WhatsApp Features
ALWAYS_ONLINE=true
# Logging
LOG_LEVEL=info
LOG_DIR=/app/logs
docker-compose up -d
This will start:
- WhatsApp API server (port 3000)
- MongoDB (port 27017)
- Redis (port 6379)
- Open your browser:
http://localhost:3000/qr
- Scan the QR code with WhatsApp mobile app
- Wait for authentication to complete
All API endpoints (except /qr
and /health
) require authentication:
# Using X-API-Key header
curl -H "X-API-Key: your-secret-api-key" http://localhost:3000/api/info
# Using Authorization Bearer
curl -H "Authorization: Bearer your-secret-api-key" http://localhost:3000/api/info
POST /api/send-bulk-messages
Send messages to multiple recipients with automatic queuing:
curl -X POST http://localhost:3000/api/send-bulk-messages \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{
"number": "1234567890",
"message": "Hello User 1",
"delay": 2000
},
{
"number": "0987654321",
"message": "Hello User 2",
"delay": 2000
}
]
}'
Response:
{
"success": true,
"message": "2 messages queued",
"jobs": [
{ "number": "1234567890", "jobId": "1" },
{ "number": "0987654321", "jobId": "2" }
]
}
POST /api/send-reaction
Send emoji reaction to a message:
curl -X POST http://localhost:3000/api/send-reaction \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"messageId": "true_1234567890@c.us_ABCDEF123456",
"reaction": "👍"
}'
POST /api/create-poll
Create a poll in a chat:
curl -X POST http://localhost:3000/api/create-poll \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"number": "1234567890",
"question": "What is your favorite color?",
"options": ["Red", "Blue", "Green", "Yellow"],
"allowMultipleAnswers": false
}'
GET /api/poll-votes/:messageId
Get poll results:
curl -H "X-API-Key: your-api-key" \
http://localhost:3000/api/poll-votes/MESSAGE_ID
POST /api/set-typing
Show or hide typing indicator:
curl -X POST http://localhost:3000/api/set-typing \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"chatId": "1234567890@c.us",
"typing": true
}'
POST /api/send-status
Post a text status:
curl -X POST http://localhost:3000/api/send-status \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"content": "Hello from the API!",
"backgroundColor": "#25D366",
"font": 1
}'
Post a media status:
curl -X POST http://localhost:3000/api/send-status \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"mediaUrl": "https://example.com/image.jpg",
"content": "Check this out!"
}'
POST /api/block-contact
Block a contact:
curl -X POST http://localhost:3000/api/block-contact \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"contactId": "1234567890@c.us"
}'
POST /api/unblock-contact
Unblock a contact:
curl -X POST http://localhost:3000/api/unblock-contact \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{
"contactId": "1234567890@c.us"
}'
All original v1.0 endpoints remain available with the /api/
prefix:
- POST /api/send-message - Send text message
- POST /api/send-media - Send media from URL or base64
- POST /api/send-file - Upload and send file
- GET /api/contacts - Get all contacts
- GET /api/chats - Get all chats
- GET /api/chat/:chatId/messages - Get chat messages
- POST /api/group/create - Create group
- GET /api/group/:groupId - Get group info
- POST /api/group/:groupId/add-participants - Add participants
- POST /api/group/:groupId/remove-participants - Remove participants
- POST /api/group/:groupId/promote - Promote to admin
- POST /api/group/:groupId/demote - Demote from admin
- POST /api/group/:groupId/settings - Update group settings
- POST /api/group/:groupId/leave - Leave group
- GET /api/profile-picture/:contactId - Get profile picture
- POST /api/chat/:chatId/archive - Archive chat
- POST /api/chat/:chatId/pin - Pin chat
- POST /api/chat/:chatId/mute - Mute chat
- POST /api/chat/:chatId/mark-read - Mark as read
- DELETE /api/chat/:chatId - Delete chat
- POST /api/logout - Logout
- POST /api/restart - Restart client
Event | Description |
---|---|
message_reaction |
Emoji reaction received on a message |
All webhook events now include:
- Automatic retry with exponential backoff
- Database logging for audit trail
- Detailed error tracking
{
"event": "message_reaction",
"data": {
"id": "reaction_id",
"msgId": "message_id",
"reaction": "👍",
"senderId": "1234567890@c.us",
"timestamp": 1234567890
},
"timestamp": "2024-10-01T12:00:00.000Z"
}
Stores all sent and received messages:
{
messageId: String,
chatId: String,
from: String,
to: String,
body: String,
type: String, // 'chat', 'image', 'video', 'audio', 'poll', etc.
hasMedia: Boolean,
timestamp: Number,
ack: Number, // Delivery status
fromMe: Boolean,
isForwarded: Boolean
}
Stores contact information:
{
contactId: String,
name: String,
number: String,
isMyContact: Boolean,
isBlocked: Boolean,
profilePicUrl: String,
labels: [String]
}
Tracks webhook delivery:
{
event: String,
payload: Mixed,
webhookUrl: String,
status: String, // 'pending', 'success', 'failed', 'retrying'
statusCode: Number,
retryCount: Number,
errorMessage: String
}
┌─────────────────────┐
│ WhatsApp API │
│ (Express + WW.js) │
│ Port: 3000 │
└──────┬──────────────┘
│
├─────────────────┐
│ │
┌──────▼──────┐ ┌─────▼──────┐
│ MongoDB │ │ Redis │
│ Port: 27017│ │ Port:6379│
└─────────────┘ └────────────┘
- whatsapp-api: Main application server
- mongodb: Database for persistence
- redis: Message queue and caching
./sessions
- WhatsApp session data./logs
- Application logsmongodb_data
- MongoDB dataredis_data
- Redis persistence
# Start all services
docker-compose up -d
# View logs
docker-compose logs -f whatsapp-api
# Stop all services
docker-compose down
# Rebuild after code changes
docker-compose up -d --build
# View database logs
docker-compose logs -f mongodb
# View queue logs
docker-compose logs -f redis
Variable | Description | Default |
---|---|---|
PORT |
Server port | 3000 |
NODE_ENV |
Environment | production |
API_KEY |
API authentication key | Required |
WEBHOOK_URL |
Webhook endpoint URL | Optional |
WEBHOOK_RETRY_ATTEMPTS |
Max webhook retries | 3 |
WEBHOOK_RETRY_DELAY |
Retry delay (ms) | 5000 |
SESSION_PATH |
Session storage path | /app/sessions |
MONGODB_URI |
MongoDB connection string | mongodb://mongodb:27017/whatsapp-api |
REDIS_HOST |
Redis hostname | redis |
REDIS_PORT |
Redis port | 6379 |
RATE_LIMIT_WINDOW_MS |
Rate limit window | 60000 |
RATE_LIMIT_MAX_REQUESTS |
Max requests per window | 100 |
CORS_ORIGIN |
Allowed CORS origins | * |
ALWAYS_ONLINE |
Keep presence online | true |
LOG_LEVEL |
Logging level | info |
LOG_DIR |
Log directory | /app/logs |
Enhanced health endpoint with detailed status:
curl http://localhost:3000/health
Response:
{
"status": "ok",
"ready": true,
"database": true,
"timestamp": "2024-10-01T12:00:00.000Z"
}
Logs are stored in ./logs
directory:
combined-YYYY-MM-DD.log
- All logserror-YYYY-MM-DD.log
- Error logs only- Automatic daily rotation
- 14-day retention
error
- Errors onlywarn
- Warnings and errorsinfo
- General information (default)debug
- Detailed debuggingverbose
- Very detailed logs
Default: 100 requests per minute per IP
Customize in .env
:
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_REQUESTS=100
- Maximum: 100 messages per request
- Automatic queue management
- Configurable delays between messages
- Retry on failure (3 attempts)
- Maximum file size: 50MB
- Automatic audio conversion for voice messages
- Supports all WhatsApp media types
.
├── index.js # Main application
├── config.js # Configuration management
├── package.json # Dependencies
├── Dockerfile # Docker image
├── docker-compose.yml # Docker orchestration
├── .env # Environment variables
├── .gitignore # Git ignore rules
├── src/
│ ├── models/
│ │ ├── database.js # Database connection
│ │ ├── Message.js # Message model
│ │ ├── Contact.js # Contact model
│ │ └── WebhookLog.js # Webhook log model
│ ├── validators/
│ │ ├── schemas.js # Joi validation schemas
│ │ └── validate.js # Validation middleware
│ └── utils/
│ └── logger.js # Winston logger config
├── sessions/ # WhatsApp sessions (auto-generated)
└── logs/ # Application logs (auto-generated)
# Check MongoDB status
docker-compose logs mongodb
# Restart MongoDB
docker-compose restart mongodb
# Check Redis status
docker-compose logs redis
# Clear Redis queue
docker-compose exec redis redis-cli FLUSHALL
# Clear session and restart
docker-compose down
rm -rf sessions/*
docker-compose up -d
Increase Docker resources or adjust:
# docker-compose.yml
services:
whatsapp-api:
shm_size: '4gb' # Increase from 2gb
- Change default API key immediately
- Use HTTPS for webhook URLs
- Restrict CORS to specific domains
- Enable rate limiting (included by default)
- Use strong MongoDB passwords in production
- Keep dependencies updated regularly
- Monitor logs for suspicious activity
- Backup database regularly
- Use environment variables for secrets
- Implement IP whitelisting for production
- API endpoints now use
/api/
prefix - Database required for full functionality
- Redis required for bulk messaging
- Update
docker-compose.yml
with new services - Update
.env
with new variables - Update API endpoint URLs to include
/api/
prefix - Install new dependencies:
npm install
- Start new services:
docker-compose up -d
- Enable compression (included by default)
- Use bulk messaging for multiple recipients
- Implement caching for frequently accessed data
- Monitor database indexes for query performance
- Use Redis for session storage in multi-instance setups
- Enable log rotation to prevent disk space issues
- Set appropriate rate limits based on your needs
MIT
Built with:
- whatsapp-web.js - WhatsApp Web API client
- Express.js - Web framework
- MongoDB - Database
- Redis - Cache and queue
- Bull - Job queue
- Winston - Logging
- Joi - Validation
- Helmet - Security
- Puppeteer - Headless Chrome
- FFmpeg - Media processing
For issues and questions:
- Check the troubleshooting section
- Review application logs:
docker-compose logs -f
- Check database connectivity
- Verify environment variables
- Consult documentation
Version: 2.0.0 Last Updated: October 2024