Why Next.js Chatbot Integration Is Unlike Any Other Framework
Next.js is the most popular React meta-framework in 2026, powering over 1.2 million production websites according to W3Techs usage statistics. Its dominance comes from a unique architecture that combines server-side rendering, static generation, streaming, and client-side hydration in a single framework. This architecture is transformative for performance and SEO -- but it creates specific challenges for third-party widget integration that do not exist in plain React, Vue, or Angular applications.
The core problem is this: chatbot widgets are inherently client-side. They require the browser DOM, the window object, and real-time WebSocket connections. But Next.js renders components on the server first, where none of these exist. If your chatbot code runs during server-side rendering, you get one of three outcomes: a build error, a hydration mismatch, or a runtime crash.
In the App Router paradigm introduced in Next.js 13 and now standard in Next.js 15 and 16, the challenge intensifies because components are Server Components by default. You must explicitly opt into client-side rendering with the 'use client' directive for any component that touches the chatbot. Getting this boundary wrong means either shipping unnecessary JavaScript to the client or breaking server-side rendering entirely.
This guide covers every pattern you need for a production-grade chatbot integration in Next.js with the App Router. You will learn: the correct component boundaries between server and client, using next/script with the afterInteractive strategy for optimal loading, avoiding hydration mismatches, route-conditional loading using middleware and layout composition, and measuring Core Web Vitals impact before and after integration.
The patterns apply to any chatbot platform (Conferbot, Intercom, Drift, Crisp, or a custom-built widget), but we use Conferbot's embed script for concrete examples since it exposes a clean API that maps well to Next.js patterns.
Whether you are adding a customer support chatbot to your SaaS product, a lead qualification bot to your marketing site, or a product assistant to your e-commerce store, these Next.js-specific patterns ensure your chatbot loads fast, renders correctly, and respects the framework's architectural boundaries.
Server Components vs Client Components: Drawing the Right Boundary
The App Router's most fundamental concept is the distinction between Server Components and Client Components. According to the Next.js Server Components documentation, Server Components render on the server, ship zero JavaScript to the client, and cannot use browser APIs, state, or effects. Client Components render on both server (for HTML) and client (for interactivity), and ship their JavaScript to the browser.
Chatbot widgets require the browser DOM, event listeners, and often WebSocket connections. This means all chatbot integration code must live in Client Components. The question is: how much of your component tree needs to be client-side?
The Wrong Approach: Making the Whole Layout a Client Component
// app/layout.tsx - WRONG
'use client' // This makes EVERYTHING client-side
import ChatWidget from '@/components/ChatWidget'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<ChatWidget />
</body>
</html>
)
}Adding 'use client' to the root layout forces every component in your application to be a Client Component. This defeats the purpose of the App Router entirely -- you lose server-side rendering benefits, ship more JavaScript, and harm Core Web Vitals.
The Correct Approach: Isolated Client Boundary
// app/layout.tsx - CORRECT (Server Component)
import ChatWidget from '@/components/ChatWidget'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<ChatWidget /> {/* Only this is client-side */}
</body>
</html>
)
}
// components/ChatWidget.tsx - Client Component
'use client'
import { useEffect, useState } from 'react'
export default function ChatWidget() {
const [isReady, setIsReady] = useState(false)
useEffect(() => {
// Safe: only runs in the browser
const script = document.createElement('script')
script.src = 'https://cdn.conferbot.com/dist/v1/widget.min.js'
script.async = true
script.onload = () => { window.ConferbotWidget('YOUR_BOT_ID', 'live_chat'); setIsReady(true) }
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [])
return null // Widget manages its own DOM
}In this pattern, the root layout remains a Server Component. The ChatWidget component has the 'use client' directive, creating a client boundary that applies only to itself and its children. The rest of your page continues to benefit from server-side rendering and zero-JavaScript delivery.
Component Boundary Architecture
| Component | Type | Reason |
|---|---|---|
| RootLayout | Server | No client-side logic needed; HTML structure only |
| Page content | Server | Static or dynamic content rendered on server |
| Header/Nav | Server (mostly) | Only interactive elements need client boundary |
| ChatWidget | Client | Requires DOM access, useEffect, useState |
| ChatTriggerButton | Client | Requires onClick handler and state |
| UnreadBadge | Client | Requires reactive state from chat SDK |
Keep the client boundary as tight as possible. The chatbot widget and its trigger button need to be Client Components. Everything else -- your layout, page content, navigation, footer -- can remain Server Components. This is the principle of composition patterns that Next.js recommends for mixing server and client code. The tighter your client boundary, the less JavaScript your users download, and the faster your pages load.
next/script: The Right Loading Strategy for Chatbot Widgets
Next.js provides the next/script component as a first-class abstraction for loading third-party scripts with specific loading strategies. For chatbot widgets, this is the most important optimization tool in your arsenal. Using next/script instead of raw <script> tags or useEffect-based loading gives you framework-level control over when and how the widget loads.
Understanding the Three Loading Strategies
According to the next/script API documentation, there are three loading strategies:
| Strategy | When It Loads | Impact on Page Load | Use Case |
|---|---|---|---|
beforeInteractive | Before any page hydration | Blocks rendering (highest impact) | Critical scripts (polyfills, consent managers) |
afterInteractive | After page becomes interactive | Minimal impact on LCP, slight INP impact | Analytics, chatbots, non-critical widgets |
lazyOnload | During browser idle time | Zero impact on all metrics | Low-priority tracking, social widgets |
For chatbot widgets, afterInteractive is the optimal strategy. It loads the widget immediately after the page becomes interactive, meaning users can start chatting within seconds of page load without any impact on Largest Contentful Paint.
Implementation with next/script
The widget script defines one global, window.ConferbotWidget. You start the bot by calling it with your bot ID and an embed type once the script has loaded. That is the whole public API, plus ConferbotWidget.track() for website events (covered below).
// components/ChatWidget.tsx
'use client'
import Script from 'next/script'
const BOT_ID = process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID!
export default function ChatWidget() {
return (
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="afterInteractive"
onLoad={() => {
// embed type: 'live_chat' (corner bubble), 'popup_chat' or 'fullpage_chat'
window.ConferbotWidget(BOT_ID, 'live_chat')
}}
onError={() => console.error('Chatbot widget failed to load')}
/>
)
}If you would rather paste exactly what the dashboard gives you, open Chatbots > ⋯ > Install on your site, pick Next.js and copy the snippet. It wraps the same loader in next/script as an inline script:
<Script
id="conferbot-loader"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
(function (d, s, id) {
var js, el = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.async = true;
js.src = 'https://cdn.conferbot.com/dist/v1/widget.min.js';
js.id = id;
js.charset = 'UTF-8';
el.parentNode.insertBefore(js, el);
js.onload = function () {
var w = window.ConferbotWidget("YOUR_BOT_ID", "live_chat");
};
})(document, 'script', 'conferbot-js');
`
}}
/>Two details from the real snippet matter. The inline Script needs its own id (here conferbot-loader), and that id must not be conferbot-js: the loader uses conferbot-js to detect that the widget script is already on the page, so reusing it would make the loader skip itself. And a second ConferbotWidget() call does not mount a second bot; the widget returns the one already on the page, so a component that renders twice is harmless.
For TypeScript, declare the global once:
// types/conferbot.d.ts
declare global {
interface Window {
ConferbotWidget: ((
botId: string,
embed: 'live_chat' | 'popup_chat' | 'fullpage_chat',
options?: {
user?: { id?: string; name?: string; email?: string; [key: string]: unknown }
customData?: Record<string, unknown>
}
) => HTMLElement | null) & {
track: (name: string, props?: Record<string, unknown>) => boolean
}
}
}
export {}When to Use lazyOnload Instead
If no page needs the chatbot in the first seconds, lazyOnload defers the download to browser idle time. Use the same onLoad call; the widget does not read data-* attributes, so the bot ID always goes through ConferbotWidget():
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="lazyOnload"
onLoad={() => window.ConferbotWidget(BOT_ID, 'live_chat')}
/>The trade-off is that the chat bubble appears a little later. The widget has no programmatic open() method, so do not build your own "Chat with us" button that expects to open it; the bubble is the trigger. If you want chat behind a link instead of a bubble, give that link its own page that loads the bot with the fullpage_chat embed type.
Combining with Preconnect Headers
Whichever strategy you use, a preconnect hint lets the browser open the connection before the script is requested. The script comes from cdn.conferbot.com; once running, the widget talks to wdt.conferbot.com (API and live connection) and loads media from prd.media.cdn.conferbot.com. In the App Router you can add the hints straight to the root layout:
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<link rel="preconnect" href="https://cdn.conferbot.com" />
<link rel="preconnect" href="https://wdt.conferbot.com" />
</head>
<body>{children}</body>
</html>
)
}Or use the next/head equivalent in a Client Component. The preconnect hint resolves DNS and establishes TLS connections in advance, saving 100-300ms when afterInteractive or lazyOnload triggers the actual script download. This is the same optimization strategy recommended in our chatbot page speed guide.
Avoiding Hydration Mismatches: The Silent Chatbot Killer
Hydration mismatches occur when the HTML rendered on the server does not match the HTML generated during client-side hydration. When Next.js detects a mismatch, it either silently patches the DOM (degrading performance) or throws a visible error in development. Either outcome is undesirable for your chatbot integration and your application's stability.
Common Hydration Mismatch Causes in Chatbot Integrations
Cause 1: Accessing window during render
The most common mistake. If your component reads from window or document during the render phase (not inside useEffect), it will return undefined on the server and a real value on the client, causing a mismatch.
// BAD - causes hydration mismatch
'use client'
export default function ChatWidget() {
const isMobile = window.innerWidth < 768 // ERROR: runs during SSR
return isMobile ? <MobileChat /> : <DesktopChat />
}
// GOOD - deferred to client
'use client'
import { useState, useEffect } from 'react'
export default function ChatWidget() {
const [isMobile, setIsMobile] = useState(false)
useEffect(() => {
setIsMobile(window.innerWidth < 768)
const handler = () =>
setIsMobile(window.innerWidth < 768)
window.addEventListener('resize', handler)
return () =>
window.removeEventListener('resize', handler)
}, [])
return isMobile ? <MobileChat /> : <DesktopChat />
}Cause 2: Conditional rendering based on client state
If the chatbot's visibility depends on client-only state (like a cookie, localStorage value, or user agent), the server renders one version and the client renders another.
// BAD - localStorage not available on server
'use client'
export default function ChatWidget() {
const dismissed = localStorage.getItem('chat_dismissed')
if (dismissed) return null
return <ChatPanel />
}
// GOOD - use useEffect for client-only checks
'use client'
import { useState, useEffect } from 'react'
export default function ChatWidget() {
const [show, setShow] = useState(true) // server default
useEffect(() => {
const dismissed = localStorage.getItem('chat_dismissed')
if (dismissed) setShow(false)
}, [])
if (!show) return null
return <ChatPanel />
}Cause 3: Widget injecting DOM before hydration completes
If the chatbot script loads via a raw <script> tag in the <head> and immediately injects DOM elements, those elements exist in the client DOM but not in the server-rendered HTML. This causes a mismatch at the <body> level.
The fix is using next/script with afterInteractive strategy, which ensures the script loads after hydration completes. This is the primary reason we recommend next/script over manual script injection.
The Hydration-Safe Chat Component Pattern
The widget never renders anything React knows about: it adds its own element to document.body and draws inside a shadow root, so it cannot cause a mismatch by itself. Mismatches come from your code around it. This pattern keeps all of that on the client:
// components/ChatWidget.tsx
'use client'
import Script from 'next/script'
import { useEffect, useState } from 'react'
export default function ChatWidget() {
// false on the server and on the first client render, so both match
const [isMounted, setIsMounted] = useState(false)
useEffect(() => setIsMounted(true), [])
if (!isMounted) return null
return (
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="afterInteractive"
onLoad={() =>
window.ConferbotWidget(process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID!, 'live_chat', {
user: getUserFromCookies() ?? undefined,
})
}
/>
)
}
function getUserFromCookies() {
// Safe: only runs in the browser, after mount
try {
const data = document.cookie.split('; ').find(c => c.startsWith('user_data='))
return data ? JSON.parse(decodeURIComponent(data.split('=')[1])) : null
} catch {
return null
}
}The isMounted guard ensures the component renders null on the server and only starts loading the chatbot after hydration completes. This eliminates the entire class of hydration mismatch bugs. It is a well-established pattern recommended by the Next.js team and used extensively in production applications that integrate third-party widgets.
For a deeper understanding of how SSR interacts with chatbot widgets and the broader implications for page performance and SEO, see our dedicated guide on chatbot loading optimization.
Route-Conditional Loading: Show the Chatbot Only Where It Matters
Not every page needs a chatbot. Your admin dashboard, authentication pages, checkout confirmation, and internal tools do not benefit from a floating chat widget. Loading the widget on these pages wastes resources and can distract users from focused tasks.
Next.js App Router provides two powerful mechanisms for route-conditional loading: layout composition and middleware. Each has distinct advantages.
Method 1: Layout Composition (Recommended)
The App Router's nested layout system lets you add the chatbot widget to specific route segments without affecting others:
// app/(marketing)/layout.tsx
// Applied to /, /pricing, /features, /blog
import ChatWidget from '@/components/ChatWidget'
export default function MarketingLayout({
children
}: {
children: React.ReactNode
}) {
return (
<>
{children}
<ChatWidget />
</>
)
}
// app/(dashboard)/layout.tsx
// Applied to /dashboard, /dashboard/settings, etc.
// NO ChatWidget here
export default function DashboardLayout({
children
}: {
children: React.ReactNode
}) {
return <>{children}</>
}
// File structure:
// app/
// (marketing)/
// layout.tsx <-- includes ChatWidget
// page.tsx <-- home page
// pricing/page.tsx
// features/page.tsx
// (dashboard)/
// layout.tsx <-- no ChatWidget
// dashboard/page.tsx
// settings/page.tsxRoute groups (parenthesized folders like (marketing)) let you organize routes without affecting the URL structure. The chatbot loads only within the marketing layout. On a first visit to a dashboard route, the widget never loads. One caveat for client-side navigation: once the widget has started, it lives on document.body, outside React, so moving from a marketing page to the dashboard inside the app does not remove it. If that matters, add a small effect to the dashboard layout that removes the widget element; a later ConferbotWidget() call boots it again.
Method 2: Middleware-Based Control
For more dynamic control (for example, showing the chatbot based on user role, geographic location, or A/B test assignment), use Next.js middleware to set a response header or cookie that the client component reads:
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
const CHATBOT_PATHS = [
'/', '/pricing', '/features',
'/blog', '/contact', '/product'
]
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const response = NextResponse.next()
const showChat = CHATBOT_PATHS.some(p =>
pathname === p || pathname.startsWith(p + '/')
)
response.headers.set(
'x-show-chatbot',
showChat ? '1' : '0'
)
return response
}
export const config = {
matcher: ['/((?!api|_next|static|favicon).*)'],
}Read the header in a Client Component using the useHeaders pattern or pass it from a Server Component:
// app/layout.tsx (Server Component)
import { headers } from 'next/headers'
import ChatWidget from '@/components/ChatWidget'
export default async function RootLayout({
children
}: {
children: React.ReactNode
}) {
const headersList = await headers()
const showChat =
headersList.get('x-show-chatbot') === '1'
return (
<html>
<body>
{children}
{showChat && <ChatWidget />}
</body>
</html>
)
}Page-Specific Chat Context
You can tell the bot where the visitor started. Pass customData when you start the widget: it travels with the conversation, your team sees it beside the chat, and the greeting and playbook visibility rules you set in the dashboard can use it.
// components/ChatWidget.tsx
'use client'
import Script from 'next/script'
import { usePathname } from 'next/navigation'
const PAGE_CONTEXT: Record<string, string> = {
'/pricing': 'pricing',
'/features': 'features',
'/checkout': 'checkout',
}
export default function ChatWidget() {
const pathname = usePathname()
return (
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="afterInteractive"
onLoad={() =>
window.ConferbotWidget(process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID!, 'live_chat', {
customData: { landingPage: pathname, section: PAGE_CONTEXT[pathname] ?? 'other' },
})
}
/>
)
}customData is read when the widget starts, so it describes the page the visitor landed on. For what they do afterwards, send website events with ConferbotWidget.track(), which you can call at any point after the script has loaded:
'use client'
import { usePathname } from 'next/navigation'
import { useEffect } from 'react'
export function TrackRoute() {
const pathname = usePathname()
useEffect(() => {
window.ConferbotWidget?.track('page_view', { path: pathname })
}, [pathname])
return null
}Tracked events appear beside the visitor's chats, and a purchase or sign-up within a week of a chat is credited to that chat. Tracking is skipped for visitors whose browser sends Do Not Track. To change who the chatbot greets and when, use the targeting settings in the dashboard rather than code; that is what Conferbot's builder is for.
Core Web Vitals Impact: Measuring and Minimizing Performance Cost
Google uses Core Web Vitals (LCP, INP, CLS) as ranking signals. Any chatbot integration that degrades these metrics hurts your SEO. The good news: with proper implementation, a chatbot widget has near-zero impact on Core Web Vitals. The bad news: most implementations get it wrong.
Baseline Measurement Protocol
Before adding the chatbot, measure your baseline Core Web Vitals. After integration, compare. Use the web-vitals library for real-user monitoring:
// lib/vitals.ts
import { onLCP, onINP, onCLS, onFCP, onTTFB }
from 'web-vitals'
export function reportVitals() {
onLCP(metric => sendToAnalytics('LCP', metric))
onINP(metric => sendToAnalytics('INP', metric))
onCLS(metric => sendToAnalytics('CLS', metric))
onFCP(metric => sendToAnalytics('FCP', metric))
onTTFB(metric => sendToAnalytics('TTFB', metric))
}
function sendToAnalytics(
name: string, metric: any
) {
// Send to your analytics endpoint
fetch('/api/vitals', {
method: 'POST',
body: JSON.stringify({
name,
value: metric.value,
delta: metric.delta,
id: metric.id,
url: window.location.href,
timestamp: Date.now()
})
})
}Measured Impact by Loading Strategy
Here is how each loading strategy affects Core Web Vitals:
| Strategy | Effect on Core Web Vitals |
|---|---|
| Raw script in <head> | Blocks rendering; can delay LCP and add blocking time |
| next/script beforeInteractive | Loads before hydration; can delay LCP and interactivity |
| next/script afterInteractive | Loads after hydration; small effect, the usual choice |
| next/script lazyOnload | Loads in browser idle time; smallest effect, chat appears slightly later |
| afterInteractive + preconnect | As afterInteractive, with a faster connection to the chat server |
Measure your own pages with Lighthouse or PageSpeed Insights before and after adding the widget.
The data is clear: afterInteractive with preconnect hints delivers near-zero impact on all Core Web Vitals while keeping the chatbot available within 1-2 seconds of page load. The lazyOnload strategy has zero impact but adds 2-5 seconds before the chatbot is available.
Preventing Cumulative Layout Shift
CLS is the most common Core Web Vitals regression from chatbot widgets. It happens when the widget injects a floating button that shifts nearby content. To prevent this:
/* Reserve space for the chat trigger button */
.chat-trigger-container {
position: fixed;
bottom: 20px;
right: 20px;
width: 60px;
height: 60px;
z-index: 99999;
/* Fixed positioning does not affect layout */
}
/* If using an inline chat panel on specific pages */
.inline-chat-container {
min-height: 400px; /* Reserve space */
contain: layout; /* Prevent layout recalculation */
}Fixed-position elements (like floating chat buttons) do not contribute to CLS because they are removed from the document flow. The CLS risk comes from inline chat panels or banners that push content down. Use min-height and CSS contain to prevent this.
JavaScript Bundle Impact
Use Next.js's built-in bundle analyzer to verify your chatbot integration is not pulling unnecessary dependencies into the client bundle:
# Install and run the bundle analyzer
npx next build
NEXT_BUNDLE_ANALYZER=true npx next buildThe chatbot widget script loads separately from your Next.js bundle (it is a third-party script, not an npm dependency), so it should add zero bytes to your application's JavaScript bundles. If you see chatbot-related code in your client bundles, you have likely imported a client-side SDK as an npm package -- ensure it is dynamically imported with next/dynamic or import() to keep it out of the initial bundle.
For a comprehensive analysis of chatbot performance impact beyond Next.js, see our complete chatbot page speed and SEO guide.
Passing Authenticated User Context to the Chatbot
Personalized chatbot experiences require user identity. When a logged-in user opens the chat, the chatbot should know their name, email, subscription plan, and account history to provide relevant responses. In Next.js, this means bridging the gap between your server-side authentication system and the client-side chatbot widget.
Pattern 1: Server Component Props
If you use server-side sessions (NextAuth, Clerk, Auth0), read the session in a Server Component and pass user data to the Client Component as props:
// app/layout.tsx (Server Component)
import { getServerSession } from 'next-auth'
import ChatWidget from '@/components/ChatWidget'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const session = await getServerSession()
const chatUser = session?.user
? { id: session.user.id, name: session.user.name ?? undefined, email: session.user.email ?? undefined, plan: session.user.plan ?? 'free' }
: undefined
return (
<html>
<body>
{children}
<ChatWidget user={chatUser} />
</body>
</html>
)
}
// components/ChatWidget.tsx (Client Component)
'use client'
import Script from 'next/script'
type ChatUser = { id: string; name?: string; email?: string; plan?: string }
export default function ChatWidget({ user }: { user?: ChatUser }) {
return (
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="afterInteractive"
onLoad={() =>
window.ConferbotWidget(process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID!, 'live_chat', user ? { user } : undefined)
}
/>
)
}This pattern is clean because the user data flows through React's prop system. The server reads the session, picks the fields your team should see, and passes them as serializable props. Anything inside user beyond id, name and email (a plan, a company) is shown to your agents beside the chat.
Pattern 2: Logins That Happen Without a Reload
The widget reads user once, when it starts; there is no method to change identity on a running widget. So in an app where people sign in or out without a full page load, start the widget only after you know who the visitor is:
'use client'
import Script from 'next/script'
import { useSession } from 'next-auth/react'
export default function ChatWidget() {
const { data: session, status } = useSession()
if (status === 'loading') return null // wait until identity is known
const user = session?.user
? { id: session.user.id, name: session.user.name ?? undefined, email: session.user.email ?? undefined }
: undefined
return (
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="afterInteractive"
onLoad={() => window.ConferbotWidget(process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID!, 'live_chat', user ? { user } : undefined)}
/>
)
}If an account switch happens mid-session, the simplest safe option is a full reload after sign-out (most auth libraries do this by default), so the next visitor never inherits the previous person's conversation.
Security Considerations
Never pass sensitive data (API keys, tokens, internal IDs) to the chatbot widget. The widget runs on the client, and any data you pass can be inspected via browser dev tools. Follow these rules:
- Pass only display-safe user data: name, email, plan name
- Use opaque user IDs rather than sequential database IDs
- Never pass session tokens or JWTs to the widget
- Use the chatbot platform's server-side API for sensitive operations (like fetching order history)
For comprehensive chatbot security guidance, including prompt injection prevention and data protection, see our chatbot security guide. The Conferbot integrations hub handles CRM and backend data sync securely through server-side webhooks rather than client-side data passing.
State Management: Zustand, Context, and Cross-Component Chat State
Most chat widgets tempt you to mirror their state in your app: an unread badge in the header, a custom open button, a message list in a sidebar. Conferbot's widget is deliberately self-contained, so it is worth knowing what you can and cannot reach from React before you design around it.
What the Widget Exposes
| You can | How |
|---|---|
| Start the bot, with identity and context | window.ConferbotWidget(botId, embed, { user, customData }) |
| Send website events (cart, purchase, sign-up) | window.ConferbotWidget.track(name, props) |
| Know the script has loaded | The onLoad callback of next/script |
There is no API for opening or closing the chat, reading messages, counting unread replies or listening to widget events. The bubble shows its own unread state, and conversations, history and handover live in the widget and in your Conferbot inbox, not in your React tree.
A Small Store Is Still Useful
What does belong in app state is whether the widget has loaded and the events you want to send, so any component can call track without checking globals. Zustand works well because stores are client-only by nature:
// stores/chatStore.ts
import { create } from 'zustand'
type ChatState = {
isReady: boolean
queued: [string, Record<string, unknown>?][]
setReady: () => void
track: (name: string, props?: Record<string, unknown>) => void
}
export const useChatStore = create<ChatState>((set, get) => ({
isReady: false,
queued: [],
setReady: () => {
get().queued.forEach(([n, p]) => window.ConferbotWidget.track(n, p))
set({ isReady: true, queued: [] })
},
track: (name, props) => {
if (get().isReady) window.ConferbotWidget.track(name, props)
else set(s => ({ queued: [...s.queued, [name, props]] }))
},
}))// components/ChatWidget.tsx
'use client'
import Script from 'next/script'
import { useChatStore } from '@/stores/chatStore'
export default function ChatWidget() {
const setReady = useChatStore(s => s.setReady)
return (
<Script
id="conferbot-js"
src="https://cdn.conferbot.com/dist/v1/widget.min.js"
strategy="afterInteractive"
onLoad={() => {
window.ConferbotWidget(process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID!, 'live_chat')
setReady()
}}
/>
)
}
// anywhere else
const track = useChatStore(s => s.track)
track('cart_updated', { value: 49, currency: 'GBP', items: 2 })The widget itself also buffers a handful of track calls made before it has fully started, so the queue above is a convenience, not a requirement. Events appear beside the visitor's chats in the inbox and feed conversion credit, which is where chatbot analytics comes from, rather than from a message stream in your app.
Testing, Edge Cases, and Production Deployment Checklist
Shipping a chatbot integration in Next.js requires testing scenarios that do not exist in client-only applications. SSR, streaming, edge runtime, and static export each introduce unique failure modes that must be verified before deployment.
Essential Test Scenarios
| Scenario | What to Test | Expected Behavior |
|---|---|---|
| Initial page load | Widget appears after page is interactive | No layout shift, no hydration errors |
| Client-side navigation | Navigate between pages with and without chatbot | Widget shows/hides based on route; no duplicates |
| Full page reload | Hard refresh on a chat-enabled page | Widget reinitializes correctly |
| JavaScript disabled | Load page with JS disabled | Noscript fallback visible (contact link) |
| Ad blocker active | Load page with uBlock Origin or similar | Page functions normally; chat degrades gracefully |
| Slow network | Throttle to 3G in DevTools | Page loads fast; chat appears after delay |
| Auth state change | Log in then log out while chat is open | User identity updates; no stale sessions |
| Back/forward navigation | Use browser back/forward buttons | Chat state persists; no widget duplication |
| Streaming SSR | Load page with React Suspense boundaries | Widget loads after streaming completes |
| Static export | Build with output: 'export' | Widget loads client-side; no SSR errors |
Playwright E2E Test Suite
One thing to know before writing these: the widget deliberately does not start in automated browsers. Playwright, Puppeteer and Selenium set navigator.webdriver, and the widget treats that (and crawler, Lighthouse and uptime-monitor user agents) as "not a visitor", so it opens no connection and draws nothing. That protects your conversation quota from bots, and it means an E2E test should assert that your page loads the script and calls the widget, not that a chat bubble appears:
// e2e/chatbot.spec.ts
import { test, expect } from '@playwright/test'
test.describe('Chatbot integration', () => {
test('loads the widget script on marketing pages', async ({ page }) => {
await page.goto('/')
await expect(page.locator('script#conferbot-js')).toHaveCount(1)
await page.waitForFunction(() => typeof window.ConferbotWidget === 'function')
})
test('does not load it on the dashboard', async ({ page }) => {
await page.goto('/dashboard')
await page.waitForTimeout(3000)
await expect(page.locator('script#conferbot-js')).toHaveCount(0)
})
test('starts the bot with the right ID and identity', async ({ page }) => {
// Spy on the call your component makes, before any page script runs
await page.addInitScript(() => {
(window as any).__chatCalls = []
let real: any
Object.defineProperty(window, 'ConferbotWidget', {
configurable: true,
get: () => (real ? (...args: any[]) => { (window as any).__chatCalls.push(args); return real(...args) } : undefined),
set: v => { real = v },
})
})
await page.goto('/')
await page.waitForFunction(() => (window as any).__chatCalls.length > 0)
const [[botId, embed]] = await page.evaluate(() => (window as any).__chatCalls)
expect(botId).toBe(process.env.NEXT_PUBLIC_CONFERBOT_BOT_ID)
expect(embed).toBe('live_chat')
})
test('no hydration errors in console', async ({ page }) => {
const errors: string[] = []
page.on('console', msg => {
if (msg.type() === 'error' && msg.text().includes('Hydration')) errors.push(msg.text())
})
await page.goto('/')
await page.waitForTimeout(3000)
expect(errors).toHaveLength(0)
})
})To see the widget itself, open the page in a normal browser window: the conferbot-widget element appears at the end of <body> once the bot has started.
Production Deployment Checklist
- Environment variables:
NEXT_PUBLIC_CONFERBOT_BOT_IDset in production environment (not hardcoded) - CSP headers:
cdn.conferbot.comin script-src,https://wdt.conferbot.comandwss://wdt.conferbot.comin connect-src,prd.media.cdn.conferbot.comin img-src and media-src - next/script strategy: Using
afterInteractiveorlazyOnload(neverbeforeInteractive) - Preconnect hints: Added for widget and API domains
- Hydration test: No console errors on any chat-enabled page
- Route testing: Chat visible only on intended routes
- Auth flow: User identity syncs on login/logout
- CLS measurement: Below 0.05 on all pages
- Ad blocker resilience: Page works normally when widget is blocked
- Noscript fallback: Contact link visible when JavaScript is disabled
- Bundle analysis: No chatbot code in initial client bundle
- Error monitoring: Sentry or similar configured to catch widget errors
With this checklist verified, your Next.js chatbot integration is production-ready. The combination of next/script optimization, hydration-safe rendering, route-conditional loading, and centralized state management gives you a chatbot that is fast, reliable, and fully integrated into the Next.js architecture.
For ongoing optimization, use the A/B testing guide to improve conversation flows, the analytics metrics guide to track performance, and the conversation design masterclass to refine your bot's messaging. And if you are using Vue.js alongside Next.js, see our companion Vue chatbot integration guide for framework-specific patterns.
Was this article helpful?
Build and deploy in 10 minutes. No coding needed.
How to Add a Chatbot to Next.js FAQ
Everything you need to know about chatbots for how to add a chatbot to next.js.
About the Author
The Conferbot team writes about building, deploying, and improving AI chatbots.
View all articles