cometchat-react-router-patterns — independently scanned and version-tracked by SaferSkills.
SaferSkills independently audited cometchat-react-router-patterns (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
Ground truth:@cometchat/chat-uikit-react@^6(+@cometchat/calls-sdk-javascript@^5) — installed package types +ui-kit/react. Official docs: https://www.cometchat.com/docs/ui-kit/react/overview · Docs MCP:claude mcp add --transport http cometchat-docs https://www.cometchat.com/docs/mcp(or fetch the URL directly without MCP). Verify symbols against the installed package/source before relying on them.
This skill teaches Claude how to integrate CometChat into React Router projects. React Router exists in two distinct modes with very different integration patterns:
Read these companion skills first:
cometchat-core -- initialization, login, CSS, provider pattern, anti-patternscometchat-components -- component catalog and composition patternscometchat-placement -- WHERE to put chat (route, modal, drawer, embedded)# Check package.json for React Router
grep -E '"react-router-dom"|"react-router"' package.json# v7 framework mode: has a config file
ls react-router.config.ts react-router.config.js 2>/dev/null
# v6 library mode: uses createBrowserRouter or <BrowserRouter> in source
grep -rn "createBrowserRouter\|BrowserRouter\|<Routes" src/ --include="*.tsx" --include="*.jsx" 2>/dev/null | head -5Decision:
react-router.config.ts or react-router.config.js exists: v7 framework modereact-router-dom is in package.json with createBrowserRouter or <BrowserRouter> in source: v6 library modereact-router (not react-router-dom) is in package.json without a config file: likely v7 in library mode -- treat as v6 library modev6 library mode is essentially a plain React app with routing. There are no SSR concerns. CometChat integration follows the same patterns as the cometchat-react-patterns skill, with routing-specific additions.
Mount the provider at the router level, wrapping the entire router or a specific route subtree:
// src/main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider } from "react-router-dom";
import { CometChatProvider } from "./providers/CometChatProvider";
import { router } from "./router";
import "@cometchat/chat-uikit-react/css-variables.css";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<CometChatProvider>
<RouterProvider router={router} />
</CometChatProvider>
</React.StrictMode>
);The provider implementation is the same as in cometchat-react-patterns section 2 -- uses import.meta.env.VITE_COMETCHAT_* for env vars.
Find the router configuration and add a new route:
// src/router.tsx
import { createBrowserRouter } from "react-router-dom";
import Layout from "./components/Layout";
import HomePage from "./pages/HomePage";
import ChatPage from "./pages/ChatPage";
export const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <HomePage /> },
{ path: "messages", element: <ChatPage /> },
// ... existing routes
],
},
]);// In App.tsx
import { Routes, Route } from "react-router-dom";
import Layout from "./components/Layout";
import ChatPage from "./pages/ChatPage";
function App() {
return (
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<HomePage />} />
<Route path="messages" element={<ChatPage />} />
</Route>
</Routes>
);
}A powerful pattern for React Router: use nested routes to show conversation details alongside the conversation list.
// Router config
export const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
path: "messages",
element: <ChatLayout />,
children: [
{ index: true, element: <EmptyState /> },
{ path: ":conversationId", element: <ConversationView /> },
],
},
],
},
]);// ChatLayout.tsx -- renders conversation list + Outlet for message view
import { Outlet } from "react-router-dom";
import { CometChatConversations } from "@cometchat/chat-uikit-react";
import { useNavigate } from "react-router-dom";
export default function ChatLayout() {
const navigate = useNavigate();
return (
<div style={{ display: "flex", height: "100vh" }}>
<div style={{ width: "360px", borderRight: "1px solid #eee" }}>
<CometChatConversations
onItemClick={(conversation) => {
const id = conversation.getConversationId();
navigate(`/messages/${id}`);
}}
/>
</div>
<div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
<Outlet />
</div>
</div>
);
}// ConversationView.tsx -- renders messages for the selected conversation
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
CometChatMessageHeader,
CometChatMessageList,
CometChatMessageComposer,
} from "@cometchat/chat-uikit-react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
export default function ConversationView() {
const { conversationId } = useParams();
const [user, setUser] = useState<CometChat.User>();
const [group, setGroup] = useState<CometChat.Group>();
useEffect(() => {
if (!conversationId) return;
// NOTE: this `:conversationId` param is OUR custom URL scheme — the prefix is
// chosen by the navigate() in ConversationsList below ("user_<uid>" / "group_<guid>").
// Do NOT confuse it with CometChat's raw Conversation.getConversationId(), which
// for a 1:1 is "<loggedInUid>_user_<peerUid>" (the "_user_" sits in the MIDDLE,
// so startsWith("user_") would never match it). Both ends must agree on the
// custom scheme; branch only on that prefix here.
if (conversationId.startsWith("user_")) {
const uid = conversationId.slice("user_".length);
CometChat.getUser(uid).then((u) => {
setUser(u);
setGroup(undefined);
});
} else if (conversationId.startsWith("group_")) {
const guid = conversationId.slice("group_".length);
CometChat.getGroup(guid).then((g) => {
setUser(undefined);
setGroup(g);
});
}
}, [conversationId]);
if (!user && !group) return null;
return (
<>
{user && <CometChatMessageHeader user={user} />}
{group && <CometChatMessageHeader group={group} />}
{user && <CometChatMessageList user={user} hideReplyInThreadOption={true} />}
{group && <CometChatMessageList group={group} hideReplyInThreadOption={true} />}
{user && <CometChatMessageComposer user={user} />}
{group && <CometChatMessageComposer group={group} />}
</>
);
}CometChat's onItemClick callbacks can use React Router's useNavigate to drive URL changes:
import { useNavigate } from "react-router-dom";
function ConversationsList() {
const navigate = useNavigate();
return (
<CometChatConversations
onItemClick={(conversation) => {
const entity = conversation.getConversationWith();
if (entity instanceof CometChat.User) {
navigate(`/messages/user_${entity.getUid()}`);
} else if (entity instanceof CometChat.Group) {
navigate(`/messages/group_${entity.getGuid()}`);
}
}}
/>
);
}This works because useNavigate returns a stable function that CometChat's callback invokes in the browser.
React Router v7 in framework mode is a full meta-framework with SSR, file-system routing, loaders, and actions. It has the same SSR concerns as Next.js: CometChat components cannot run on the server.
Visual Builder support on RR v7: as of v4.3.0 (F19 fix),cometchat builder export --platform reactpost-extract codemod patches the canonical's type-as-value imports so Rolldown (Vite 7+ / RR v7's bundler) builds clean. Previously this combo failed with[MISSING_EXPORT] "CometChatSettingsInterface" is not exported. The patched canonical drops intoapp/CometChat/and builds in <1s (691ms client + 59ms server). No additional config required.
v7 renders components on the server by default. CometChat components will crash during server rendering. Use a ClientOnly wrapper:
// app/components/ClientOnly.tsx
import { useState, useEffect, type ReactNode } from "react";
interface ClientOnlyProps {
children: ReactNode;
fallback?: ReactNode;
}
export function ClientOnly({ children, fallback = null }: ClientOnlyProps) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
return mounted ? <>{children}</> : <>{fallback}</>;
}Or use React.lazy + Suspense:
import { lazy, Suspense } from "react";
const ChatView = lazy(() => import("../components/ChatView"));
export default function MessagesRoute() {
return (
<ClientOnly fallback={<div>Loading chat...</div>}>
<Suspense fallback={<div>Loading chat...</div>}>
<ChatView />
</Suspense>
</ClientOnly>
);
}The provider needs ClientOnly wrapping because useEffect runs on the client but the module import of @cometchat/chat-uikit-react happens on the server too:
// app/providers/CometChatProvider.tsx
import React, { useEffect, useState, createContext, useContext } from "react";
interface CometChatContextValue {
isReady: boolean;
error: string | null;
}
const CometChatContext = createContext<CometChatContextValue>({
isReady: false,
error: null,
});
export const useCometChat = () => useContext(CometChatContext);
// Module-level state prevents both double-init AND double-login in React
// StrictMode. Without the loginInFlight guard, a second mount calls
// login() while the first is still pending and the SDK throws
// "Please wait until the previous login request ends."
let initialized = false;
let loginInFlight: Promise<unknown> | null = null;
// `ensureLoggedIn` is defined inside `setup()` below so it can close over
// the dynamically-imported `CometChatUIKit`. Hoisting it to module scope
// would `ReferenceError` because the static import is intentionally
// removed (SSR safety) — `CometChatUIKit` only exists inside the await.
export function CometChatProvider({ children }: { children: React.ReactNode }) {
const [isReady, setIsReady] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function setup() {
try {
// Dynamic import to prevent server-side module resolution
const { CometChatUIKit, UIKitSettingsBuilder } = await import(
"@cometchat/chat-uikit-react"
);
async function ensureLoggedIn(uid: string, authToken?: string): Promise<void> {
const existing = await CometChatUIKit.getLoggedinUser();
if (existing) return;
if (loginInFlight) {
await loginInFlight;
return;
}
loginInFlight = authToken
? CometChatUIKit.loginWithAuthToken(authToken)
: CometChatUIKit.login(uid);
try {
await loginInFlight;
} finally {
loginInFlight = null;
}
}
if (!initialized) {
initialized = true;
const settings = new UIKitSettingsBuilder()
.setAppId(import.meta.env.VITE_COMETCHAT_APP_ID)
.setRegion(import.meta.env.VITE_COMETCHAT_REGION)
.setAuthKey(import.meta.env.VITE_COMETCHAT_AUTH_KEY)
.subscribePresenceForAllUsers()
.build();
await CometChatUIKit.init(settings);
}
await ensureLoggedIn("cometchat-uid-1"); // DEVELOPMENT ONLY — see cometchat-production skill
setIsReady(true);
} catch (e) {
setError(String(e));
}
}
setup();
}, []);
if (error) {
return (
<div style={{ color: "red", padding: 16, fontFamily: "monospace" }}>
CometChat Error: {error}
</div>
);
}
if (!isReady) return null;
return (
<CometChatContext.Provider value={{ isReady, error }}>
{children}
</CometChatContext.Provider>
);
}Key difference from the plain React provider: The import("@cometchat/chat-uikit-react") is done dynamically inside useEffect, NOT at the top level. This prevents the server from trying to resolve the module.
Option A — Chat-only app (all routes use CometChat):
Wrap the entire app. This disables SSR for all routes since ClientOnly renders nothing on the server.
// app/root.tsx
import { Outlet } from "react-router";
import { ClientOnly } from "./components/ClientOnly";
import { CometChatProvider } from "./providers/CometChatProvider";
export default function Root() {
return (
<html lang="en">
<body>
<ClientOnly>
<CometChatProvider>
<Outlet />
</CometChatProvider>
</ClientOnly>
</body>
</html>
);
}Option B — Mixed app (some routes need SSR):
Keep the root clean and scope CometChat to a layout route. Non-chat routes keep full SSR.
// app/root.tsx — no CometChat here, SSR works normally
import { Outlet } from "react-router";
export default function Root() {
return (
<html lang="en">
<body>
<Outlet />
</body>
</html>
);
}// app/routes/chat.tsx — layout route for all /chat/* paths
import { Outlet } from "react-router";
import { ClientOnly } from "../components/ClientOnly";
import { CometChatProvider } from "../providers/CometChatProvider";
export default function ChatLayout() {
return (
<ClientOnly fallback={<div>Loading chat...</div>}>
<CometChatProvider>
<Outlet />
</CometChatProvider>
</ClientOnly>
);
}Then nest chat routes under this layout (e.g. app/routes/chat.messages.tsx). Marketing pages, dashboards, and other non-chat routes render server-side as normal.
Use Option A for apps where every page involves chat (messaging apps, social platforms). Use Option B for apps that add chat to an existing product (SaaS, marketplaces, support).
v7 framework mode uses file-based routing. Create a route file:
// app/routes/messages.tsx
import { lazy, Suspense } from "react";
import { ClientOnly } from "../components/ClientOnly";
const ChatView = lazy(() => import("../components/ChatView"));
export default function MessagesRoute() {
return (
<ClientOnly fallback={<div>Loading chat...</div>}>
<Suspense fallback={<div>Loading chat...</div>}>
<ChatView />
</Suspense>
</ClientOnly>
);
}NEVER put CometChat initialization or SDK calls in a `loader` or `action`. Loaders and actions run on the server in v7 framework mode. CometChat requires browser APIs.
// WRONG -- loader runs on the server
export async function loader() {
const { CometChat } = await import("@cometchat/chat-sdk-javascript");
const user = await CometChat.getUser("uid"); // crashes on server
return { user };
}
// CORRECT -- use clientLoader if you need chat data at route entry
export async function clientLoader() {
const { CometChat } = await import("@cometchat/chat-sdk-javascript");
const user = await CometChat.getUser("uid");
return { user };
}clientLoader runs only in the browser. It is the right place for CometChat data fetching at the route level. However, most CometChat integrations do not need loaders at all -- the components handle their own data fetching.
This pattern works in both v6 and v7. Chat as a parent route with nested child routes:
/messages → Conversation list (left pane), empty state (right pane)
/messages/:conversationId → Conversation list (left pane), messages (right pane){
path: "messages",
element: <ChatLayout />,
children: [
{ index: true, element: <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "#999" }}>Select a conversation</div> },
{ path: ":conversationId", element: <ConversationView /> },
],
}app/routes/
messages.tsx → ChatLayout (renders <Outlet />)
messages._index.tsx → Empty state
messages.$conversationId.tsx → ConversationView// app/routes/messages.tsx
import { Outlet } from "react-router";
import { ClientOnly } from "../components/ClientOnly";
import { lazy, Suspense } from "react";
const ConversationList = lazy(() => import("../components/ConversationList"));
export default function MessagesLayout() {
return (
<div style={{ display: "flex", height: "100vh" }}>
<div style={{ width: "360px", borderRight: "1px solid #eee" }}>
<ClientOnly>
<Suspense fallback={<div>Loading...</div>}>
<ConversationList />
</Suspense>
</ClientOnly>
</div>
<div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
<Outlet />
</div>
</div>
);
}Same as cometchat-react-patterns -- uses VITE_ prefix:
VITE_COMETCHAT_APP_ID=your_app_id
VITE_COMETCHAT_REGION=us
VITE_COMETCHAT_AUTH_KEY=your_auth_keyAccess: import.meta.env.VITE_COMETCHAT_APP_ID
Also uses Vite under the hood, so the same VITE_ prefix applies:
VITE_COMETCHAT_APP_ID=your_app_id
VITE_COMETCHAT_REGION=us
VITE_COMETCHAT_AUTH_KEY=your_auth_keyServer-only variables (for auth token generation in actions) can omit the VITE_ prefix so they are never exposed to the client bundle:
COMETCHAT_AUTH_TOKEN=your_server_secretAccess server-only vars in loaders/actions via process.env:
// app/routes/api.cometchat-token.tsx (runs server-side only)
export async function action({ request }: ActionFunctionArgs) {
const secret = process.env.COMETCHAT_AUTH_TOKEN;
// ...
}Note:process.envis available in loaders/actions when using the default Node adapter (@react-router/node). Other adapters (Cloudflare, Deno) expose env differently — check your adapter's docs.
Import in src/main.tsx:
import "@cometchat/chat-uikit-react/css-variables.css";Import in app/root.tsx:
import "@cometchat/chat-uikit-react/css-variables.css";Or use the links export:
// app/root.tsx
import cometchatStyles from "@cometchat/chat-uikit-react/css-variables.css?url";
export function links() {
return [{ rel: "stylesheet", href: cometchatStyles }];
}The ?url suffix tells Vite to return a URL instead of injecting the CSS, which works with React Router's links convention.
The most common mistake in v7 framework mode. Loaders and actions run on the server. Any CometChat code in a loader crashes with window is not defined. Use clientLoader instead, or handle data fetching in the component.
React Router v7's unstable_middleware feature does NOT affect CometChat. CometChat has no middleware requirements. Do not add CometChat-related middleware.
useNavigate works inside CometChat's event callbacks (onItemClick, etc.) because these callbacks execute in the browser within the React tree. This is safe:
const navigate = useNavigate();
<CometChatConversations
onItemClick={(conv) => navigate(`/messages/${conv.getConversationId()}`)}
/>Even clientLoader is not the right place for CometChat initialization. Init should happen once in the provider (app root), not per-route. clientLoader is only appropriate for CometChat data queries (like CometChat.getUser()) that need to complete before the route renders.
If a project is migrating from v6 library mode to v7 framework mode, the CometChat integration must change:
ClientOnly wrappercreateBrowserRouter routes to file-system routesDo not mix v6 and v7 patterns. Detect the mode (section 1) and use the correct pattern.
npm install @cometchat/chat-uikit-react@^6 @cometchat/chat-sdk-javascript@^4 — ⚠️ keep the `@^6` major pin; never install bare. v7 is on npm — a bare npm install @cometchat/chat-uikit-react pulls it once it's tagged latest, and these v6 skills break against the v7 API..env with VITE_COMETCHAT_APP_ID, VITE_COMETCHAT_REGION, VITE_COMETCHAT_AUTH_KEY.env to .gitignore@cometchat/chat-uikit-react/css-variables.css in src/main.tsxsrc/providers/CometChatProvider.tsx (uses import.meta.env.VITE_*)CometChatProvider in src/main.tsx wrapping <RouterProvider>src/pages/ChatPage.tsx (see cometchat-placement for patterns){ path: "messages", element: <ChatPage /> } to the router confignpm install @cometchat/chat-uikit-react@^6 @cometchat/chat-sdk-javascript@^4 — ⚠️ keep the `@^6` major pin; never install bare. v7 is on npm — a bare npm install @cometchat/chat-uikit-react pulls it once it's tagged latest, and these v6 skills break against the v7 API..env with VITE_COMETCHAT_APP_ID, VITE_COMETCHAT_REGION, VITE_COMETCHAT_AUTH_KEY.env to .gitignore@cometchat/chat-uikit-react/css-variables.css in app/root.tsxapp/components/ClientOnly.tsx (section 3)app/providers/CometChatProvider.tsx with dynamic imports (section 3)ClientOnly + CometChatProvider in app/root.tsxapp/routes/messages.tsx with ClientOnly + lazy import (section 3)If the customer picks Visually in dispatcher Step 3.1, skills runs cometchat builder export --platform react --output <target> to download the canonical src/CometChat/ + patch settings in one step.
Full recipe lives in `cometchat-core` §11 "Visual Builder integration". This section is a pointer + React Router-specific gotchas:
cometchat builder export --platform react --output app/CometChat --json.app/routes/chat.client.tsx — the .client.tsx suffix skips SSR for this file.app/routes.ts via route("chat", "routes/chat.client.tsx").cometchat builder export --platform react --output src/CometChat --json (default).cometchat-react-patterns §9).React Router v7's Vite 7+ build uses Rolldown, which rejects the canonical CometChat/'s type-as-value imports (e.g. import { CometChatSettingsInterface } from "../context/CometChatContext" used in type-only positions) with [MISSING_EXPORT] "CometChatSettingsInterface" is not exported. Webpack-based bundlers (CRA, Next.js classic) and rollup (Astro, older Vite) tolerate it as a warning.
This is fixed in v4.3.0. After cometchat builder export --platform react, the CLI runs a post-extract codemod (applyReactRolldownFix) that rewrites the affected imports with the inline type modifier so Rolldown builds clean (verified <1s: 691ms client + 59ms server). No customer action or config required — RR v7 + Visual Builder builds out of the box.
@cometchat/[email protected] + @cometchat/[email protected].package.json needs cometChatCustomConfig block (Finding F2).tsconfig.app.json requires the relaxation set from cometchat-core §11.2.If the customer picks In code, ignore this section.
~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.