Skip to content

Backend Recipes

Mcdavid Obioha edited this page Dec 2, 2026 · 1 revision

Backend Recipes

Copy-paste servers for the features that need one.

The widget never talks to an AI provider and never holds an API key. You run a small server that does, and point the widget at it. Each recipe below takes about two minutes.

Why a proxy? Anything in the browser, including a key in headers, can be read in the network tab and copied. Keep the key on your server, and rate limit the endpoint.

Import the helpers from the adapters subpath so they stay out of your bundle unless you use them:

import { createOpenAICompatibleAI, createWebhookTransport } from 'whatsapp-chat-widget-react/adapters';

In the script-tag build, createOpenAICompatibleAI is on the global: WhatsAppChatWidget.createOpenAICompatibleAI({ ... }).


1. Next.js App Router proxy for Claude or OpenAI

One route that speaks the /v1/chat/completions format the widget sends, and forwards it to Anthropic or OpenAI. Set AI_PROVIDER=anthropic or openai and the matching key in .env.local.

// app/api/whatsapp-ai/route.ts
const ALLOWED_ORIGINS = ['https://yoursite.com', 'http://localhost:3000'];

// Simple in-memory rate limit: 10 requests per minute per IP. Use Upstash or Vercel KV for real traffic.
const hits = new Map<string, number[]>();
function limited(ip: string) {
  const now = Date.now();
  const recent = (hits.get(ip) ?? []).filter((t) => now - t < 60_000);
  recent.push(now);
  hits.set(ip, recent);
  return recent.length > 10;
}

function cors(origin: string | null) {
  const allowed = origin && ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
  return {
    'Access-Control-Allow-Origin': allowed,
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
    Vary: 'Origin',
  };
}

export async function OPTIONS(req: Request) {
  return new Response(null, { status: 204, headers: cors(req.headers.get('origin')) });
}

export async function POST(req: Request) {
  const headers = cors(req.headers.get('origin'));
  const ip = req.headers.get('x-forwarded-for')?.split(',')[0] ?? 'unknown';
  if (limited(ip)) return Response.json({ error: 'Too many requests' }, { status: 429, headers });

  const { messages, temperature } = await req.json();
  // Cap what a visitor can make you pay for.
  const trimmed = (messages ?? []).slice(0, 4).map((m: { role: string; content: string }) => ({
    role: m.role === 'system' ? 'system' : 'user',
    content: String(m.content).slice(0, 4000),
  }));

  if (process.env.AI_PROVIDER === 'anthropic') {
    const system = trimmed.filter((m: { role: string }) => m.role === 'system').map((m: { content: string }) => m.content).join('\n');
    const upstream = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-api-key': process.env.ANTHROPIC_API_KEY!,
        'anthropic-version': '2023-06-01',
      },
      body: JSON.stringify({
        model: process.env.ANTHROPIC_MODEL ?? 'claude-haiku-5-5',
        max_tokens: 500,
        temperature,
        system,
        messages: trimmed.filter((m: { role: string }) => m.role === 'user'),
      }),
    });
    if (!upstream.ok) return Response.json({ error: 'AI request failed' }, { status: 502, headers });
    const data = await upstream.json();
    // Translate Anthropic's reply into the OpenAI shape the widget reads.
    const text = data.content?.map((part: { text?: string }) => part.text ?? '').join('') ?? '';
    return Response.json({ choices: [{ message: { role: 'assistant', content: text } }] }, { headers });
  }

  const upstream = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
    body: JSON.stringify({ model: process.env.OPENAI_MODEL ?? 'gpt-4.1-mini', max_tokens: 500, temperature, messages: trimmed }),
  });
  if (!upstream.ok) return Response.json({ error: 'AI request failed' }, { status: 502, headers });
  return Response.json(await upstream.json(), { headers });
}

Use it in your page. The model here is only a label; the route picks the real model:

import { WhatsAppChat } from 'whatsapp-chat-widget-react';
import { createOpenAICompatibleAI } from 'whatsapp-chat-widget-react/adapters';

const ai = createOpenAICompatibleAI({
  endpoint: '/api/whatsapp-ai',
  model: 'default',
  enableRouting: true,
  systemPrompt: 'We run a furniture studio in Lagos. Open Mon to Sat, 9am to 5pm. Delivery takes 3 to 5 days.',
});

<WhatsAppChat agents={agents} ai={ai} />

Tips

  • CORS: keep ALLOWED_ORIGINS to your own domains. A same-origin endpoint such as /api/whatsapp-ai needs no CORS at all.
  • Rate limits: the in-memory map resets on every cold start and does not share across instances. Use Upstash Ratelimit, Vercel KV, or your platform's rate limiting for real traffic.
  • Cost: the route caps messages and tokens. Choose a small, cheap model; polishing a sentence does not need a large one.
  • Instant replies: put the facts you want answered (hours, prices, policies) in systemPrompt. The model is told to answer only from it, and to leave instantReply empty otherwise.
  • Abuse: add a Turnstile or reCAPTCHA check before calling the provider if the endpoint is public.

2. Cloudflare Worker proxy for static HTML sites

For plain HTML, WordPress, Webflow or Shopify, using the <script> build. Deploy with wrangler deploy, then add the secret with wrangler secret put OPENAI_API_KEY (or ANTHROPIC_API_KEY).

// worker.ts
interface Env {
  OPENAI_API_KEY?: string;
  ANTHROPIC_API_KEY?: string;
  RATE_LIMITER?: { limit(options: { key: string }): Promise<{ success: boolean }> }; // optional Workers Rate Limiting binding
}

const ALLOWED_ORIGINS = ['https://yoursite.com'];

function cors(origin: string | null) {
  return {
    'Access-Control-Allow-Origin': origin && ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0],
    'Access-Control-Allow-Methods': 'POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
    Vary: 'Origin',
  };
}

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const headers = cors(req.headers.get('origin'));
    if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers });
    if (req.method !== 'POST') return new Response('Method not allowed', { status: 405, headers });

    const ip = req.headers.get('cf-connecting-ip') ?? 'unknown';
    if (env.RATE_LIMITER && !(await env.RATE_LIMITER.limit({ key: ip })).success) {
      return Response.json({ error: 'Too many requests' }, { status: 429, headers });
    }

    const { messages, temperature } = (await req.json()) as { messages?: { role: string; content: string }[]; temperature?: number };
    const trimmed = (messages ?? []).slice(0, 4).map((m) => ({
      role: m.role === 'system' ? 'system' : 'user',
      content: String(m.content).slice(0, 4000),
    }));

    if (env.ANTHROPIC_API_KEY) {
      const upstream = await fetch('https://api.anthropic.com/v1/messages', {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'x-api-key': env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01' },
        body: JSON.stringify({
          model: 'claude-haiku-5-5',
          max_tokens: 500,
          temperature,
          system: trimmed.filter((m) => m.role === 'system').map((m) => m.content).join('\n'),
          messages: trimmed.filter((m) => m.role === 'user'),
        }),
      });
      if (!upstream.ok) return Response.json({ error: 'AI request failed' }, { status: 502, headers });
      const data = (await upstream.json()) as { content?: { text?: string }[] };
      const text = (data.content ?? []).map((p) => p.text ?? '').join('');
      return Response.json({ choices: [{ message: { role: 'assistant', content: text } }] }, { headers });
    }

    const upstream = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: { 'content-type': 'application/json', authorization: `Bearer ${env.OPENAI_API_KEY}` },
      body: JSON.stringify({ model: 'gpt-4.1-mini', max_tokens: 500, temperature, messages: trimmed }),
    });
    if (!upstream.ok) return Response.json({ error: 'AI request failed' }, { status: 502, headers });
    return Response.json(await upstream.json(), { headers });
  },
};

Use it from the script tag. Pin the version and use SRI in production (see the README):

<script src="https://cdn.jsdelivr.net/npm/whatsapp-chat-widget-react@0.8.0/dist/standalone.global.js"></script>
<script>
  WhatsAppChatWidget.init({
    phoneNumber: '+2348012345678',
    ai: WhatsAppChatWidget.createOpenAICompatibleAI({
      endpoint: 'https://whatsapp-ai.yourname.workers.dev',
      model: 'default',
      enableRouting: false,
    }),
  });
</script>

Already running an AI gateway? Cloudflare AI Gateway, LiteLLM, OpenRouter, Groq and Ollama all speak /v1/chat/completions, so createOpenAICompatibleAI can point at your own server in front of them without the translation code above. Never point it straight at a provider from the browser.


3. n8n and the WhatsApp Cloud API: lead webhooks and live chat

Lead webhook (webhookUrl)

Every submission is sent to your webhook even if the visitor closes WhatsApp before sending, using navigator.sendBeacon.

  1. In n8n, add a Webhook node: method POST, path whatsapp-lead, response Immediately. Copy the production URL.
  2. Set it on the widget: webhookUrl="https://n8n.example.com/webhook/whatsapp-lead".
  3. The JSON body is:
{
  "name": "Ada", "subject": "Pricing", "message": "Hello",
  "selectedAgent": { "id": "sales", "name": "Sales" },
  "pageContext": { "title": "Pricing", "url": "https://site.com/pricing" },
  "utm": { "utm_source": "ads" },
  "timestamp": 1790000000000
}
  1. Connect the node to Slack, HubSpot, Google Sheets or an email. In Make and Zapier use a Custom Webhook / Catch Hook trigger the same way.

sendBeacon sends Content-Type: application/json from another origin, so the webhook must answer the CORS preflight. n8n, Make and Zapier hooks do. If you use your own endpoint, allow POST and the Content-Type header for your site's origin.

Live chat (createWebhookTransport)

import { createWebhookTransport } from 'whatsapp-chat-widget-react/adapters';

// Create once, outside the component.
const transport = createWebhookTransport({
  sendUrl: 'https://n8n.example.com/webhook/chat-send',
  pollUrl: 'https://n8n.example.com/webhook/chat-replies',
  pollIntervalMs: 3000,
});

<WhatsAppChat phoneNumber="+2348012345678" transport={transport} widgetId="support" />

Workflow A: visitor to WhatsApp. Webhook node at chat-send (respond immediately with { "messageId": "<id>" }), then a WhatsApp Business Cloud node (or an HTTP Request to POST https://graph.facebook.com/<version>/<PHONE_NUMBER_ID>/messages) that sends message to your agent's number. Put the sessionId in the text, for example [a1b2] Ada: Hello, so the agent's reply can be matched.

Workflow B: WhatsApp to visitor. A WhatsApp Trigger node receives the agent's reply. Extract the session id from the quoted text, then store { id, text, timestamp, session } in an n8n Data Table (or Redis, Airtable, a Sheet).

Workflow C: replies endpoint. Webhook node at chat-replies (method GET) that reads the query session and since, looks up rows for that session with timestamp > since, and responds with a JSON array: [{ "id": "...", "text": "...", "timestamp": 1790000001000 }].

The widget polls every 3 seconds while the tab is visible, ignores duplicate ids, and shows delivery status per message. Polling is the simplest option; for lower latency, write your own WhatsAppTransportAdapter with a WebSocket or Server-Sent Events subscribe.

Checklist

  • Production webhook URLs, not test URLs.
  • CORS allowed for your site on all three endpoints.
  • Authorization header (via headers) only if your endpoints are behind your own proxy; the header is visible to visitors, so it is a rate limit tool, not a secret.
  • WhatsApp Cloud API only lets you send free-form messages inside the 24-hour customer care window after the visitor's last message. Start with a template message for first contact.

Clone this wiki locally