A production-ready, multi-tenant WhatsApp AI assistant built with Node.js, TypeScript, and OpenAI. Designed for scalability, this engine uses a queued messaging pipeline to handle high-volume traffic without timing out.
- Dynamic Multi-Tenancy: Automatically switches between business accounts using database-stored credentials (tokens/IDs).
- AI-Powered Conversations: Integrated with OpenAI's GPT-4o for intelligent, context-aware responses.
- Persistent Memory: Stores full chat history in PostgreSQL, allowing for coherent multi-turn conversations.
- Reliable Queuing (BullMQ/Redis): Offloads message processing to background workers to stay within Meta's strict 3-second webhook timeout.
- Advanced Security: Implements HMAC SHA256 signature verification for all incoming WhatsApp webhooks.
- Comprehensive Testing: Includes a unit testing suite powered by Vitest to ensure core logic reliability.
- Clean Architecture: Decoupled layers (Core, Infrastructure, Application, Interfaces) for maximum maintainability.
- Runtime: Node.js (v20+)
- Language: TypeScript
- Framework: Express.js
- Database: PostgreSQL (via Prisma ORM)
- Caching & Queues: Redis & BullMQ
- AI: OpenAI API
- Communication: WhatsApp Cloud API (Meta)
- Validation & Types: Envalid & Zod
- Testing: Vitest
src/
├── core/ # Business Logic & Entities (Types, Interfaces)
├── application/ # Use Cases (Messaging Pipeline Orchestration)
├── infrastructure/ # External Tools (WhatsApp, OpenAI, DB, Queue, Workers)
├── interfaces/ # Entry points (Controllers, Webhook Handlers)
├── config/ # Environment validation & global constants
└── shared/ # Utility functions & helpers
- Node.js (v20 or higher)
- PostgreSQL (Running instance)
- Redis (Running instance)
- Ngrok (For local webhook testing)
Create a .env file in the root directory and fill in your credentials:
PORT=3000
NODE_ENV=development
# WhatsApp Cloud API
WHATSAPP_PHONE_NUMBER_ID=your_phone_id
WHATSAPP_ACCESS_TOKEN=your_permanent_access_token
WHATSAPP_VERIFY_TOKEN=your_custom_verify_token
WHATSAPP_API_VERSION=v20.0
WHATSAPP_APP_SECRET=your_app_secret_from_meta
# OpenAI
OPENAI_API_KEY=your_openai_key
OPENAI_MODEL=gpt-4o
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# PostgreSQL
DATABASE_URL=postgresql://user:password@localhost:5432/whatsapp_botInitialize the database schema using Prisma:
npm run prisma:pushCreate your first business/tenant account in the database:
npm run seedRuns the server with nodemon and ts-node for real-time reloading:
npm run devCompiles TypeScript and runs the optimized JavaScript:
npm run build
npm startExecute the unit testing suite using Vitest:
npm test- Expose Localhost: Run
ngrok http 3000. - Meta Portal: Go to your App Dashboard > WhatsApp > Configuration.
- Callback URL:
https://your-ngrok-url.app/webhook - Verify Token: Must match your
WHATSAPP_VERIFY_TOKENin.env. - Webhooks Fields: Click Manage and subscribe to
messages.
- Webhook: Receives POST from Meta.
- Controller: Validates payload and pushes message to BullMQ (Redis).
- Queue: Immediately returns
200 OKto Meta (preventing timeouts). - Worker: Picks up the job and triggers the Messaging Pipeline.
- Repository: Fetches Tenant data and User chat history from PostgreSQL.
- AI Service: Sends history + new message to OpenAI.
- WhatsApp Service: Sends AI-generated response back to the user via Meta Graph API.
- Webhook Security: Verifies the
x-hub-signature-256header (HMAC SHA256) to ensure requests originate from Meta. - Idempotency: Message IDs are used as Job IDs in BullMQ to prevent duplicate processing.
- Fail-Fast: The app won't start if required environment variables are missing (via
envalid). - Retries: BullMQ is configured with exponential backoff for failed OpenAI/WhatsApp calls.
- Test-Aware Config: Environment validation is bypassed in test mode to allow for safe CI/CD execution.
ISC License - Feel free to use this for your own SaaS products!