WAPI Gateway
Headless WhatsApp REST API Gateway with Fastify & Baileys

Project at a Glance
- Problem: Integrating automated WhatsApp alerts, transactional messages, or media dispatches into backend services often leads to tightly coupled scripts that lack proper HTTP authentication, request validation, reconnection resilience, or operational monitoring.
- Deliverables: A headless TypeScript + Fastify 5 REST API gateway wrapping Baileys (
@whiskeysockets/baileys), supporting text and media delivery (both multipart file upload and remote URL), number verification, session logout, Bearer token authentication, JSON Schema validation, typing simulation, optional Telegram Bot event & heartbeat monitoring, Vitest test setup, and Docker / PM2 deployment configs. - Core Stack: Node.js 18+, TypeScript 5, Fastify 5, Baileys (
@whiskeysockets/baileys), Pino, Helmet, Vitest, Docker / Docker Compose, PM2. - Practical Value: Built solo in 2026 as a clean, self-hostable open-source backend utility for programmatic WhatsApp notification and alert dispatching.
Project Overview
WAPI Gateway is a lightweight, headless WhatsApp API gateway built with TypeScript, Fastify 5, and Baileys. Rather than embedding WhatsApp Web socket handling directly inside application servers, external services communicate with WAPI Gateway over a standard JSON and multipart REST API secured by Bearer token authentication.
On first startup, the service prints a QR code to the terminal for WhatsApp Linked Devices pairing and persists session credentials locally under auth/. From there, it maintains an auto-reconnecting socket connection, logs structured operational events via Pino, and optionally reports connection health and periodic heartbeats to a Telegram Bot.
System Architecture & Request Flow
+-------------------------------------------------------------+
| EXTERNAL SERVICES / CRON / WEBHOOKS |
+------------------------------+------------------------------+
| HTTP (JSON / Multipart)
| Authorization: Bearer <API_KEY>
v
+-------------------------------------------------------------+
| FASTIFY 5 API SERVER |
| - Helmet Security Headers & Pino Structured Logging |
| - JSON Schema Request Validation |
| - preHandler Bearer Auth Hook (/api/*) |
+--------------+-------------------------------+--------------+
| |
v v
+-----------------------------+ +-----------------------------+
| WHATSAPP SERVICE | | TELEGRAM SERVICE |
| - Baileys Socket Client | | - Event Alerts (Connect, |
| - Local Session Storage | | Disconnect, Logout, QR) |
| - Auto-Reconnect Handler | | - Periodic Uptime Heartbeat|
| - Typing Delay Simulation | | (configurable interval) |
+--------------+--------------+ +--------------+--------------+
| |
v v
WhatsApp Web Socket Telegram Bot API
REST API Surface
All /api/* endpoints are protected by a Fastify preHandler Bearer token hook (Authorization: Bearer <API_KEY>), while GET /health remains unauthenticated for container and uptime probes:
| Method | Endpoint | Purpose |
|---|---|---|
GET | /health | Returns socket connection status, linked user JID, and server uptime |
GET | /api/status/:number | Checks whether a phone number (international format without +) is registered on WhatsApp |
POST | /api/message | Sends a text message with structured error codes (422 WA_NUMBER_NOT_FOUND, 503 WA_NOT_CONNECTED) |
POST | /api/media | Sends image, video, audio, or document via multipart/form-data (10MB default limit) |
POST | /api/media-url | Sends supported media directly from a remote URL with optional caption and required document filename |
POST | /api/logout | Logs out the active WhatsApp session and clears stored local auth credentials |
Core Engineering Highlights
- Layered Fastify Architecture:
- Clean separation across
config/(environment validation),hooks/(auth.hook.ts),routes/(api.ts,health.route.ts),controllers/(health,status,message,media), andservices/(whatsapp.service.ts,telegram.service.ts). - Built-in Fastify JSON Schema validation rejects malformed payloads at the boundary with standardized
VALIDATION_ERRORresponses before reaching the WhatsApp socket layer.
- Clean separation across
- Connection Resilience & Human-Like Pacing:
- Automatic reconnection handles transient socket drops without restarting the container.
- Configurable typing simulation (
WA_TYPING_DELAY,WA_TYPING_MIN_MS,WA_TYPING_CHAR_MS) introduces realistic pacing proportional to message length to reduce automated-behavior flags.
- Out-of-Band Telegram Monitoring:
- Because WhatsApp session disconnects or forced logouts require operator awareness (such as re-scanning a QR code), the optional Telegram service pushes instant notifications for
Connected,Disconnected,Logged out,QR needed, and periodicHeartbeatuptime summaries (default every 30 minutes).
- Because WhatsApp session disconnects or forced logouts require operator awareness (such as re-scanning a QR code), the optional Telegram service pushes instant notifications for
- Deployment & Operational Readiness:
- Ships with Helmet security headers, Pino structured JSON logging, Vitest test configuration,
Dockerfile+docker-compose.ymlfor containerized hosting, andecosystem.config.cjsfor PM2 process management.
- Ships with Helmet security headers, Pino structured JSON logging, Vitest test configuration,
Scope & Known Limitations
- Single-Session Design: Scoped intentionally as a lightweight 1-instance = 1-WhatsApp-number gateway rather than a multi-tenant SaaS hub.
- Unofficial Protocol Caveat: Because it relies on Baileys (an unofficial WhatsApp Web client library), protocol changes by WhatsApp/Meta can require library updates, and bulk/spam messaging risks account restrictions. Official commercial high-volume messaging should use Meta's WhatsApp Business API.