Three ways to add AI chatbot script to your Next.js application using the Script component.
Visit example pages with integrated chatbot
Add the widget script to your root layout for global availability across all pages.
app/layout.tsx
import Script from 'next/script' export default function RootLayout({ children }) { return ( <html> <body> {children} <Script src="https://chat-widget.sensay.io/<chatbot-identifier>/embed-script.js" strategy="afterInteractive" /> </body> </html> ) }
Add the widget script to a specific layout for part of your application.
components/SensayScript.tsx
"use client"; import Script from "next/script"; import { useEffect, useId } from "react"; export default function SensayScript({ src }: { src: string }) { // Generate a unique ID for script so NextJS can run it on client side navigation. // NextJS Script component by default runs script only once based on the src value. const id = useId(); const url = new URL(src); url.searchParams.set("id", id); // Destroy the chatbot when the component unmounts. // Destroy chatbot elements as NextJS doesn't clean up the Script component on client side navigation. useEffect(() => { return () => { window.SensayChatbot?.destroy(); }; }, []); return <Script src={url.toString()} strategy="afterInteractive" />; }
app/products/layout.tsx
import SensayScript from "@/components/SensayScript"; export default function ProductsLayout({ children }) { return ( <div> {children} <SensayScript src="https://chat-widget.sensay.io/<chatbot-identifier>/embed-script.js" /> </div> ) }
Add the widget script to a specific page component for page-specific functionality.
components/SensayScript.tsx
"use client"; import Script from "next/script"; import { useEffect, useId } from "react"; export default function SensayScript({ src }: { src: string }) { // Generate a unique ID for script so NextJS can run it on client side navigation. // NextJS Script component by default runs script only once based on the src value. const id = useId(); const url = new URL(src); url.searchParams.set("id", id); // Destroy the chatbot when the component unmounts. // Destroy chatbot elements as NextJS doesn't clean up the Script component on client side navigation. useEffect(() => { return () => { window.SensayChatbot?.destroy(); }; }, []); return <Script src={url.toString()} strategy="afterInteractive" />; }
app/support/page.tsx
import SensayScript from "@/components/SensayScript"; export default function SupportPage() { return ( <div> <h1>Support Page</h1> <SensayScript src="https://chat-widget.sensay.io/<chatbot-identifier>/embed-script.js" /> </div> ) }