WebNest
Team/Shahnawaz Sazid/WhatsApp-Bot-Backend

Repository

WhatsApp-Bot-Backend

View on GitHub ↗
TypeScript0 stars0 forks

README

WhatsApp Backend API

A role-based backend system to send WhatsApp messages via WhatsApp Web, track message status, and communicate with a frontend (for now using terminal) using Socket.IO.

This project supports message sending, message queuing, message storing in database, QR code authentication, auto-reconnect, and real-time status updates. also test case written.

Project Flow

Server Initialization

  • Express server starts and sets up API routes and Socket.IO for real-time communication.
  • WhatsApp client is initialized via whatsapp-web.js with local authentication.

WhatsApp Service (WhatsAppService)

  • Maintains WhatsApp client connection, QR code, and status.
  • Handles sending messages via a queue (PQueue) to prevent overload.
  • Stores each message to MongoDB (MessageLog) with status: PENDING, SENT, or FAILED.
  • Supports auto-reconnect if the client disconnects (checks authentication session if authenticated no need to scan qr code again).
  • The flow is if authenticated one time the qr code will not be generated again until the session is destroyed.

Socket.IO Integration

  • Emits WhatsApp status, QR code, and disconnection events in real-time to frontend.
  • Frontend can request current QR/status anytime.

API Endpoints (WhatsAppRoutes)

MethodEndpointDescription
GET/statusGet WhatsApp status, QR, and queue stats
GET/qrGet QR code if not authenticated
POST/send/textSend a text message (rate-limited, validated)
DELETE/disconnectDisconnect WhatsApp client manually

Validation & Error Handling

  • Requests validated with Zod schemas (sendTextMessageSchema).
  • Errors handled with AppError and catchAsync.
  • Returns HTTP-friendly responses with sendResponse.

Technologies Used

  • Node.js & Express → REST API backend
  • TypeScript → Type safety
  • whatsapp-web.js → Connect and send messages via WhatsApp Web
  • Socket.IO → Real-time communication with frontend
  • PQueue → Concurrency-controlled message queue
  • Zod → Request validation
  • MongoDB (Mongoose) → Message logging
  • dotenv → Environment variable management
  • http-status-codes → Clean status codes
  • Jest + Supertest -> USED FOR Testing purposes

Messaging Flow

Server Start (npm run dev / node server.js)
        │
        ▼
Load Environment Variables (.env)
        │
        ▼
Connect to MongoDB
        │
        ▼
Initialize Express App & Middlewares
        │
        ▼
Initialize Socket.IO (initSocket)
        │
        ▼
WhatsAppService.initialize(io)  ← Start WhatsApp Client
        │
        ▼
Create WhatsApp Client (whatsapp-web.js)
        │
        ▼
┌─────────────────────────────────────
│ Check if previous session exists     │
│ - If yes, authenticate automatically │
│ - If no, generate QR code            │
└──────────────────────────────────────
        │
        ▼
QR Code Generated? (Client not authenticated)
        │
        ▼
Emit QR via Socket.IO → Frontend scans QR
        │
        ▼
WhatsApp Client Authenticated
        │
        ▼
Set WhatsApp Status → READY
        │
        ▼
Frontend / API Request
  - POST /send/text
  - GET /status /qr
        │
        ▼
Request Validation (Zod Schema)  ← Validate phone, message
        │
        ▼
WhatsAppService.sendMessage()
        │
Message Valid & Client Ready?
  - Yes → Add to PQueue (Concurrency 5)
  - No  → Throw Error / 503
        │
        ▼
Queue Processes Message
        │
WhatsApp Client Sends Message
        │
        ▼
Update MessageLog in MongoDB
  - Status: SENT / FAILED
  - messageId, timestamp
        │
        ▼
Emit Real-Time Updates via Socket.IO
  - Status
  - Queue Stats
  - QR (if needed)
        │
        ▼
Frontend Receives Updates
  - Message Status
  - WhatsApp Status
  - QR Code (if scanning required)

Testing Summary

  • Validation Tests (Zod)
  • Check if message and phone number are valid before hitting API
  • Reject empty, missing, invalid, or too long messages.
  • API Tests (Supertest + Jest)
  • Send message: success for valid payload, fail for invalid/missing fields.
  • WhatsApp status & QR: retrieve status and QR, handle 404 if not available.
  • Errors: 503 if WhatsApp not ready, 500 if send fails.
  • Disconnect: properly disconnects client.
  • Rate limiting: ensures excessive requests return 429.
  • Mocks: WhatsAppService methods are mocked, so tests run without real WhatsApp.

Installation

  • clone the repository
git clone https://github.com/Sazid60/WhatsApp-Bot-Backend.git
cd WhatsApp-Bot-Backend
  • Install dependencies
npm install
  • set the env file
PORT=5000
DB_URL=mongodb+srv://<name>:<pass>@cluster0.cjbmdks.mongodb.net/wp_app?retryWrites=true&w=majority&appName=Cluster0
NODE_ENV=development
EXPRESS_SESSION_SECRET=express-session
FRONTEND_URL=http://localhost:3000
WHATSAPP_SESSION_PATH=./sessions
  • run test
# Run all tests
npm run test

# Run tests with coverage
npm run test:coverage
  • run the project
npm run dev
``
← Back to profile