Artificial Intelligence is transforming how businesses communicate with customers, and messaging platforms are at the center of this shift. Instead of manually answering repetitive questions, businesses can use AI assistants to provide instant responses, summarize conversations, translate messages, and automate customer support.
WhatsApp is one of the world’s most widely used messaging platforms, making it an ideal place to deploy an AI-powered assistant. By combining the WhatsApp Business Platform API with Google’s Gemini API, you can create a chatbot capable of understanding natural language and generating intelligent replies.
In this tutorial, you’ll build an AI WhatsApp Assistant using Node.js, Express, and the Gemini API. The bot will receive incoming WhatsApp messages through webhooks, send them to Gemini for processing, and return AI-generated responses back to the user.
By the end of this guide, you’ll have a working foundation that you can extend with chat history, multilingual support, order tracking, FAQ automation, and human handoff.
What You’ll Build
- AI-powered WhatsApp chatbot
- Automatic replies using Gemini API
- Webhook-based message processing
- Node.js + Express backend
- Multi-language support
- Conversation context (basic)
- Secure API configuration
- Production-ready project structure
Project Architecture
WhatsApp User
↓
WhatsApp Business Platform
↓
Webhook (Express.js)
↓
Gemini API
↓
AI Response
↓
WhatsApp User
Whenever a user sends a message, the WhatsApp platform forwards it to your webhook. Your Express server extracts the message, sends it to Gemini, receives the AI-generated reply, and sends that reply back through the WhatsApp Business Platform.
Prerequisites
- Basic JavaScript knowledge
- Node.js installed
- Visual Studio Code
- A Google account
- A Gemini API key
- Access to the WhatsApp Business Platform
Get Your Gemini API Key
Gemini will generate all AI responses for the chatbot.
- Open Google AI Studio.
- Create a new project if necessary.
- Generate an API key.
- Copy the key and store it securely.
Avoid hardcoding the key in your source code. Later in this tutorial, you’ll store it in environment variables.
Set Up the WhatsApp Business Platform
Create or configure your WhatsApp Business Platform application and obtain the credentials required for development:
- Phone Number ID
- Access Token
- Webhook Verify Token (you choose this)
- Business Account ID
These values allow your server to verify webhook requests and send replies through the platform.
Create the Project Folder
Use the following structure:
ai-whatsapp-assistant/
│
├── server.js
├── package.json
├── .env
├── routes/
│ webhook.js
├── services/
│ gemini.js
├── public/
│ index.html
│ style.css
└── README.md
Keeping routing logic and AI integration in separate folders makes the application easier to maintain.
Initialize the Project
Open your terminal and run:
mkdir ai-whatsapp-assistant
cd ai-whatsapp-assistant
npm init -y
Install Required Packages
npm install express axios dotenv cors
These packages are used for:
- Express – Web server
- Axios – HTTP requests
- dotenv – Environment variables
- CORS – Cross-origin support (if needed)
Create the Express Server
Create server.js.
import express from "express";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(express.json());
app.get("/",(req,res)=>{
res.send("AI WhatsApp Assistant Running");
});
const PORT =
process.env.PORT || 3000;
app.listen(PORT,()=>{
console.log(
`Server running on ${PORT}`
);
});
Start the server:
node server.js
If everything is configured correctly, visiting http://localhost:3000 will display a confirmation message.
Create Environment Variables
Create a file named .env.
PORT=3000
GEMINI_API_KEY=YOUR_API_KEY
WHATSAPP_ACCESS_TOKEN=YOUR_ACCESS_TOKEN
PHONE_NUMBER_ID=YOUR_PHONE_NUMBER_ID
VERIFY_TOKEN=YOUR_VERIFY_TOKEN
Keeping credentials outside your source code makes your project safer and easier to manage across development and production environments.
Create the Webhook Route
Create routes/webhook.js.
import express from "express";
const router =
express.Router();
router.get("/",
(req,res)=>{
res.send(
"Webhook Ready"
);
});
export default router;
Register the route inside server.js.
import webhookRoutes
from "./routes/webhook.js";
app.use(
"/webhook",
webhookRoutes
);
Verify the Webhook
The WhatsApp Business Platform verifies your webhook before sending events. Add a verification endpoint:
router.get("/",(req,res)=>{
const mode =
req.query["hub.mode"];
const token =
req.query["hub.verify_token"];
const challenge =
req.query["hub.challenge"];
if(
mode==="subscribe" &&
token===process.env.VERIFY_TOKEN
){
return res.status(200)
.send(challenge);
}
res.sendStatus(403);
});
When the verification token matches, the platform receives the challenge value and confirms the webhook.
Create a Simple Dashboard (Optional)
Although the bot works through webhooks, you can create a small dashboard to monitor server status.
public/index.html
<!DOCTYPE html>
<html>
<head>
<title>
AI WhatsApp Assistant
</title>
</head>
<body>
<h1>
AI WhatsApp Assistant
</h1>
<p>
Server is running successfully.
</p>
</body>
</html>
Current Progress
At this stage, you have successfully:
- Created the Node.js project
- Installed required packages
- Built the Express server
- Configured environment variables
- Created the webhook route
- Added webhook verification
- Prepared the project structure for AI integration
Receive Incoming WhatsApp Messages
Now that your Express server and webhook are configured, it’s time to receive incoming WhatsApp messages. Whenever a user sends a message to your WhatsApp Business number, the platform delivers a webhook event to your server.
In this section, you’ll extract the user’s message, send it to the Gemini API, receive an AI-generated response, and send the reply back to WhatsApp automatically.
Update the Webhook Route
Open routes/webhook.js and add a POST endpoint to receive webhook events.
router.post("/", async (req, res) => {
try {
const body = req.body;
console.log(JSON.stringify(body, null, 2));
res.sendStatus(200);
}
catch(error){
console.error(error);
res.sendStatus(500);
}
});
This endpoint receives webhook events whenever a user sends a message.
Extract the User’s Message
The webhook payload contains information about the sender and the message. Extract the text and sender ID.
const message =
body.entry?.[0]
?.changes?.[0]
?.value?.messages?.[0];
if(!message){
return res.sendStatus(200);
}
const userMessage =
message.text.body;
const sender =
message.from;
The sender value uniquely identifies the WhatsApp user who sent the message.
Create the Gemini Service
Create a new file named services/gemini.js.
import axios from "axios";
import dotenv from "dotenv";
dotenv.config();
const API_URL =
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${process.env.GEMINI_API_KEY}`;
export async function askGemini(prompt){
try{
const response =
await axios.post(API_URL,{
contents:[
{
parts:[
{
text:prompt
}
]
}
]
});
return response.data
.candidates[0]
.content.parts[0]
.text;
}
catch(error){
console.error(error);
return "Sorry, I couldn't process your request right now.";
}
}
Import the Gemini Service
Inside routes/webhook.js:
import {
askGemini
}
from "../services/gemini.js";
Generate an AI Reply
After extracting the user’s message, send it to Gemini.
const aiReply =
await askGemini(
userMessage
);
Gemini will analyze the user’s message and return a conversational response.
Send a Reply Back to WhatsApp
Create a helper function that sends a message using the WhatsApp Business Platform API.
import axios from "axios";
async function sendMessage(
to,
message
){
await axios.post(
`https://graph.facebook.com/v23.0/${process.env.PHONE_NUMBER_ID}/messages`,
{
messaging_product:
"whatsapp",
to,
text:{
body:message
}
},
{
headers:{
Authorization:
`Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`,
"Content-Type":
"application/json"
}
}
);
}
Send the AI Response
After Gemini generates a response:
await sendMessage(
sender,
aiReply
);
The chatbot will automatically send the AI-generated reply back to the user.
Complete Webhook Flow
User sends message
↓
Webhook receives event
↓
Extract message
↓
Gemini API
↓
Generate response
↓
WhatsApp API
↓
Reply sent
Add Conversation Context
Basic conversation memory helps Gemini produce more relevant responses.
const conversations = {};
function getHistory(user){
if(!conversations[user]){
conversations[user]=[];
}
return conversations[user];
}
Store both the user’s message and the AI response.
const history =
getHistory(sender);
history.push({
role:"user",
text:userMessage
});
history.push({
role:"assistant",
text:aiReply
});
For production systems, store conversation history in a database such as Firestore instead of server memory.
Limit Conversation Size
Prevent memory usage from growing indefinitely.
if(history.length>20){
history.splice(
0,
history.length-20
);
}
Keeping only recent messages helps maintain context while reducing memory usage.
Handle Empty Messages
if(
!userMessage ||
userMessage.trim()===""
){
return res.sendStatus(200);
}
Improve Prompt Quality
Instead of forwarding only the user’s message, provide instructions to Gemini.
const prompt =
`You are a helpful WhatsApp assistant.
Answer politely and briefly.
User:
${userMessage}`;
Well-structured prompts often produce more consistent responses.
Log Incoming Requests
console.log(
"User:",
sender
);
console.log(
"Message:",
userMessage
);
console.log(
"AI:",
aiReply
);
Logging helps debug webhook issues during development.
Error Handling
try{
// Process request
}
catch(error){
console.error(error);
await sendMessage(
sender,
"Sorry, an unexpected error occurred."
);
}
Providing a friendly fallback message improves the user experience if something goes wrong.
Test Your Chatbot
After configuring your webhook and server:
- Start the Node.js server.
- Expose it using your preferred tunneling solution if running locally.
- Configure the webhook URL in your WhatsApp Business Platform settings.
- Send a message from your test WhatsApp account.
- Verify that the bot responds with an AI-generated reply.
Example Conversation
User:
Can you explain what Firebase is?
AI:
Firebase is Google's Backend-as-a-Service platform that provides authentication, databases, cloud storage, hosting, messaging, analytics, and other tools to help developers build and scale web and mobile applications.
Features Completed
- ✅ Receive WhatsApp messages
- ✅ Extract incoming text
- ✅ Connect to Gemini API
- ✅ Generate AI replies
- ✅ Send responses back to WhatsApp
- ✅ Maintain basic conversation context
- ✅ Logging
- ✅ Error handling
- ✅ End-to-end message flow
Deploy Your AI WhatsApp Assistant
Now that your chatbot can receive WhatsApp messages, process them with the Gemini API, and send intelligent replies, the next step is preparing it for real-world usage. This includes deploying the application, protecting sensitive credentials, storing conversations, and improving performance.
Protect Your API Keys
Never hardcode API keys or access tokens inside your JavaScript files or commit them to a public Git repository.
Store all sensitive values inside the .env file.
PORT=3000
GEMINI_API_KEY=YOUR_GEMINI_API_KEY
WHATSAPP_ACCESS_TOKEN=YOUR_ACCESS_TOKEN
PHONE_NUMBER_ID=YOUR_PHONE_NUMBER_ID
VERIFY_TOKEN=YOUR_VERIFY_TOKEN
Also remember to add the following line to your .gitignore file:
.env
This prevents your credentials from being uploaded to version control.
Deploy the Server
Your Express application can be hosted on a VPS or cloud platform. Regardless of the hosting provider, make sure you:
- Install Node.js
- Copy the project files
- Install dependencies with
npm install - Configure environment variables
- Start the server with a process manager such as PM2
Example:
npm install
npm install -g pm2
pm2 start server.js
pm2 save
Using a process manager helps restart your application automatically if it crashes or after a server reboot.
Configure HTTPS
The WhatsApp Business Platform requires secure HTTPS endpoints for webhooks. Ensure your server uses a valid SSL/TLS certificate and verify that your webhook URL is publicly accessible over HTTPS before registering it.
Store Conversations in Firestore
Instead of storing conversations in memory, use Firestore so chat history persists across server restarts.
Example document structure:
conversations
|
|--UserPhoneNumber
|
|--messages
|
|--message1
|--message2
|--message3
Example data:
{
user:"919876543210",
role:"user",
message:"Hello",
createdAt:Date.now()
}
Saving conversations also enables analytics, support history, and improved context for future interactions.
Add Voice Note Support
Many users prefer sending voice messages instead of typing. You can extend your assistant to:
- Download incoming voice notes
- Convert speech to text using a speech recognition service
- Send the transcription to Gemini
- Reply with AI-generated text
This creates a more natural conversational experience for users.
Support Image Messages
If your chosen Gemini model supports image understanding, you can build workflows such as:
- Identify products from photos
- Explain screenshots
- Extract information from receipts
- Summarize documents from images
- Answer questions about uploaded pictures
Create Custom AI Personalities
Different businesses require different communication styles. You can customize the system prompt for various use cases.
Example:
const systemPrompt =
`You are a customer support assistant.
Always reply politely.
Keep answers under 100 words.
If you don't know the answer,
recommend contacting human support.`;
A consistent system prompt helps maintain the desired tone across conversations.
Rate Limiting
Protect your application from abuse by limiting the number of requests a user can make within a certain time period.
- Limit requests per phone number.
- Reject duplicate requests.
- Apply cooldown periods for excessive usage.
- Log suspicious activity for review.
Performance Optimization
- Cache frequently requested answers.
- Trim unnecessary conversation history.
- Reuse HTTP connections where possible.
- Validate input before sending it to Gemini.
- Compress responses if your infrastructure supports it.
- Monitor server memory and CPU usage.
Useful Business Features
You can evolve the assistant beyond simple Q&A by adding:
- Order status lookup
- Appointment scheduling
- Lead qualification
- Customer feedback collection
- FAQ automation
- Product recommendations
- Multi-language customer support
- Escalation to a human agent
Production Checklist
| Task | Status |
|---|---|
| Webhook Verification | ✅ |
| Environment Variables | ✅ |
| HTTPS Enabled | ✅ |
| Conversation Storage | ✅ |
| Error Handling | ✅ |
| Logging | ✅ |
| Rate Limiting | ✅ |
| Deployment | ✅ |
| Security Review | ✅ |
Frequently Asked Questions
Can I use this chatbot for customer support?
Yes. Many businesses use AI assistants to answer common questions, provide product information, and route complex issues to human agents.
Can I store conversation history?
Yes. Firestore, PostgreSQL, or another database can be used to save messages, enabling persistent chat history and analytics.
Can the chatbot understand multiple languages?
Yes. Gemini supports many languages, allowing the assistant to communicate with users from different regions.
Can I connect it to other systems?
Yes. You can integrate CRM platforms, inventory systems, payment gateways, scheduling tools, or other business applications through your backend.
Future Improvements
- Voice conversations
- Image understanding
- Document summarization
- AI-powered product recommendations
- Customer sentiment analysis
- Multi-agent workflows
- Admin dashboard with analytics
- Live agent handoff
Final Verdict
Building an AI WhatsApp Assistant with the Gemini API is a practical way to combine conversational AI with one of the world’s most widely used messaging platforms. Throughout this tutorial, you’ve learned how to create a Node.js server, verify webhooks, process incoming messages, generate intelligent responses with Gemini, and send replies back through the WhatsApp Business Platform.
By securing your credentials, storing conversations, enabling HTTPS, and preparing your application for deployment, you’ve also laid the groundwork for a production-ready solution. From here, you can extend the assistant with voice support, image understanding, CRM integrations, analytics, and other advanced features to meet the needs of real-world users and businesses.
Conclusion: You now have a complete roadmap for building, securing, deploying, and scaling an AI-powered WhatsApp Assistant using Node.js and the Gemini API. This project provides a solid foundation for creating intelligent messaging applications for customer support, automation, and business communication.


