How-to guide

How to add live chat to React and Next.js

A single-page app needs a little more care than a static site. The widget should load once, survive route changes, and know when a user signs in or out. This guide shows the working code for React, the Next.js App Router and the Pages Router, using the DChat widget. No npm package is needed.

Before you start

You need a running DChat server and its address. If you do not have one yet, follow the guide for Windows and IIS or Linux and Docker, or try it on your own machine first. The examples below use https://chat.example.com; replace it with your server. The site ID default is the one the Widget Builder uses unless you have created another widget site.

Copy your exact snippet from Widget Builder in the dashboard if you have set a colour, position or greeting. Each setting is a data- attribute, and you can carry them across in the same way as the two shown here.

React: load the script once

Create one small component. It adds the script to the page the first time it renders and does nothing after that.

import { useEffect } from 'react';

const CHAT_SERVER = 'https://chat.example.com';

export function ChatWidget() {
  useEffect(() => {
    if (document.getElementById('dchat-script')) return;

    const script = document.createElement('script');
    script.id = 'dchat-script';
    script.src = `${CHAT_SERVER}/widget/dchat.iife.js`;
    script.async = true;
    script.setAttribute('data-server-url', CHAT_SERVER);
    script.setAttribute('data-site-id', 'default');
    document.body.appendChild(script);
  }, []);

  return null;
}

The check on the script's id matters. React Strict Mode runs effects twice in development, and without the check the widget script would be added twice.

Render the component once, near the top of your app, outside your routes:

import { ChatWidget } from './ChatWidget';

export default function App() {
  return (
    <>
      <Routes />
      <ChatWidget />
    </>
  );
}

Do not remove the script in an effect cleanup. The widget attaches its own element to document.body, outside your React tree, so it stays on screen and keeps the conversation open while the visitor moves between routes.

Next.js App Router

Use the built-in next/script component in your root layout. The layout stays mounted across navigation, so the script loads once.

// app/layout.tsx
import Script from 'next/script';

const CHAT_SERVER = 'https://chat.example.com';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src={`${CHAT_SERVER}/widget/dchat.iife.js`}
          data-server-url={CHAT_SERVER}
          data-site-id="default"
          strategy="lazyOnload"
        />
      </body>
    </html>
  );
}

lazyOnload waits until the browser is idle, which keeps chat out of the way of your page's first render. If chat is the main purpose of a page, use afterInteractive instead.

Next.js Pages Router

Put the same component in pages/_app.tsx:

// pages/_app.tsx
import type { AppProps } from 'next/app';
import Script from 'next/script';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Script
        src="https://chat.example.com/widget/dchat.iife.js"
        data-server-url="https://chat.example.com"
        data-site-id="default"
        strategy="lazyOnload"
      />
    </>
  );
}

Add TypeScript types

The widget adds a global window.DChat object. It exists only after the script has loaded, so mark it optional. That makes TypeScript remind you to write window.DChat?.open().

// dchat.d.ts
export {};

declare global {
  interface Window {
    DChat?: {
      setUser(identifier: string, details?: Record<string, unknown>): void;
      setCustomAttributes(values: Record<string, unknown>): void;
      open(): void;
      close(): void;
      toggle(): void;
      reset(): void;
      on(event: 'ready' | 'open' | 'close' | 'message' | 'unread',
         callback: (payload?: unknown) => void): () => void;
    };
  }
}

Open chat from your own button

Any button or link in your app can open the chat window:

export function ContactButton() {
  return (
    <button type="button" onClick={() => window.DChat?.open()}>
      Chat with us
    </button>
  );
}

The same object offers close(), toggle() and on(). For example, DChat.on('unread', callback) gives you the unread count for a badge in your own navigation, and returns a function that stops listening. Call that function in your effect's cleanup.

Tell chat who is signed in

If your app has accounts, pass the signed-in user to the widget so agents can see who they are talking to. Anyone can run JavaScript in their own browser, so a user ID sent from the page alone proves nothing. Sign it on your server with the identity secret from the dashboard, using HMAC-SHA256.

// app/api/chat-identity/route.ts (runs on your server only)
import { createHmac } from 'node:crypto';
import { getCurrentUser } from '@/lib/auth'; // your own sign-in code

export async function GET() {
  const user = await getCurrentUser();
  if (!user) return Response.json(null, { status: 401 });

  const identifierHash = createHmac('sha256', process.env.DCHAT_IDENTITY_SECRET!)
    .update(user.id)
    .digest('hex');

  return Response.json({ id: user.id, name: user.name, email: user.email, identifierHash });
}

Keep the secret in a server-side environment variable. Never give it a NEXT_PUBLIC_ prefix, because that would put it in the browser bundle. Then send the result to the widget from a client component:

useEffect(() => {
  if (!user) {
    window.DChat?.reset();
    return;
  }

  fetch('/api/chat-identity')
    .then((response) => response.json())
    .then((me) => {
      window.DChat?.setUser(me.id, {
        identifierHash: me.identifierHash,
        name: me.name,
        email: me.email,
      });
    });
}, [user]);

Calling DChat.reset() at sign-out matters on shared computers. It forgets the user, the conversation and the visitor ID in that browser, so the next person starts clean.

In this example the user changes after the page has loaded. If your user is already known on first render, wait for the script first, with the onLoad prop of next/script or the load event of the script element. Calls made after the script loads and before the widget finishes starting are remembered and applied.

If your site sends a Content Security Policy

A strict policy blocks the widget without any visible error on the page. Allow your chat server in these directives, and check the browser console for anything else your setup needs:

  • script-src: to load the widget
  • connect-src: for its requests to your server
  • img-src and media-src: for attachments, images and audio
  • style-src: the widget adds its styles in a style element inside its own shadow root, so a policy without 'unsafe-inline' needs a hash or nonce approach that you should test

Test it

  1. Load a page. The launcher should appear in the corner.
  2. Move between several routes. The launcher should appear once and stay in place.
  3. Start a chat as a visitor, change route, and confirm that the conversation is still open.
  4. Sign in to the dashboard, set yourself online, and answer the chat.
  5. Sign out of your app and confirm that the next chat starts empty.

If the launcher does not appear, work through the widget troubleshooting guide.

Common questions

Is there an npm package for the DChat widget?

No package is needed. The widget is one script served from your own DChat server, so it always matches your server version and adds nothing to your JavaScript bundle.

Will the widget reload when the route changes?

No. In a single-page app the page does not reload between routes. The widget sits on document.body outside your React tree, so it stays open and keeps its conversation.

Why does the widget load twice in development?

React Strict Mode runs effects twice in development. Give the script an id and return early if an element with that id already exists, as the example in this guide does.

Does the widget work with server-side rendering?

Yes. The widget runs only in the browser. Load it from an effect or with next/script, and do not touch window.DChat while rendering on the server.

How do I hide the widget on some routes?

Load the script only in the layout for the routes that should have chat. If it is already loaded, you can hide the element with the id dchat-widget-root on the routes where you do not want it.

Self-hosted customer support software

Deploy live chat on your own terms, not on someone else's pricing model.

DChat gives you the installable server, web dashboard, website widget, and desktop agent tools in one self-hosted product, with live chat free to run, and an AI agent that answers, acts with the approvals you set and hands off to your team when you want one. Run it on infrastructure you trust, on the model you choose.

Deployment

Install on Windows or Linux, behind IIS or Nginx, in a VM, or in Docker if that fits your stack.

Commercial model

Live chat is free with unlimited agents. Premium, with the AI agent, is billed per agent per month, never per conversation.

AI Flexibility

Run the AI agent on a local Ollama model, or connect OpenAI and Anthropic with your own provider accounts.