A RESTful WhatsApp messaging API built with Express.js and Baileys library for seamless WhatsApp integration.
- 🏓 Ping/Pong - Health check endpoint
- 📊 Status Check - WhatsApp connection status monitoring
- 📨 Send Message - Send text messages to personal chats
- 👥 Send Group Message - Send messages to WhatsApp groups
- 🔗 Webhooks - Real-time event notifications via HTTP webhooks
- 🏢 Multi-Instance - Manage multiple WhatsApp instances simultaneously
- 🔌 Plugin Management - Per-instance plugin configuration and control
- 📋 Logging - Comprehensive logging for all activities
- 🔧 Modular Structure - Clean, maintainable, and scalable code structure
- Clone the repository:
git clone https://github.com/ibnusyawall/whisper-api.git
cd whisper-api- Install dependencies:
npm install- Set up environment variables:
cp .env.example .env-
Configure your
.envfile with the required variables (see Environment Variables section below). -
Set up the database (MongoDB with Prisma):
# Generate Prisma client
npx prisma generate
# Push database schema to MongoDB
npx prisma db push- Start the server:
# Development
npm run dev
# Production
npm startFor comprehensive API documentation, including all available endpoints, request/response examples, and testing collections, please refer to:
📚 API Collections Documentation
The API supports multiple operational modes:
- Single Instance Mode: Legacy endpoints for single WhatsApp instance
- Multi-Instance Mode: Advanced endpoints for managing multiple WhatsApp instances
- Hybrid Mode: Both single and multi-instance endpoints available simultaneously
Key endpoint categories:
- 🌐 Global Endpoints: Mode information and system status
- 🔀 Single Instance (Legacy): Basic WhatsApp messaging functionality
- 🏢 Multi-Instance Management: Instance creation, monitoring, messaging, webhook management, and plugin configuration
- Ensure
WHATSAPP_MODE=singleorWHATSAPP_MODE=bothin your.envfile - Start the server:
npm startornpm run dev - Scan the QR code displayed in the terminal using WhatsApp on your phone
- Check connection status:
GET /api/v1/status - Start sending messages using legacy endpoints
- Ensure
WHATSAPP_MODE=multiorWHATSAPP_MODE=bothin your.envfile - Configure
DATABASE_URLin your.envfile - Set up the database:
npx prisma generate && npx prisma db push - Start the server:
npm startornpm run dev - Create a WhatsApp instance:
POST /api/v1/instances - Get the QR code:
GET /api/v1/instances/{phone}/qr - Scan the QR code with WhatsApp on your phone
- Check instance status:
GET /api/v1/instances/{phone}/status - Start sending messages using multi-instance endpoints
# Check current mode
curl http://localhost:3000/api/v1/mode
# Create instance (multi-instance mode)
curl -X POST http://localhost:3000/api/v1/instances \
-H "Content-Type: application/json" \
-d '{"phone":"628123456789","name":"My Instance"}'
# Get QR code (multi-instance mode)
curl http://localhost:3000/api/v1/instances/628123456789/qrsrc/
├── app.js # Main application file
├── config/ # Configuration files
│ └── mode.config.js # WhatsApp mode configuration
├── controllers/ # Request handlers
│ ├── instance.controller.js # Multi-instance management
│ ├── log.controller.js # Logging handler
│ ├── message.controller.js # Message sending handler
│ ├── mode.controller.js # Mode information handler
│ ├── ping.controller.js # Health check handler
│ ├── status.controller.js # Status check handler
│ └── webhook.controller.js # Webhook management
├── core/ # Core system components
│ └── plugin-manager.core.js # Plugin management system
├── database/ # Database connection and setup
│ └── prisma.js # Prisma client configuration
├── plugins/ # Optional features as plugins
│ ├── admin-commands.plugin.js
│ ├── anti-mention.plugin.js
│ ├── eval-command.plugin.js
│ └── welcome-group.plugin.js
├── routes/ # API route definitions
│ └── index.js # Main routing configuration
├── services/ # Business logic and services
│ ├── instanceLogService.js # Instance logging service
│ ├── instanceService.js # Instance management service
│ ├── messageService.js # Message handling service
│ ├── webhookService.js # Webhook management service
│ ├── whatsapp.service.js # Legacy WhatsApp service
│ └── whatsappInstanceManager.service.js # Multi-instance manager
└── utils/ # Utility functions
└── logger.js # Winston logger utility
api-collections/ # API testing collections
├── global/ # Global endpoint tests
├── multi-instance/ # Multi-instance endpoint tests
├── single-instance/ # Legacy endpoint tests
├── postman_collection.json # Postman collection
└── README.md # API documentation
auth/ # Baileys authentication files
logs/ # Application logs
prisma/ # Prisma database schema
├── schema.prisma # Database schema definition
tests/ # Test files
├── database tests and setup
Configure the following environment variables in your .env file:
# Server Configuration
PORT=3000 # Port number for the server (default: 3000)
NODE_ENV=production # Environment mode: development, production
# Database Configuration (Required for Multi-Instance Mode)
DATABASE_URL="mongodb://localhost:27017/whisper-api"
# MongoDB connection string for Prisma
# Format: mongodb://[username:password@]host[:port]/database
# Example: mongodb://user:pass@localhost:27017/whisper-api
# WhatsApp Configuration
WHATSAPP_MODE=multi # Operational mode: single, multi, both
# - single: Legacy single-instance only
# - multi: Multi-instance management only (default)
# - both: Hybrid mode
# Logging Configuration
LOG_LEVEL=info # Logging level: error, warn, info, debug
DEBUG=true # Enable verbose debug output: true, false| Variable | Description | Default | Required |
|---|---|---|---|
PORT |
Server port number | 3000 |
No |
NODE_ENV |
Application environment | production |
No |
DATABASE_URL |
MongoDB connection string | - | Yes (for multi-instance) |
WHATSAPP_MODE |
Operational mode | multi |
No |
LOG_LEVEL |
Logging verbosity | info |
No |
DEBUG |
Debug mode toggle | false |
No |
The WHATSAPP_MODE variable determines which endpoints are available:
single: Only legacy single-instance endpoints (/api/v1/ping,/api/v1/message, etc.)multi: Only multi-instance endpoints (/api/v1/instances/*, webhooks, etc.)both: All endpoints available (recommended for development)
For multi-instance functionality, a MongoDB database with replica set support is required. This is essential for Prisma to handle transactions and ensure data consistency. You can either use a cloud provider that supports replica sets or set one up locally using Docker.
Important Note: Standard single-node MongoDB instances (like the default mongo:latest Docker image) will not work for multi-instance mode due to the lack of replica set functionality.
MongoDB Atlas provides free-tier clusters with replica sets enabled by default. This is the easiest and most reliable way to get started.
- Create a free cluster on MongoDB Atlas.
- Get your connection string (e.g.,
mongodb+srv://user:[email protected]/whisper-api). - Update
DATABASE_URLin your.envfile.
You can run a local MongoDB replica set using the provided Docker Compose file. This is ideal for development and testing.
-
Ensure you have Docker and Docker Compose installed.
-
Run the following command to start a single-node replica set:
docker-compose up -d
-
Update your
DATABASE_URLto use the local replica set:DATABASE_URL="mongodb://localhost:27017/whisper-api?replicaSet=rs0&directConnection=true" -
Stop the replica set when you're done:
docker-compose down
This setup provides a complete, isolated environment for running the database with the required replica set configuration.
- Format:
628123456789(with country code 62 for Indonesia) - Numbers starting with
0will be automatically formatted - Example:
08123456789→628123456789
- Group IDs typically end with
@g.us - Example:
[email protected] - Can be obtained from WhatsApp logs or other tools
- Logs are stored in the
logs/directory app.log- all application logserror.log- error logs only- Automatic log rotation (5MB per file, max 10 files)
The API returns standardized error responses:
{
"success": false,
"error": "Error type",
"message": "Detailed error message",
"timestamp": "2025-07-13T10:00:00.000Z"
}# Install Railway CLI
npm install -g @railway/cli
# Deploy
railway login
railway init
railway up# Install Vercel CLI
npm install -g vercel
# Deploy
vercel --prod- Connect your GitHub repository
- Set build command:
npm install - Set start command:
npm start - Deploy
# Using PM2 for process management
npm install -g pm2
pm2 start src/app.js --name whisper-api
pm2 startup
pm2 save# Health check
curl -X GET http://localhost:3000/api/v1/ping
# Send message
curl -X POST http://localhost:3000/api/v1/message \
-H "Content-Type: application/json" \
-d '{"phoneNumber":"628123456789","message":"Hello World!"}'
# Check status
curl -X GET http://localhost:3000/api/v1/statusconst axios = require('axios');
// Send message
const sendMessage = async () => {
try {
const response = await axios.post('http://localhost:3000/api/v1/message', {
phoneNumber: '628123456789',
message: 'Hello from Whisper API!'
});
console.log(response.data);
} catch (error) {
console.error(error.response.data);
}
};- The API supports three operational modes:
single,multi, andboth(hybrid) - Check current mode with
GET /api/v1/modebefore using specific endpoints - Keep the server running to maintain WhatsApp connections
- All API responses follow a consistent format with
success,data, andmessagefields
- QR code appears in terminal on first run or after logout
- WhatsApp session is stored in the
auth/directory - Don't delete the
auth/folder to maintain session - Service will automatically reconnect if disconnected
- Only one WhatsApp connection can be active at a time
- Requires MongoDB database connection for instance management
- Each instance has its own authentication state stored in the database
- QR codes are retrieved via API endpoints (
/api/v1/instances/{phone}/qr) - Multiple WhatsApp instances can run simultaneously
- Instance data persists between server restarts
- Webhooks can be configured per instance for real-time notifications
- Only available in multi-instance mode
- Configure webhooks per instance for different events
- Supported events:
message_received,message_sent,connection_status, etc. - Webhook URLs should be publicly accessible HTTPS endpoints
- MongoDB is required for multi-instance functionality
- Prisma ORM handles database operations
- Run
npx prisma db pushto sync schema changes - Database stores instances, webhooks, messages, and logs
- QR code not appearing in terminal: Delete the
auth/folder and restart the application - QR code expired: Restart the server to generate a new QR code
- Authentication failed: Clear the
auth/folder and scan a fresh QR code
- QR code not generated: Check if instance exists with
GET /api/v1/instances/{phone}/status - QR code endpoint returns error: Ensure the instance is in
pendingordisconnectedstate - QR code expired: Call
POST /api/v1/instances/{phone}/restartto generate a new one
- Connection lost: Check status with
GET /api/v1/statusand restart if needed - Messages not sending: Verify connection status and phone number format (628xxxxxxxxx)
- Service disconnected: Check logs and restart the application
- Instance not connecting: Check instance status with
GET /api/v1/instances/{phone}/status - Messages failing: Ensure instance is in
connectedstate before sending - Multiple instances failing: Check database connection and MongoDB availability
- Webhook not receiving events: Verify webhook URL is accessible and uses HTTPS
- Connection failed: Verify
DATABASE_URLin.envfile - Schema out of sync: Run
npx prisma db pushto update database schema - Migration errors: Run
npx prisma generatefollowed bynpx prisma db push - MongoDB not accessible: Ensure MongoDB is running and accessible at the specified URL
- Port already in use: Change
PORTin.envor kill existing processes withlsof -ti:3000 | xargs kill -9 - Wrong operational mode: Check
WHATSAPP_MODEin.envand restart server - Environment variables not loaded: Ensure
.envfile exists and is properly formatted - Service instability: Check logs in
logs/directory for detailed error information
- High memory usage: Monitor instance count and consider restarting instances periodically
- Slow response times: Check database performance and consider adding indexes
- Rate limiting: WhatsApp may limit message sending; implement delays between messages
- Log file size: Configure log rotation or clear old logs from
logs/directory
- API endpoints not working: Verify the correct mode is set and endpoints are available
- CORS errors: Configure CORS settings if accessing from browser applications
- Authentication errors: Ensure proper headers and request format as per API documentation
- Webhook testing: Use tools like ngrok for local webhook testing with public HTTPS URLs
- Fork the repository
- Create a 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
This project is licensed under the MIT License - see the LICENSE file for details.
This project is for educational and development purposes. Please ensure you comply with WhatsApp's Terms of Service when using this API.
If you found this project helpful, please give it a ⭐ star!
For issues and questions, please create an issue in the GitHub repository.