How to add an AI chatbot to React and Next.js
Updated · 3 min read
In a Next.js app, load the chatbot once from your root layout with next/script. In any other React app (Vite and the like), put the plain script tag in index.html just before </body>.
Before you start
- Build your assistant in the Chatty4All editor: pick a design, then teach it about your business.
- Under Go live → Websites it may run on, add your website's address. The assistant only loads on the sites listed there, so nobody can copy your code onto theirs.
- Publish it. The editor then shows your code with your own assistant id in place of
YOUR_BOT_ID.
Your code
This is the whole install. Copy yours from Go live in the editor: it's the same line with your id filled in.
// Next.js (app/layout.tsx) — or any React app with the plain <script> tag
import Script from "next/script";
<Script src="https://chatty4all.design/widget.js" data-bot="YOUR_BOT_ID" strategy="afterInteractive" />Add it to React and Next.js
- Add the component to your root layout so it loads on every page.
- Open or close it from your own buttons with window.Chatty.open() / .close().
Tips for React and Next.js
- Load it once, from the layout. A second copy on the same page is ignored, so there's nothing to gain from adding it per page.
- Any link to
#ask-ai, or any element with adata-chatty-openattribute, opens the chat. So a menu item can be your launcher. - The script loads after your page and never holds it up. If the assistant can't load, nothing shows on your page.
- If your app sets a Content-Security-Policy, add
https://chatty4all.designtoscript-srcandframe-src.
Showing the chat inside a page instead
For the Inline layout, render <div id="chatty-chat"></div> where the chat should appear and add data-inline data-target="#chatty-chat" to the script.
Check it worked
- Open your live site in a private window. The chat button should appear in the corner within a few seconds.
- If it says it isn't enabled for this site, add that exact domain under Go live → Websites it may run on.
- If nothing appears, check that you published the assistant and that the line is on the page (view the page source and search for
widget.js).
Would you rather let your AI coding assistant do it? See install the chatbot with Cursor, Claude, Lovable, v0 or Bolt.