Documentation
Embed Chatbot

Embed Chatbot into Your Website

Integrating a chatbot into your web application is straightforward; however, because the widget needs to know who is talking, you must first create an authenticated session for each user before they can interact with the bot.

In this tutorial you will walk through the exact steps required to embed the chatbot in your own site.
If you have ever integrated Stripe you will find the flow familiar: your backend generates a session, then your front-end redirects (or iframes) the user to the returned URL.


Step 1: Create a New Authorized Session

From your backend call the following API to obtain the session URL:

curl --location 'https://www.askyourdatabase.com/api/chatbot/v2/session' \
--header 'Authorization: Bearer ${API_KEY}' \
--header 'Content-Type: application/json' \
--data-raw '{
  "chatbotid": "${botid}",
  "name": "Sheldon",
  "email": "test@gmail.com"
}'

Where do I get chatbotid? When you are editing the bot in the dashboard, for the last part of the URL (…/chatbot/5da7b8cf3a372f5e6e6b64af9ae189c7), the 5da7b8cf3a372f5e6e6b64af9ae189c7 is the botid.

How do I supply credentials? Pass the API key in the Authorization header:
Authorization: Bearer ${API_KEY}
You can create a key on the API Key page.

Need to support multiple tenants that each have their own database?
Simply include an optional databaseConfig object in the same request body and the chatbot will connect to the right datastore for that user.
See the guide on Database Switching (Multiple Tenants) for the exact JSON shapes and best practices.

The endpoint returns a one-time OAuth-style callback URL:

{"url":"https://www.askyourdatabase.com/api/chatbot/auth/callback?code=abcdefg"}

Embed this URL in an <iframe> (or redirect if you prefer) and the chatbot UI will load automatically.


Step 2: Load the Chatbot

You can explore the full implementation in our official Next.js demo (opens in a new tab) repository.
Below is a minimal example.

Backend route (Next.js /api/ayd):

import { NextRequest, NextResponse } from "next/server";
 
export const revalidate = 0;
export const dynamic = "force-dynamic";
 
export async function POST(req: NextRequest) {
  const { url } = await fetch("https://www.askyourdatabase.com/api/chatbot/v2/session", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + process.env.AYD_API_KEY,
    },
    body: JSON.stringify({
      chatbotid: process.env.CHATBOT_ID,
      name: "Sheldon",
      email: "test@gmail.com",
      // ➜ (Optional) databaseConfig can be added here for tenant isolation.
    }),
  }).then((res) => res.json());
 
  return NextResponse.json({ url });
}

Front-end component:

"use client";
import { useEffect, useState } from "react";
 
export default function Home() {
  const [iframeUrl, setIframeUrl] = useState("");
 
  const fetchAydSession = () => {
    fetch("/api/ayd", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({}),
    })
      .then((res) => res.json())
      .then(({ url }) => {
        setIframeUrl(url);
      });
  };
 
  useEffect(() => {
    // Set initial iframe URL - this provides a default chatbot URL using the environment variable
    if (typeof window !== "undefined") {
      setIframeUrl(`https://www.askyourdatabase.com/chatbot/${process.env.CHATBOT_ID}`);
    }
 
    // Listen for messages from the iframe - this handles communication between the parent window and the embedded chatbot
    const handleMessage = (event: MessageEvent) => {
      if (event.data.type === 'LOGIN_SUCCESS') {
        // Login successful - update iframe URL with the authenticated session URL provided in the message
        setIframeUrl(event.data.url);
      } else if (event.data.type === 'LOGIN_REQUIRED') {
        // Login required - fetch a new authenticated session from our API endpoint
        fetchAydSession();
      }
    };
 
    if (typeof window !== "undefined") {
      window.addEventListener('message', handleMessage);
    }
 
    return () => {
      if (typeof window !== "undefined") {
        window.removeEventListener('message', handleMessage);
      }
    };
  }, []);
 
  return (
    <main>
      <iframe
        className="mx-auto"
        style={{ height: 640, width: 400 }}
        src={iframeUrl}
      />
    </main>
  );
}

Quick Start with the Demo Repository

Need something running in minutes?
Clone or click “Deploy to Vercel” on the repo
https://github.com/AskYourDatabase/nextjs-chatbot (opens in a new tab)
and you will have a live site where you can drop your chatbot (and dashboard) widgets with minimal configuration.

The flow above fetches a fresh session URL from your backend and embeds the resulting page inside an iframe—nothing more to it!