Skip to main content

React and Next.js

The widget is a plain script that attaches itself to document.body, so in a single-page app you load it once, not per route. Two ways:

Option A: the script tag in your HTML shell​

The simplest. In Vite, Create React App or any app with an index.html, add the snippet before </body>; it works for anonymous visitors on every route.

index.html
<script src="https://api.mysarthi.tech/widget/v1.js" data-site-key="ws_acme_7f3a9c" async></script>

In Next.js, use next/script in the root layout so it is loaded once and after hydration:

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

export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<Script src="https://api.mysarthi.tech/widget/v1.js" data-site-key="ws_acme_7f3a9c" strategy="afterInteractive" />
</body>
</html>
);
}

Option B: a small component (needed for signed-in users)​

When you need to pass a token for the signed-in user, load the script without data-site-key and call window.Sarthi.init yourself. A component that mounts once near the root:

components/SarthiChat.jsx
'use client'; // Next.js App Router: this runs in the browser

import { useEffect } from 'react';

const WIDGET_SRC = 'https://api.mysarthi.tech/widget/v1.js';
const SITE_KEY = 'ws_acme_7f3a9c';

export default function SarthiChat({ signedIn }) {
useEffect(() => {
const options = {
siteKey: SITE_KEY,
// Only for signed-in pages: your own route returns a fresh token (see "Signed-in customers").
...(signedIn && {
getEndUserToken: () =>
fetch('/api/sarthi-token', { credentials: 'same-origin' })
.then((r) => r.json())
.then((d) => d.token),
}),
};

if (window.Sarthi?.version) {
window.Sarthi.init(options);
} else {
// The script hasn't loaded yet: queue the call; it runs as soon as it has.
window.Sarthi = { q: [['init', options]] };
if (!document.querySelector(`script[src="${WIDGET_SRC}"]`)) {
const s = document.createElement('script');
s.src = WIDGET_SRC;
s.async = true;
document.body.appendChild(s);
}
}
return () => window.Sarthi?.destroy?.();
}, [signedIn]);

return null;
}

Render it once, in your root layout or App:

<SarthiChat signedIn={Boolean(user)} />
  • The queue (window.Sarthi = { q: [['init', …]] }) is understood by the widget: calls made before the script loads run as soon as it has. Don't put data-site-key on the tag when you call init yourself, or the widget would start twice.
  • When the user logs in or out, the component re-runs: destroy() removes the current bubble and init starts the right kind of chat. A chat started as anonymous is never shown to a signed-in user, and the other way round.
  • The token route (/api/sarthi-token) is yours: see Signing the token on your server for an Express and a Next.js route handler.

Strict mode and hot reload​

React's development strict mode mounts effects twice; destroy() in the cleanup keeps that harmless. Hot reloads also call the cleanup, so you never end up with two bubbles.