Vercel Chat SDK

Build WhatsApp bots with Vercel Chat SDK

Use @wati-io/chat-sdk-adapter to connect a Chat SDK bot to your Wati WhatsApp number. Chat SDK is Vercel's open-source TypeScript library for chat bots. You write your bot's logic once, and the Wati adapter handles receiving WhatsApp messages through Wati webhooks and replying through the Wati API.

With the adapter, your bot can:

  • Reply to WhatsApp messages with formatted text, files and images
  • Send reply buttons and list menus, and handle the customer's choice
  • Receive photos, voice notes, documents, locations and reactions
  • Send approved templates to start a conversation or reach a customer after 24 hours
  • Show a typing indicator and read conversation history

The adapter is maintained by Wati and is open source under the MIT license.

Before you start

You need:

  • A Wati workspace with a connected WhatsApp number, on a plan that includes webhooks.
  • Your Wati API endpoint and an access token, from API Docs in the Wati dashboard
  • Node.js 20 or later, and somewhere to host the bot with a public HTTPS URL, such as Vercel
  • Optional: to show customers "typing…" while the bot works, turn on Settings → Team Inbox → General Settings → Show typing indicator to customers

Messages your team sends from the Wati Team Inbox, and messages from Wati chatbots, don't trigger the bot. If a Wati chatbot or auto-reply is active on the same number, customers may get replies from both, so pause it for conversations the bot handles.

Set up

1. Install

npm install @wati-io/chat-sdk-adapter chat @chat-adapter/state-redis

2. Create the bot

import { Chat } from "chat";
import { createRedisState } from "@chat-adapter/state-redis";
import { createWatiAdapter } from "@wati-io/chat-sdk-adapter";

export const bot = new Chat({
  userName: "support",
  state: createRedisState(),
  adapters: {
    wati: createWatiAdapter(),
  },
});

bot.onDirectMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});

WhatsApp conversations are one-to-one, so incoming messages arrive in onDirectMessage.

3. Add the webhook route

For a Next.js app:

import { after } from "next/server";
import { bot } from "@/lib/bot";

export async function POST(request: Request): Promise<Response> {
  return bot.webhooks.wati(request, {
    waitUntil: (task) => after(() => task),
  });
}

4. Set environment variables

VariableRequiredValue
WATI_API_ENDPOINTYesThe API endpoint from API Docs, for example https://live-mt-server.wati.io/123456. You can paste it as shown; the adapter removes the tenant ID.
WATI_ACCESS_TOKENYesYour access token, with or without Bearer .
WATI_WEBHOOK_SECRETYesA long random string you choose, for example the output of openssl rand -hex 32.
WATI_CHANNEL_PHONE_NUMBERNoYour WhatsApp number, digits only. Needed if your workspace has more than one number.
REDIS_URLFor serverless hostingRedis connection URL. On Vercel, add Redis from the Storage tab.

5. Register the webhook in Wati

  1. Deploy the bot so it has a public HTTPS URL.

  2. In Wati, open Webhooks and add a webhook with this URL, using your WATI_WEBHOOK_SECRET as the token:

    https://your-app.com/api/webhooks/wati?token=YOUR_WATI_WEBHOOK_SECRET
  3. Subscribe to Message Received, and make sure the webhook is enabled.

The adapter rejects any request without the correct token, so only Wati can trigger your bot. Keep the full webhook URL private, since it contains the secret.

6. Test it

Send a WhatsApp message to your Wati number. The bot should reply within a few seconds.

To test locally before deploying, run your app and expose it with a tunnel such as cloudflared tunnel --url http://localhost:3000 or ngrok http 3000, then register the tunnel URL as the webhook. The example app includes a status page that checks your settings and shows the webhook URL to register.

Buttons and menus

Send a card with buttons, then handle the customer's tap with onAction:

import { Actions, Button, Card, CardText } from "chat";

await thread.post(
  Card({
    title: "Order #1042",
    children: [
      CardText("Do you want to confirm your order?"),
      Actions([
        Button({ id: "confirm", label: "Confirm", value: "1042" }),
        Button({ id: "cancel", label: "Cancel", value: "1042" }),
      ]),
    ],
  }),
);

bot.onAction("confirm", async (event) => {
  await event.thread?.post(`Order ${event.value} confirmed.`);
});
You sendCustomer sees
1 to 3 buttonsWhatsApp reply buttons
4 to 10 buttonsA list menu
A Select with up to 10 optionsA list menu
Link buttonsThe links written out in the message

Button labels can be up to 20 characters and must be unique within a message. The adapter remembers which action each label belongs to in your Chat SDK state, so use Redis or another shared store when your bot runs on more than one server or on serverless hosting.

Templates

WhatsApp only lets you send free-form messages within 24 hours of the customer's last message. To start a conversation, or to reply after that window, send an approved template:

import type { WatiAdapter } from "@wati-io/chat-sdk-adapter";

const wati = bot.getAdapter("wati") as WatiAdapter;

const { threadId } = await wati.sendTemplate("+15551234567", {
  templateName: "order_update",
  parameters: [{ name: "name", value: "Ana" }],
});

await bot.thread(threadId).subscribe();

Use the parameter names shown in the Wati template editor, such as name, not WhatsApp's numbered placeholders like 1.

Files and media

Send a file with a caption:

await thread.post({
  markdown: "Here is your invoice.",
  files: [{ filename: "invoice.pdf", mimeType: "application/pdf", data: pdfBuffer }],
});

Photos, voice notes, documents and stickers your customers send arrive as attachments. Call attachment.fetchData() to download one.

Supported features

FeatureSupported
Send and receive text, with WhatsApp formattingYes
Reply buttons and list menusYes
Send files and imagesYes
Receive photos, voice notes, documents and locationsYes
Receive reactionsYes
Approved templatesYes
Typing indicatorYes, once turned on in Wati settings
Conversation historyYes
Edit or delete sent messagesNo, WhatsApp doesn't allow it
Send reactionsNot yet
Link (CTA URL) buttonsSent as plain links
Streaming responsesSent as one message when complete

Troubleshooting

ProblemWhat to check
The bot doesn't replyIn Webhooks, check the webhook is enabled, subscribed to Message Received, and points to your current URL. Check your server logs for requests to /api/webhooks/wati.
Requests to the webhook return 401The token in the webhook URL doesn't match WATI_WEBHOOK_SECRET.
API calls return 401Check the access token, and that WATI_API_ENDPOINT is for your workspace's region.
A button tap arrives as a normal messageThe bot couldn't find the button's action. Use Redis for state on serverless hosting, and give every button in a message a different label.
A template fails with "There are no valid Receivers"The template's parameter names don't match. Use the names from the Wati template editor.
Replies are slow or arrive out of orderWati usually delivers webhooks within a few seconds, but delivery can occasionally be slower.
The customer sees no typing indicatorTurn it on in Settings → Team Inbox → General Settings → Show typing indicator to customers, then restart or redeploy the bot. Until then the bot's replies are still sent, without the indicator.

Resources