Back to Blog
Integrations

How to Add an AI Chatbot to Next JS (Next.js)

Add a hosted AssistLoop support agent to a Next.js App Router or Pages Router site with next/script. This guide covers client boundaries, safe public configuration, production testing, troubleshooting, and the path from automated answers to human handoff.

11 min read
How to Add an AI Chatbot to Next JS (Next.js)

An ai chatbot can answer product and support questions inside your existing Next.js site without adding a streaming interface, model connection, or custom chat backend. This guide shows where to place the AssistLoop hosted widget in App Router and Pages Router projects, how to keep browser-only code out of server components, and how to test the support path before customers use it.

What you need before you start

You need three things:

  • An AssistLoop account with an AI agent.
  • A Next.js application and access to its project repository.
  • A support knowledge base that the agent is allowed to use.

The knowledge base can include website content, uploaded PDF, DOCX, or TXT files, pasted text, and exact Q&A pairs. Use training sources for your agent to control what it knows and how it answers. Exact Q&A pairs are useful when wording matters, such as a refund rule or a policy statement.

You also need the AssistLoop embed snippet from the agent setup or widget settings. The dashboard is the source of truth for the script URL, Agent ID, and configuration attributes. Do not copy a script URL from another tutorial or invent one from memory.

This guide adds a hosted support agent to an existing site. It does not build a custom model, streaming chat UI, or AI backend. If you need complete control over the conversation interface and model orchestration, you need a separate application design. For a support widget that your team can train, review, and hand off to a person, the hosted approach keeps the Next.js work small.

Step 1. Create and train the AssistLoop agent

Create the agent in AssistLoop, then add the content it needs to answer questions about your product, pricing, policies, and account workflows. Start with material that support already considers approved. A smaller source set is easier to review than a large folder of documents that nobody owns.

Use exact Q&A pairs for answers that should not be paraphrased. Examples include:

  • Refund and cancellation rules.
  • Eligibility requirements.
  • Legal or compliance wording.
  • Account instructions that must follow a fixed sequence.

Before publishing the widget, ask the agent real support questions and review the conversation logs. Remove unsupported promises. Correct source content that produces vague answers. If the agent cannot answer a question safely, that is a useful result during testing. You can add an approved source or route the request to a person.

Choose the support path before you embed the widget:

  • Answer from the approved knowledge base.
  • Capture a lead when sales needs to follow up.
  • Hand the conversation to a person.
  • Trigger an Agent Action when the request needs a system lookup or another operation.

That decision affects the widget’s greeting, suggested replies, and test cases. A question about a public setup step can receive an answer. A billing dispute should have a clear route to human support.

Step 2. Add the widget with next/script in the App Router

In an App Router project, keep the page and layout as Server Components where possible. Put the widget in a small client component because the hosted script runs in the browser.

Create a component such as components/AssistLoopWidget.tsx:

'use client'

import Script from 'next/script'

const scriptUrl = process.env.NEXT_PUBLIC_ASSISTLOOP_SCRIPT_URL
const agentId = process.env.NEXT_PUBLIC_ASSISTLOOP_AGENT_ID

export default function AssistLoopWidget() {
  if (!scriptUrl || !agentId) {
    return null
  }

  return (
    <Script
      src={scriptUrl}
      data-agent-id={agentId}
      strategy="afterInteractive"
    />
  )
}

The NEXT_PUBLIC_ names above are application configuration names, not AssistLoop credentials. Set them to the exact public script URL and Agent ID shown in your AssistLoop dashboard. If the dashboard snippet uses a different attribute or configuration shape, keep that exact shape when moving it into the component. Do not put an API key, shared secret, or private customer data in these values.

The important boundary is the component itself. The 'use client' directive lets the widget own browser-side script behavior while the rest of your layout can remain a React Server Component. Next.js documents this separation in its guide to Client Components.

Import the component in app/layout.tsx or in the site shell that wraps the pages where support should appear:

import AssistLoopWidget from '@/components/AssistLoopWidget'

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <html lang="en">
      <body>
        {children}
        <AssistLoopWidget />
      </body>
    </html>
  )
}

next/script is the right starting point for a hosted widget. It lets Next.js manage script loading instead of asking a component to inject a browser script with useEffect. Read the Next.js script-loading documentation when you need to adjust loading strategy or placement.

Mount the component in the root layout when customers should be able to ask for help across the product. Use a more specific layout when support belongs only on public marketing pages, the billing area, or another defined part of the site.

Step 3. Keep the integration safe in a Pages Router project

A Pages Router project does not have app/layout.tsx. Place the same client widget in the shared application shell, usually pages/_app.tsx, so it loads as pages change.

The widget component can stay the same:

// pages/_app.tsx
import type { AppProps } from 'next/app'
import AssistLoopWidget from '@/components/AssistLoopWidget'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <AssistLoopWidget />
    </>
  )
}

Keep this integration limited to public widget configuration. An Agent ID and a hosted script URL can be exposed to the browser when the dashboard requires them. API keys, shared secrets, private customer records, and server-only credentials cannot.

A client boundary is needed because the widget interacts with the browser. That does not mean the entire application must become client-rendered. Keep browser-only script behavior in the widget component and keep data access on the server.

Use next/script instead of starting with a useEffect that creates a script element. A manual effect can be appropriate for a library with unusual loading requirements, but it adds lifecycle and duplicate-load problems when Next.js already provides script handling.

Embedding a hosted support agent is different from calling a private API from a server route. The widget needs its public embed configuration. A private API call needs server-side authentication, request validation, and a separate route design. Do not move private credentials into the widget to make those two jobs look alike.

Step 4. Match the widget to your product

Set the brand color, logo, avatar, name, greeting, theme, and suggested replies so the support entry point feels like part of your product. Widget customization covers the settings that control the visitor-facing appearance.

Write a greeting that sets a boundary. Tell visitors what the agent can answer and when a person can take over. For example, a product site might say that the agent answers setup and plan questions, then offer human help for account-specific requests.

Add suggested replies for the first questions visitors actually ask. Billing, setup, account access, and order status are better starting points than generic prompts because they give the agent a defined job and give you clear conversations to review.

Keep the first version narrow. A short, approved knowledge base is easier to check than a large collection of unowned internal documents. Add another source when conversation logs show a repeated unanswered question, not because more documents feel safer.

Step 5. Test the widget in development and production

Open the site in a clean browser session. Confirm that the widget appears, that the browser console has no relevant error, and that the page has no hydration warning related to the widget component.

Run three conversations:

  1. Ask a question the knowledge base should answer.
  2. Ask a question the agent should decline or route elsewhere.
  3. Ask for help that should reach a person.

Compare each answer with the approved source content in the conversation logs. Check the first response time from the visitor’s point of view. An answer that appears eventually but leaves the visitor staring at an empty widget still needs investigation.

Test the deployed HTTPS domain, not only localhost. Confirm that:

  • The production environment contains the public script URL and Agent ID.
  • The deployed layout includes the client widget component.
  • Your content-security policy permits the dashboard-provided script and the widget’s required connections.
  • The widget appears after a fresh production build.
  • The widget behaves correctly on mobile.

Check authenticated pages separately. Decide whether the widget should appear there, and verify that route-level layouts do not mount it twice. If the widget should appear only on public pages, place it in that route group instead of the global shell.

Troubleshooting the Next.js embed

The widget does not appear. Inspect the deployed page and browser console. Confirm that the client widget component is mounted in the active layout and that the dashboard-provided Agent ID is present. Check the production script URL as well, since a missing public environment value can cause the component to return nothing.

The script causes a server or hydration error. Move the widget into a client component and keep browser-only behavior out of the Server Component. Use next/script instead of reading browser globals or creating the script during server rendering.

The widget works locally but not after deployment. Check the production environment values, deployed domain, HTTPS configuration, content-security policy rules, and whether the component is included in the production build. Local development can hide a missing production variable.

The agent gives weak or missing support information. Return to the training sources and add exact Q&A pairs for sensitive answers. Retest with the original customer wording. Do not solve a content problem by adding more frontend code.

Human support never receives the conversation. Confirm that the selected AssistLoop plan includes human handoff and test the path with a real conversation. With human handoff, your team can pick up the conversation history instead of asking the visitor to start over.

What to connect after the first successful install

Set a handoff rule for billing disputes, account-specific questions, and requests the agent cannot answer. The person taking over should receive the conversation history so the visitor does not have to repeat the problem.

Use lead capture when a prospective customer needs a reply from sales. Keep the request inside the conversation where possible, and ask only for the details the sales team will use.

Consider Agent Actions for work such as booking a meeting or checking order status through an API. Validate the action, its inputs, and its data access before exposing it to customers. A system lookup that returns the wrong account is a support incident, not a frontend bug.

Review conversation logs regularly. Repeated unanswered questions show where the knowledge base needs a new source or an exact Q&A pair. Weak answers that come from unclear source content should be fixed in training, not hidden with a new greeting.

When the support path is ready, create your AI agent and add the dashboard-provided widget configuration to your Next.js site. Start with one focused support journey, test it on the deployed domain, then expand from evidence in the conversations.

FAQ

How do you add an AI chatbot to a Next.js App Router app?

Create a small client component, load the AssistLoop dashboard-provided embed script with next/script, and mount that component in the App Router layout or site shell. The hosted widget handles the support conversation while your Next.js app provides the integration point.

Can you add a support chatbot to Next.js without building an AI backend?

Yes. AssistLoop provides a hosted support agent that you train on approved business content and embed as a website widget. Your app does not need to build the model connection, streaming interface, or chatbot backend for this setup.

Should a Next.js chatbot script use next/script or useEffect?

Use next/script as the first choice for the hosted widget and keep it inside a client component. This avoids putting browser-only script behavior in a Server Component and gives Next.js control over script loading.

What should you test after embedding an AI chatbot in Next.js?

Test an approved knowledge-base answer, a question the agent should decline, and a request that should reach a person. Repeat the checks on the deployed HTTPS domain, then review the conversation logs and mobile layout.

Hasen

Written by

Hasen