Think about how many customers message your business on WhatsApp each day. They ask about prices, orders, and delivery times. Answering every one of them by hand takes hours. A WhatsApp AI agent can do much of that work for you. It reads each message, thinks about it, and sends a helpful reply in seconds.
In this guide, we will build one with three tools. Next.js catches the messages. n8n runs the AI. WhatsApp sends the replies back to your customer. I will use simple words and short steps. You can follow along even if you have never built a bot before.
By the end, you will have a working agent, a way to test it, and a clear list of rules to keep it safe.
What Is a WhatsApp AI Agent?
An old chatbot works like a phone menu. “Press 1 for orders. Press 2 for prices.” If the customer types something strange, it gets lost.
An AI agent is different. It understands normal sentences. A customer can write, “Hi, is my order coming today?” and the agent knows what they mean. It can also remember the chat and use tools, like looking up an order in a sheet.
Before we build, let’s learn one word: webhook. A webhook is like a doorbell. When something happens in one app, that app rings the bell at your door. In our case, WhatsApp rings the bell every time a customer sends a message.
Here are the four parts we will connect:
• WhatsApp Cloud API. This is Meta’s official way to send and receive WhatsApp business messages.
• Next.js webhook. This is your front door. It checks that each message is real.
• n8n. This is a tool where you build workflows with blocks. It is the brain of our agent.
• An AI model. This lives inside n8n and writes the reply.
You may ask, “Why add Next.js? Can’t I connect WhatsApp straight to n8n?” You can, and many guides show that. It works fine for a quick demo. But a Next.js webhook in the middle gives you more control. You can check that messages are real, ignore junk, hide your n8n address, add limits, and use your own code or database later.
What You Need Before You Start
Here is a short list:
• A free Meta developer account
• Node.js 20 or newer, and a basic idea of the Next.js App Router
• An n8n account (the cloud version or your own server)
• An API key from an AI company, like OpenAI
• A code editor, like VS Code
• A Vercel account if you want to put the webhook online
Meta gives you a free test phone number, so you can try everything without a real business line. Real use costs money for messages and AI calls, so check the prices first.
Plan the Flow First: A Simple Rule from Numan Dev
Before you build anything, stop and plan. This saves a lot of time.
Software engineer Numan builds mobile apps and AI systems. On his site, he shares a simple rule: start with the product need, then pick the tech. That rule fits this project well. Do not ask, “What can this bot do?” Ask, “What do my customers need help with?”
For a small online store, the answer might be:
• Answer common questions about prices and delivery
• Check the status of an order
• Pass the chat to a real person when the bot is stuck
Next, write down the path of one message. Here is ours:
1. A customer sends a message on WhatsApp.
2. Meta sends that message to your Next.js webhook.
3. Next.js checks it is real and passes it to n8n.
4. n8n asks the AI model for a reply.
5. n8n sends the reply through the WhatsApp Cloud API.
6. The customer sees the answer.
Also decide what the agent must never do, like promising refunds. Writing these rules now is easier than fixing a bad reply later.
Step 1: Set Up the WhatsApp Cloud API
Let’s start on the Meta side.
1. Go to the Meta for Developers website and create an app. Choose the business type.
2. Add the WhatsApp product to your app.
3. Meta gives you a free test phone number. Add your own phone number to the list of people who can receive test messages.
4. Find your temporary access token and your phone number ID.
5. Open your app settings and find the app secret.
6. Make up a long random text for the verify token. You will use it in a minute.
Save these four things somewhere safe: the access token, the phone number ID, the app secret, and the verify token. The temporary token stops working after about a day. That is fine for testing. We will fix that when we go live.
Do not connect the webhook yet. We need to build it first.
Step 2: Build the Next.js Webhook
Create a new app, or use one you already have:
npx create-next-app@latest whatsapp-agent –typescript –app
cd whatsapp-agent
Make a file called .env.local and add these lines:
WHATSAPP_VERIFY_TOKEN=your-long-random-text
WHATSAPP_APP_SECRET=your-app-secret
N8N_WEBHOOK_URL=https://your-n8n.com/webhook/whatsapp-agent
N8N_SECRET=another-long-random-text
Now create the file app/api/whatsapp/route.ts and paste this in:
import crypto from “crypto”;
import { NextRequest, NextResponse } from “next/server”;
// 1. Meta calls this once to check your webhook
export async function GET(req: NextRequest) {
const p = req.nextUrl.searchParams;
if (
p.get(“hub.mode”) === “subscribe” &&
p.get(“hub.verify_token”) === process.env.WHATSAPP_VERIFY_TOKEN
) {
return new NextResponse(p.get(“hub.challenge”), { status: 200 });
}
return new NextResponse(“Forbidden”, { status: 403 });
}
// 2. Check the message really came from Meta
function isValid(raw: string, header: string | null) {
if (!header) return false;
const expected =
“sha256=” +
crypto
.createHmac(“sha256”, process.env.WHATSAPP_APP_SECRET!)
.update(raw)
.digest(“hex”);
const a = Buffer.from(header);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
// 3. Meta sends every new message here
export async function POST(req: NextRequest) {
const raw = await req.text();
if (!isValid(raw, req.headers.get(“x-hub-signature-256”))) {
return new NextResponse(“Invalid signature”, { status: 401 });
}
const body = JSON.parse(raw);
const message = body?.entry?.[0]?.changes?.[0]?.value?.messages?.[0];
// Ignore status updates and anything that is not text
if (!message || message.type !== “text”) {
return NextResponse.json({ ok: true });
}
await fetch(process.env.N8N_WEBHOOK_URL!, {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
“x-api-key”: process.env.N8N_SECRET!,
},
body: JSON.stringify({
from: message.from,
text: message.text.body,
messageId: message.id,
}),
});
return NextResponse.json({ ok: true });
}
Let’s walk through it. The file has three jobs.
The GET function answers Meta’s first check. Meta sends your verify token and a random “challenge” text. If the token matches, you send the challenge back as plain text. That proves the webhook is yours.
The isValid function checks the signature. Meta signs every message with your app secret. You make the same signature on your side. If the two match, the message is real. If not, you reject it.
The POST function handles real messages. It checks the signature, picks out the text message, and sends the short version to n8n. It also ignores “delivered” and “read” updates, which Meta sends to the same address.
One important detail: we read the body with req.text() first. The signature is based on the exact raw text. If you turn it into JSON first, the check will fail.
Now run npm run dev. Meta needs a public web address, so use a tunnel tool like ngrok to get one. Then go back to the Meta dashboard. Paste your address, ending in /api/whatsapp, and your verify token. Click Verify. After that, subscribe to the messages field. If the check passes, your GET function works.
Before we build the n8n part, here is the big picture of the whole flow.

Step 3: Build the n8n Workflow
Now open n8n and create a new workflow. You only need three main blocks.
Block 1: Webhook. This catches the message from Next.js. Set the method to POST and the path to whatsapp-agent. Turn on Header Auth, and use the same secret you put in N8N_SECRET. Set it to respond right away. Meta gets upset when a webhook is slow, so you want to say “got it” fast and do the thinking after.
Block 2: AI Agent. Add an AI Agent block and connect it to the Webhook. Then fix three things:
• Prompt. Choose to define it yourself, and use the customer’s text. In n8n, that is {{ $json.body.text }}.
• Chat model. Connect an OpenAI Chat Model block and add your API key.
• Memory. Connect a Simple Memory block. For the session key, use the phone number: {{ $json.body.from }}. This gives every customer their own chat history. Without it, the agent forgets what was said, or worse, mixes up two customers.
Block 3: HTTP Request. This sends the reply back through WhatsApp. Set the method to POST and the address to:
https://graph.facebook.com/v24.0/YOUR_PHONE_NUMBER_ID/messages
Meta changes its version number from time to time, so check the latest one in their docs. Add a header called Authorization with the value Bearer YOUR_ACCESS_TOKEN. Then set the body to JSON and use this expression:
={{ {
messaging_product: “whatsapp”,
to: $(‘Webhook’).item.json.body.from,
type: “text”,
text: { body: $json.output }
} }}
Here, $json.output is the answer from the AI Agent block. Writing the body this way keeps n8n from breaking when the reply has quotes or new lines.
One last thing. n8n gives you two web addresses for a webhook: a test one and a production one. The test address only works while you click “Listen for test event.” The production address works after you turn the workflow on. Use the test one now, and switch later.
Step 4: Teach Your Agent With a Good Prompt
The AI model is smart, but it knows nothing about your business. The prompt is where you teach it. In the AI Agent block, open the system message and write clear rules. Here is a simple example:
You are the WhatsApp helper for Green Basket, a small online grocery store.
Keep replies short and friendly. Use simple words.
You can answer questions about prices, delivery, and opening hours.
If you do not know something, say so and offer to connect a real person.
Never promise refunds or discounts.
Short prompts with clear rules work better than long, messy ones.
When you are ready for more, give the agent tools. In n8n, you can add a Google Sheets block so the agent can check your product list. You can also add an HTTP tool that calls an API in your own Next.js app, like /api/orders, to check an order. Start with one tool, and make sure it works before adding another.
Step 5: Test the Whole Flow
Now let’s try it. Turn on your Next.js app and your tunnel. In n8n, click “Listen for test event.” Then send a message from your phone to the test number, like “Do you deliver on Sunday?”
If everything works, you should see three things:
• Your Next.js terminal shows a request.
• n8n shows the message moving through each block.
• Your phone gets a reply.
If nothing happens, check these:
• Did you subscribe to the messages field in the Meta dashboard?
• Is your phone number on the allowed list for the test number?
• Is your tunnel address still the same? Free tunnels often change it.
• Did the temporary token expire?
Keep Your WhatsApp AI Agent Safe
A bot that talks to real customers needs rules. Please do not skip this part.
• Always check the signature. Without it, anyone can send fake messages to your webhook.
• Keep secrets in environment variables. Never put tokens in your code or in a public repo.
• Lock your n8n webhook. The header secret makes sure only your Next.js app can call it.
• Add rate limits. Stop one person from sending hundreds of messages and running up your AI bill.
• Limit what the agent can do. Start with read-only tools. For anything that moves money or changes data, ask a human first.
• Follow WhatsApp’s rules. Message people who asked to hear from you. Also know that you can reply freely only within 24 hours of the customer’s last message. After that, you need an approved template message.
• Offer a human option. If a customer is upset or the agent is unsure, hand the chat to a real person.
Go Live
When the test works, it is time to move to the real thing.
• Deploy your Next.js app to Vercel, and add your environment variables there.
• In the Meta dashboard, change the webhook address to your live Vercel address.
• In n8n, turn the workflow on and switch to the production webhook address. Update N8N_WEBHOOK_URL in Vercel.
• Replace the temporary token with a permanent one. In Meta’s business settings, you can make a system user and create a long-lasting token.
• Add your real business phone number. Meta may ask you to verify your business first.
Common Mistakes to Avoid
These problems come up again and again:
1. Turning the body into JSON before the signature check. This breaks the check every time.
2. Using the n8n test address in production. It stops working when you close the editor.
3. Forgetting to subscribe to the messages field. Verification passes, but no messages arrive.
4. Using an expired token. The temporary token only lasts a short time.
5. Slow replies to Meta. If your webhook takes too long, Meta may send the same message again. Keep n8n set to respond right away.
6. No session key in memory. The agent forgets the chat or mixes up customers.
Frequently Asked Questions
Do I need to know how to code?
A little helps. The Next.js part is one file. The n8n part is mostly clicking and connecting blocks.
Can I skip Next.js and use only n8n?
Yes, for a quick test. But a Next.js webhook gives you signature checks, limits, and room to add your own code later.
Can the agent reply in Urdu or other languages?
Most AI models can reply in many languages. Test it with real messages before you go live.
Final Thoughts
A WhatsApp AI agent sounds big, but the pieces are simple. Meta sends messages to a Next.js webhook. The webhook checks them and passes them to n8n. n8n asks the AI for an answer and sends it back through WhatsApp.
Start small. Build the flow with one question, like “What are your opening hours?” Make sure it works from start to finish. Then add memory, then a tool, then a human handoff.
Customers like fast answers, and your team likes fewer repeat questions. With a little setup, a WhatsApp AI agent can give you both.
