In this tutorial, you'll build a production-ready WhatsApp AI agent using Next.js App Router and Zavu. The best part? You don't need to manage any external AI API keys - Zavu's AI Gateway gives you access to all top-tier AI models (GPT-4, Claude, Gemini, Mistral, and more) directly from your Zavu dashboard.
What We're Building
A Next.js application that:
- Receives incoming WhatsApp messages via Route Handlers
- Verifies webhook signatures for security
- Uses Zavu's managed AI agents for intelligent responses
- Leverages Next.js App Router and Server Actions
- Automatically maintains conversation context
Prerequisites
- Node.js 18+
- A Zavu account with API credentials
- Basic React and TypeScript knowledge
No external AI API keys required! Zavu's AI Gateway provides access to all major AI models through a single integration.
Installation
Create a new Next.js project or add to an existing one:
Choose your package manager:
Bun (recommended):
terminalbun install @zavudev/sdk
npm:
terminalnpm install @zavudev/sdk
pnpm:
terminalpnpm add @zavudev/sdk
Then create the project:
terminalnpx create-next-app@latest whatsapp-agent cd whatsapp-agent
When prompted, select:
- TypeScript: Yes
- ESLint: Yes
- App Router: Yes
- Src directory: Yes
- Import alias: @/*
Project Structure
whatsapp-agent/
├── src/
│ ├── app/
│ │ ├── api/
│ │ │ └── webhook/
│ │ │ └── route.ts
│ │ └── page.tsx
│ └── lib/
│ └── zavu.ts
├── .env.local
└── package.jsonEnvironment Configuration
Create a .env.local file in your project root:
terminalZAVUDEV_API_KEY=your_zavu_api_key ZAVU_WEBHOOK_SECRET=your_webhook_secret
That's it! No OpenAI, Anthropic, or other AI provider keys needed.
How Zavu AI Gateway Works
Zavu provides a unified AI Gateway that gives you access to all top-tier AI models without managing individual API keys:
- GPT-4o, GPT-4o-mini - OpenAI's latest models
- Claude 3.5 Sonnet, Claude 3 Opus - Anthropic's models
- Gemini Pro - Google's AI models
- Mistral Large - Mistral AI's models
You can configure which model to use directly in your Zavu dashboard.
Initialize the Zavu Client
Create src/lib/zavu.ts:
TypeScriptimport Zavudev from '@zavudev/sdk'; export const zavu = new Zavudev({ apiKey: process.env.ZAVUDEV_API_KEY, });
Create the Webhook Route Handler
Create src/app/api/webhook/route.ts:
TypeScriptimport { NextRequest, NextResponse } from 'next/server'; import crypto from 'crypto'; import { zavu } from '@/lib/zavu'; // X-Zavu-Signature: t=<seconds>,v2=<hex> (v1=<hex> on older webhooks). // v2 signs "<t>.<body>"; v1 signs the body alone. function verifyWebhookSignature(rawBody: string, header: string): boolean { const secret = process.env.ZAVU_WEBHOOK_SECRET; if (!header || !secret) return false; const parts: Record<string, string> = {}; for (const piece of header.split(',')) { const i = piece.indexOf('='); if (i > 0) parts[piece.slice(0, i)] = piece.slice(i + 1); } const timestamp = Number(parts.t); if (!Number.isFinite(timestamp)) return false; const age = Math.floor(Date.now() / 1000) - timestamp; if (age > 300 || age < -60) return false; const received = parts.v2 ?? parts.v1; if (!received) return false; const signedPayload = parts.v2 ?: rawBody; const expected = crypto.createHmac('sha256', secret).update(signedPayload).digest('hex'); if (expected.length !== received.length) return false; return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received)); } export async function POST(request: NextRequest) { try { const rawBody = await request.text(); const signature = request.headers.get('x-zavu-signature') || ''; if (!verifyWebhookSignature(rawBody, signature)) { console.error('Invalid webhook signature'); return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const payload = JSON.parse(rawBody); const eventType = payload.type; console.log(${timestamp}.${rawBody}Received webhook event:${eventType}); if (eventType === 'message.inbound') { const message = payload.data; console.log(Message from${message.from}: ${message.text}); } return NextResponse.json({ status: 'ok' }); } catch (error) { console.error('Webhook error:', error); return NextResponse.json( { error: 'Internal server error' }, { status: 500 } ); } }
Deploy and Configure
https://yourdomain.com/api/webhook - Enable events: message.inbound - Copy the webhook secret to your .env.local fileterminalnpm run build npm start
Testing Locally
For local testing, use ngrok:
terminalnpx ngrok http 3000
Copy the HTTPS URL and configure it in your Zavu webhook settings.
Create a Managed AI Agent
Option 1: Via Zavu Dashboard
Option 2: Via Server Actions
Create a server action at src/app/actions/agent.ts:
TypeScript'use server'; import { zavu } from '@/lib/zavu'; import { revalidatePath } from 'next/cache'; export async function createAgent(formData: FormData) { const senderId = formData.get('senderId') as string; const name = formData.get('name') as string; const systemPrompt = formData.get('systemPrompt') as string; await zavu.senders.agent.create(senderId, { name, provider: 'zavu', model: 'gpt-4o-mini', systemPrompt, contextWindowMessages: 10, includeContactMetadata: true }); // Agents are created disabled. Switch it on once it is configured. const response = await zavu.senders.agent.update(senderId, { enabled: true }); revalidatePath('/dashboard'); return response.agent; } export async function getAgentStats(senderId: string) { const response = await zavu.senders.agent.stats(senderId); return response; }
Knowledge Bases
Create a server action for knowledge bases at src/app/actions/knowledge-base.ts:
TypeScript'use server'; import { zavu } from '@/lib/zavu'; export async function createKnowledgeBase(formData: FormData) { const senderId = formData.get('senderId') as string; const name = formData.get('name') as string; const description = formData.get('description') as string; const response = await zavu.senders.agent.knowledgeBases.create(senderId, { name, description }); return response.knowledgeBase; } export async function addDocument(formData: FormData) { const senderId = formData.get('senderId') as string; const kbId = formData.get('kbId') as string; const title = formData.get('title') as string; const content = formData.get('content') as string; const response = await zavu.senders.agent.knowledgeBases.documents.create(kbId, { senderId, title, content }); return response.document; }
Custom Tools
Create a tool endpoint at src/app/api/tools/order-status/route.ts:
TypeScriptimport { NextRequest, NextResponse } from 'next/server'; import crypto from 'crypto'; // Tool calls are signed differently from message webhooks: // X-Zavu-Signature is the hex HMAC-SHA256 of the raw body, keyed with the tool's own secret. function verifyToolSignature(rawBody: string, signature: string): boolean { const secret = process.env.ZAVU_TOOL_WEBHOOK_SECRET; if (!signature || !secret) return false; const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex'); if (expected.length !== signature.length) return false; return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature)); } export async function POST(request: NextRequest) { try { const rawBody = await request.text(); if (!verifyToolSignature(rawBody, request.headers.get('x-zavu-signature') || '')) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // The body is { tool, arguments, context, timestamp } const body = JSON.parse(rawBody); const order_id = body.arguments?.order_id; const orderStatus = await getOrderFromDatabase(order_id); return NextResponse.json({ success: true, data: { order_id: order_id, status: orderStatus.status, estimated_delivery: orderStatus.delivery_date, tracking_url: orderStatus.tracking_url } }); } catch (error) { console.error('Tool error:', error); return NextResponse.json( { success: false, error: 'Internal server error' }, { status: 500 } ); } } async function getOrderFromDatabase(orderId: string) { return { status: 'shipped', delivery_date: '2024-01-20', tracking_url: 'https://tracker.example.com/ORD-12345' }; }
Create the tool via server action:
TypeScript// src/app/actions/tools.ts 'use server'; import { zavu } from '@/lib/zavu'; export async function createOrderStatusTool(formData: FormData) { const senderId = formData.get('senderId') as string; const webhookUrl =; const response = await zavu.senders.agent.tools.create(senderId, { name: 'get_order_status', description: 'Get the current status of a customer order', webhookUrl, parameters: { type: 'object', properties: { order_id: { type: 'string', description: 'The order ID to look up' } }, required: ['order_id'] } }); // The signing secret is returned only on create. Store it as ZAVU_TOOL_WEBHOOK_SECRET. console.log('Tool webhook secret:', response.tool.webhookSecret); return response.tool; }https://${process.env.VERCEL_URL || 'localhost:3000'}/api/tools/order-status
Using Your Own AI Credentials (Optional)
If you prefer to use your own AI provider credentials, set them on the agent itself: when creating it, pass provider: "openai" (or "anthropic", "google", "mistral") together with apiKey, your key for that provider, instead of provider: "zavu". You can also pick the provider and enter the key on the sender's Agent tab in the dashboard.
This gives you full control over billing while still benefiting from Zavu's unified API.
Next Steps
- Explore the AI Agents dashboard to monitor conversations
- Add knowledge bases for domain-specific responses
- Create custom tools to integrate with your backend systems
- Build conversation flows for specific use cases
- Add a dashboard UI to manage your agents
Check out the Zavu documentation for more examples and advanced features.