DEV Community

MochaWang
MochaWang

Posted on AI-assisted

Add Knocket chat to a Next.js blog and reply from Telegram

I added a chat bubble to my Next.js blog so readers could ask a question from an article or project page. When someone sends a message, I get a Telegram notification. I reply to that notification in Telegram, and the visitor sees my reply in the same chat window.

This walkthrough comes from my October 2026 setup on a Next.js 15 App Router project. The part I want to show is what happens during client-side navigation. If the widget has already loaded on a public page, it can stay visible when you navigate to a route where it should be hidden.

Connect Telegram

  1. Open BotFather, send /newbot, and follow the prompts to create a bot. Copy its token.
  2. Open Management → Integrations → Telegram Bot in Knocket, enter the token, then complete the activation step in Telegram using the instructions Knocket gives you.
  3. In Knocket’s notification settings, enable Telegram and select the option for full messages with quote replies. Confirm that the bot shows as connected.

Copy the widget identifier from Knocket’s Installation page. The identifier goes in the browser’s SDK URL. Keep the Telegram bot token in the integration settings.

Load the widget on public routes

I mounted this client component once in the blog’s shared layout. It skips the script on direct visits to /admin and /login or their subpaths. When the widget has already loaded, it calls hide() on excluded routes and uses CSS to hide the injected host element.

"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import Script from "next/script";

const SDK_URL =
  "https://trtc.io/knocket-sdk/sdk.js?identifier=YOUR_KNOCKET_IDENTIFIER";

type KnocketWindow = Window & {
  contactWidget?: {
    show?: () => void;
    hide?: () => void;
  };
};

function isExcludedPath(pathname: string) {
  return ["/admin", "/login"].some(
    (path) => pathname === path || pathname.startsWith(`${path}/`),
  );
}

function synchronizeVisibility() {
  const widget = (window as KnocketWindow).contactWidget;
  if (isExcludedPath(window.location.pathname)) {
    widget?.hide?.();
  } else {
    widget?.show?.();
  }
}

export function KnocketWidget() {
  const pathname = usePathname();
  const excluded = !pathname || isExcludedPath(pathname);

  useEffect(() => {
    synchronizeVisibility();
    return () => (window as KnocketWindow).contactWidget?.hide?.();
  }, [excluded]);

  return (
    <>
      <style id="knocket-route-style">{`
        #contact-widget-auto {
          --contact-widget-right: max(20px, env(safe-area-inset-right));
          --contact-widget-bottom: max(20px, env(safe-area-inset-bottom));
        }
        @media (max-width: 767px) {
          #contact-widget-auto {
            --contact-widget-right: max(12px, env(safe-area-inset-right));
            --contact-widget-bottom: max(12px, env(safe-area-inset-bottom));
          }
        }
        ${excluded ? "#contact-widget-auto { display: none !important; }" : ""}
      `}</style>
      {excluded ? null : (
        <Script
          id="knocket-sdk"
          src={SDK_URL}
          strategy="lazyOnload"
          onReady={synchronizeVisibility}
        />
      )}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_KNOCKET_IDENTIFIER with the value from your console and mount <KnocketWidget /> once in your shared layout. The widget uses lazyOnload to load during browser idle time. The onReady callback checks the current URL, so a route change while the SDK is loading won’t leave the widget visible on an excluded page.

The contactWidget object and host selector reflect the version of Knocket I tested. Check them if the SDK changes. Route-based widget visibility is a UI choice. Keep your application’s authentication checks in place.

Verify the round trip

  1. Open a public article at a mobile viewport width. Start a chat and send a distinct test message.
  2. Find that notification in Telegram. Use Reply on the notification itself and send a short response.
  3. Return to the original visitor session and check that the response appears in the chat.
  4. Visit the login page directly. If you can navigate from a public page to an excluded route within the app, test that transition too, then return to a public page and check that the widget reappears.

My first test used the simulated conversation in the Knocket inbox. The message showed up in the inbox, but I didn’t receive a Telegram notification. Repeating the test from the embedded widget worked in both directions. If you run into the same symptom, start with a message from the actual website.

Mobile screenshot of a visitor message and the reply sent through Telegram

Read the original Chinese walkthrough with setup screenshots. See also the Knocket Web Widget docs and the Next.js 15 script guide.

Adapted from my original Chinese write-up with AI-assisted translation and editing.

Top comments (0)