Skip to content

IndraFer/apiBaileysWA

Repository files navigation

API Baileys WA Socket

WhatsApp REST API powered by Baileys WA Sockets. Built with Hono + TypeScript and features Dual-Runtime Support (runs natively on Bun or Node.js). Includes a built-in Visual Dashboard for easy management, keep clean simple and avoid heavy over-engineering.

Note

This project is not meant to be a full-fledged WhatsApp server. It is a wrapper around the Baileys library, providing an HTTP interface for easier integration with other applications, don't use it for spamming or any activities that's prohibited by WhatsApp META.

Disclaimer: This project is 100% AI-assisted and intended for educational purposes only. It will be maintained as a side project in spare time only, with no guarantees of ongoing support, updates, or production readiness.

Thus, we do not store WhatsApp messages or any other data (aside from credentials for auto-reconnecting).


✨ Features

Feature Description
Dual Runtime Support Run on ultra-fast Bun or standard Node.js (cPanel/VPS compatible)
Visual Dashboard Built-in UI to manage sessions, webhooks, and send messages
Dashboard RBAC Role-based access (admin, manager, assistant) + approvals
Session Assignment ACL Optional per-user assigned sessions (dashboard scope only)
Multi-Session Manage multiple WhatsApp accounts simultaneously
QR Code & Pairing Code Connect via QR scan or 8-digit pairing code
Complete Chat API Send text, media, forward, delete, read messages
Broadcast Queue Bulk message sending with anti-spam delays
Group & Profile Full management (create, participants, status, picture)
Media Handling Download, process, retrieve, and auto-cleanup old media
Webhook System Retries, exponential backoff, and signature modes
Dual Auth State Save session data to Files (dev) or Redis (production)
API Authentication Bearer token or Redis-stored API keys with roles
Hardened Dashboard Auth JWT auth, stream token for SSE, password policy, approval flow
Swagger/OpenAPI Built-in interactive API documentation at /docs
Docker Support Ready-to-use Dockerfiles for both Bun and Node.js

πŸš€ Quick Start

1. Prerequisite (Choose One Runtime)

  • Bun: Ultra-fast, ideal for VPS or Home Servers (Recommended).
  • Node.js: Standard, portable, ideal for cPanel VPS or traditional Node.js hosting.
  • Docker: Containerized deployment. Ensure you have Docker Compose installed.

2. Local Setup (Bun OR Node.js)

# Clone the repository
git clone <repository-url>
cd baileys-wa-api

# Configure Environment
cp .env.example .env
# Edit .env and configure DASHBOARD_JWT_SECRET

Running with Bun (Fastest)

bun install

# Development (Auto-reload)
bun run dev

# Production Build
bun run start

Running with Node.js (Highest Compatibility)

npm install

# Development (via tsx watch)
npm run dev:node

# Production Build
npm run start:node

The API will start at http://localhost:3000. Access the following default routes:

  • πŸ–₯️ Dashboard: http://localhost:3000/dashboard/
  • πŸ“– Swagger Docs: http://localhost:3000/docs
  • πŸ’š Health Check: http://localhost:3000/status

🐳 Docker Deployment

The project provides configurations for both runtimes. Redis is highly recommended and included in the docker-compose setups.

Option A: Docker with Bun (Default & Recommended)

docker compose up -d
docker compose logs -f api

Option B: Docker with Node.js

If you prefer forcing the native Node.js container:

docker compose -f docker-compose.node.yml up -d
docker compose -f docker-compose.node.yml logs -f api

To stop containers: docker compose down


πŸ–₯️ Visual Dashboard

The API includes an intuitive, modular web dashboard to manage everything visually without touching the CLI.

Dashboard Configuration (.env)

DASHBOARD_ENABLED=true
DASHBOARD_REGISTRATION_ENABLED=false
DASHBOARD_REGISTRATION_REQUIRE_APPROVAL=true
DASHBOARD_JWT_SECRET=super-secret-key-change-me
DASHBOARD_PASSWORD_MIN_LENGTH=6

Initial Setup

  1. Open http://localhost:3000/dashboard/ in your browser.
  2. If data/dashboard-users.json is empty, you will be prompted to create the very first Admin Account.
  3. Create your account with a secure password (hashed via bcryptjs).
  4. Once created, recommended to set DASHBOARD_REGISTRATION_ENABLED=false in .env to prevent public sign-ups.

Role & Access Model

  • admin: full dashboard access (users/approval/roles, session lifecycle, webhooks, all messaging).
  • manager: operational access for chats/outbound/groups, without admin-level account controls.
  • assistant: reply-focused dashboard role (no proactive outbound), for safer delegated handling.
  • Optional assignedSessions: per-user session scoping in dashboard APIs/UI only.

Registration & Approval Behavior

  • DASHBOARD_REGISTRATION_ENABLED=false: registration form is disabled for additional users.
  • DASHBOARD_REGISTRATION_REQUIRE_APPROVAL=true: newly registered users remain pending until approved by admin.
  • The first bootstrap admin (when user file is empty) is created immediately.

Features

  • Sessions: Add WhatsApp accounts (QR/Pairing Code), Delete accounts safely (auto-cleans media/logs).
  • Messaging: Test sending texts, images, and bulk broadcasts interactively.
  • Webhooks: Configure webhook URLs and event subscriptions per-session.
  • Events: Real-time SSE (Server-Sent Events) live log for WhatsApp events.

πŸ” API Authentication

The raw REST API /chats, /groups, etc., supports two authentication methods:

1. Simple Token (Dev / Single-User)

Set AUTH_GLOBAL_TOKEN in .env:

AUTH_GLOBAL_TOKEN=your-secret-token-here

Supported headers for simple token mode:

  • Authorization: Bearer <token>
  • x-api-key: <token>
  • x-access-token: <token>
  • token: <token>

Use in requests:

curl -H "Authorization: Bearer your-secret-token-here" http://localhost:3000/sessions

2. Redis API Keys (Production / Multi-User)

Requires REDIS_ENABLED=true. Manage keys using the CLI:

# Bun Runtime
bun run manage-api-keys create user

# Node.js Runtime
npm run manage-api-keys:node create admin

Use header: x-api-key: <your-api-key>

# Create user API key
bun run manage-api-keys create user

# Create admin API key
bun run manage-api-keys create admin

# List all keys
bun run manage-api-keys list

# Delete a key
bun run manage-api-keys delete <api-key>

Use in requests:

curl -H "x-api-key: <your-api-key>" http://localhost:3000/sessions

Note: In development mode (NODE_ENV=development), API authentication is skipped entirely.

Dashboard Authentication (UI)

  • Dashboard endpoints (/dashboard/api/*) use JWT-based auth.
  • SSE/Event stream endpoints use short-lived stream-scoped tokens.
  • Stream token endpoint: GET /dashboard/api/auth/stream-token

πŸ“± API Usage Examples

Create Session (Pairing Code)

POST /sessions/my-session
Content-Type: application/json

{
  "usePairingCode": true,
  "phoneNumber": "+6281234567890",
  "webhookUrl": "http://your-server.com/webhook"
}

Send an Image

POST /chats/my-session/send
Content-Type: application/json

{
  "receiver": "6281234567890",
  "message": {
    "image": { "url": "https://example.com/image.jpg" },
    "caption": "Check this out!"
  }
}

Send Bulk Messages (Anti-Spam)

POST /chats/my-session/send-bulk
Content-Type: application/json

{
  "messages": [
    { "receiver": "6281234567890", "message": { "text": "Hello #1" } },
    { "receiver": "6281234567891", "message": { "text": "Hello #2" } }
  ]
}

Response:

{
	"success": true,
	"message": "Broadcast job created",
	"data": { "jobId": "bc_1709271000_abc123", "total": 3, "status": "pending" }
}

Track progress:

GET /chats/my-session/broadcast/bc_1709271000_abc123

Create a Group

POST /groups/my-session/create
Content-Type: application/json

{
  "groupName": "API Test Group",
  "participants": ["6281234567890", "6281234567891"]
}

Webhook Events

Set WEBHOOK_URL in .env or per-session. Events are sent as POST:

{
  "sessionId": "my-session",
  "event": "messages.upsert",
  "data": { "messages": [...], "type": "notify" }
}

When signature mode is enabled, webhook requests can include:

  • x-webhook-timestamp
  • x-webhook-signature: sha256=<hmac>

Controlled by:

  • WEBHOOK_SIGNATURE_MODE=off|optional|required
  • WEBHOOK_ALLOW_GLOBAL_TOKEN_FALLBACK=true|false

Fallback order for webhook auth/signing secret:

  1. Per-session webhook secret
  2. AUTH_GLOBAL_TOKEN (only when fallback is enabled)

Available events:

  • connection.update β€” Connection state changes (QR, open, close)
  • messages.upsert β€” New messages received
  • messages.update β€” Message status updates (sent, delivered, read)
  • messages.delete β€” Messages deleted
  • messages.reaction β€” Reactions added/removed
  • chats.upsert, chats.update, chats.delete
  • contacts.upsert, contacts.update
  • groups.upsert, groups.update
  • group-participants.update
  • presence.update
  • blocklist.set, blocklist.update

πŸ“‚ Project Structure

baileys-wa-api/
β”œβ”€β”€ data/                           # Dashboard users and internal dashboard data (JSON)
β”œβ”€β”€ media/                          # Downloaded media files
β”œβ”€β”€ sessions/                       # Auth/session state per WhatsApp session
β”œβ”€β”€ scripts/
β”‚   └── manage-api-keys.ts          # API key management CLI
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts                    # Runtime entry point (Bun/Node)
β”‚   β”œβ”€β”€ app.ts                      # Hono app bootstrap + routes + docs
β”‚   β”œβ”€β”€ config.ts                   # Centralized environment config
β”‚   β”œβ”€β”€ baileys/
β”‚   β”‚   β”œβ”€β”€ connection.ts           # BaileysConnection class
β”‚   β”‚   β”œβ”€β”€ connectionManager.ts    # Multi-session manager
β”‚   β”‚   β”œβ”€β”€ types.ts                # Type definitions
β”‚   β”‚   β”œβ”€β”€ authState/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.ts            # Auth state factory
β”‚   β”‚   β”‚   β”œβ”€β”€ file.ts             # File-based auth
β”‚   β”‚   β”‚   └── redis.ts            # Redis-based auth
β”‚   β”‚   β”œβ”€β”€ store/
β”‚   β”‚   β”‚   └── memoryStore.ts      # In-memory message store
β”‚   β”‚   └── helpers/
β”‚   β”‚       β”œβ”€β”€ downloadMedia.ts    # Media download utilities
β”‚   β”‚       └── shouldIgnoreJid.ts  # JID filtering
β”‚   β”œβ”€β”€ dashboard/
β”‚   β”‚   β”œβ”€β”€ api.ts                  # Dashboard backend APIs (stats/events/webhooks)
β”‚   β”‚   β”œβ”€β”€ auth.ts                 # Dashboard auth + users/roles/approval
β”‚   β”‚   β”œβ”€β”€ eventBus.ts             # In-process event bus for SSE
β”‚   β”‚   └── loader.ts               # Dashboard route/static loader
β”‚   β”œβ”€β”€ dashboard-ui/
β”‚   β”‚   β”œβ”€β”€ index.html              # Dashboard SPA shell
β”‚   β”‚   β”œβ”€β”€ css/
β”‚   β”‚   β”‚   └── styles.css
β”‚   β”‚   └── js/
β”‚   β”‚       β”œβ”€β”€ api.js
β”‚   β”‚       β”œβ”€β”€ app.js
β”‚   β”‚       β”œβ”€β”€ auth.js
β”‚   β”‚       β”œβ”€β”€ theme.js
β”‚   β”‚       β”œβ”€β”€ components/
β”‚   β”‚       β”‚   β”œβ”€β”€ modal.js
β”‚   β”‚       β”‚   └── toast.js
β”‚   β”‚       └── pages/              # overview/sessions/chatrooms/groups/webhooks/events/settings
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ logger.ts               # Pino logger
β”‚   β”‚   β”œβ”€β”€ redis.ts                # Redis client helpers
β”‚   β”‚   β”œβ”€β”€ response.ts             # API response helpers
β”‚   β”‚   └── runtime.ts              # Bun/Node runtime abstraction
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”œβ”€β”€ auth.ts                 # API authentication
β”‚   β”‚   β”œβ”€β”€ rateLimit.ts            # API rate limiting
β”‚   β”‚   └── sessionValidator.ts     # Session existence check
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ session.ts              # Session CRUD
β”‚   β”‚   β”œβ”€β”€ chat.ts                 # Chat operations
β”‚   β”‚   β”œβ”€β”€ group.ts                # Group management
β”‚   β”‚   β”œβ”€β”€ profile.ts              # Profile management
β”‚   β”‚   β”œβ”€β”€ media.ts                # Media handling
β”‚   β”‚   β”œβ”€β”€ story.ts                # Story broadcasting
β”‚   β”‚   └── status.ts               # Server health
β”‚   β”œβ”€β”€ schemas/
β”‚   β”‚   β”œβ”€β”€ chat.ts                 # Chat schemas
β”‚   β”‚   β”œβ”€β”€ group.ts                # Group schemas
β”‚   β”‚   └── session.ts              # Session schemas
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ broadcastQueue.ts       # Broadcast queue with delays
β”‚   β”‚   └── mediaCleanup.ts         # Media file cleanup
β”‚   β”‚   └── webhookLog.ts           # Webhook delivery log storage
β”‚   └── utils/
β”‚       β”œβ”€β”€ asyncSleep.ts           # Async sleep utilities
β”‚       β”œβ”€β”€ phone.ts                # Phone/JID formatting
β”‚       └── validation.ts           # Validation utilities
β”œβ”€β”€ .env.example
β”œβ”€β”€ biome.jsonc
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ docker-compose.node.yml
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ Dockerfile.node
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
└── README.md

βš™οΈ Configuration Reference (.env)

Variable Default Description
NODE_ENV development Environment (development / production)
HOST 0.0.0.0 Server host
PORT 3000 Server port
LOG_LEVEL info Log level (debug, info, warn, error)
AUTH_GLOBAL_TOKEN β€” Simple auth token
REDIS_ENABLED false Enable Redis integration
REDIS_URL redis://localhost:6379 Redis connection URL
REDIS_PASSWORD β€” Redis password
BAILEYS_LOG_LEVEL warn Baileys internal log level
MAX_RETRIES 5 Max reconnection attempts
RECONNECT_INTERVAL 5000 Reconnection delay (ms)
MAX_SESSIONS 50 Maximum concurrent WhatsApp sessions
WEBHOOK_URL β€” Default webhook URL
WEBHOOK_SIGNATURE_MODE off Webhook signature mode (off, optional, required)
WEBHOOK_ALLOW_GLOBAL_TOKEN_FALLBACK true Allow fallback to AUTH_GLOBAL_TOKEN for webhook secret/signature
WEBHOOK_ALLOWED_EVENTS ALL Comma-separated event filter
WEBHOOK_RETRY_MAX 3 Webhook delivery retry count
WEBHOOK_RETRY_INTERVAL 5000 Initial webhook retry delay (ms)
WEBHOOK_BACKOFF_FACTOR 3 Exponential backoff multiplier
BROADCAST_MIN_DELAY_MS 1500 Min delay between bulk messages
BROADCAST_MAX_DELAY_MS 3000 Max delay between bulk messages
BROADCAST_BATCH_SIZE 10 Messages per batch before pause
BROADCAST_BATCH_PAUSE_MS 5000 Pause between batches
MEDIA_INCLUDE_BASE64 false Include media in webhooks
MEDIA_CLEANUP_ENABLED true Auto-delete old media files
MEDIA_CLEANUP_INTERVAL_MS 3600000 Media cleanup interval (ms)
MEDIA_MAX_AGE_HOURS 24 Max age of media files
CORS_ORIGIN * CORS allowed origins
DASHBOARD_ENABLED true Enable internal UI dashboard
DASHBOARD_REGISTRATION_ENABLED false Allow account creation
DASHBOARD_REGISTRATION_REQUIRE_APPROVAL true Require admin approval before new user can login
DASHBOARD_PASSWORD_MIN_LENGTH 6 Minimum password length for dashboard users
DASHBOARD_JWT_SECRET change-this-to-a-random-secret JWT secret for dashboard auth
SIMULATE_TYPING_BEFORE_SEND true Auto-send "composing" presence before each message (default: true)
SIMULATE_TYPING_DELAY_MIN_MS 1500 Typing delay range in ms (random between min-max)
SIMULATE_TYPING_DELAY_MAX_MS 3000 Typing delay range in ms (random between min-max)
AUTO_READ_MESSAGES false Auto-mark incoming messages as read (default: false, like WA Web toggle)
AUTO_MARK_ONLINE true Auto-set presence to "available" when sending messages (default: true)

πŸ§ͺ Useful Scripts

Use these commands for validation and maintenance:

# Type-check only
npm run build-check

# Lint with error-level gate
npm run lint

# Full lint diagnostics
npm run lint:all

# Auto-format/fix source files
npm run format

API key helper:

# Bun runtime
bun run manage-api-keys create admin

# Node runtime
npm run manage-api-keys:node create admin

πŸ“ License

License: MIT

This project is licensed under the MIT License - see the LICENSE file for details.

About

WhatsApp REST API built with Hono + TypeScript and features Dual-Runtime Support (runs natively on Bun or Node.js). Includes a built-in Visual Dashboard for easy management.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors