@cometchat/skills 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,857 @@
1
+ ---
2
+ name: cometchat-nextjs-patterns
3
+ description: "Framework-specific patterns for integrating CometChat React UI Kit v6 into Next.js projects (App Router and Pages Router). Covers SSR prevention, provider setup, route placement, API routes, and common pitfalls."
4
+ license: "MIT"
5
+ compatibility: "Node.js >=18; React >=18; Next.js >=13; @cometchat/chat-uikit-react ^6; @cometchat/chat-sdk-javascript ^4"
6
+ allowed-tools: "executeBash, readFile, fileSearch, listDirectory"
7
+ metadata:
8
+ author: "CometChat"
9
+ version: "3.0.0"
10
+ tags: "chat cometchat nextjs next react ssr app-router pages-router patterns"
11
+ ---
12
+
13
+ ## Purpose
14
+
15
+ This skill teaches Claude how to integrate CometChat into a Next.js project. Next.js is the most complex framework to integrate with because of Server-Side Rendering (SSR) and the Server Component / Client Component boundary. Every CometChat component is browser-only -- getting this wrong is the #1 source of integration failures.
16
+
17
+ **Read these companion skills first:**
18
+ - `cometchat-core` -- initialization, login, CSS, provider pattern, anti-patterns
19
+ - `cometchat-components` -- component catalog and composition patterns
20
+ - `cometchat-placement` -- WHERE to put chat (route, modal, drawer, embedded)
21
+
22
+ This skill covers the HOW for Next.js specifically.
23
+
24
+ ---
25
+
26
+ ## 1. Project detection
27
+
28
+ A project uses Next.js when `package.json` has `next` as a dependency.
29
+
30
+ ### Detecting App Router vs Pages Router
31
+
32
+ Both may coexist in a project. Check which is primary:
33
+
34
+ ```bash
35
+ # App Router: look for app/ directory with layout.tsx
36
+ ls app/layout.tsx app/layout.jsx 2>/dev/null
37
+
38
+ # Pages Router: look for pages/ directory with _app.tsx
39
+ ls pages/_app.tsx pages/_app.jsx pages/_app.js 2>/dev/null
40
+ ```
41
+
42
+ **If `app/layout.tsx` exists, treat the project as App Router.** Even if `pages/` also exists, App Router is the primary routing mechanism in modern Next.js.
43
+
44
+ **If only `pages/` exists, treat the project as Pages Router.**
45
+
46
+ ---
47
+
48
+ ## 2. Critical: SSR prevention
49
+
50
+ **Every file that imports from `@cometchat/chat-uikit-react` MUST prevent server-side rendering.** CometChat components access `window`, `document`, and WebSocket APIs during import -- not just during render, but at import time. If Next.js tries to import these modules on the server, the build crashes with `ReferenceError: window is not defined`.
51
+
52
+ ### App Router: "use client" directive
53
+
54
+ Add `"use client"` as the FIRST line of every file that imports CometChat:
55
+
56
+ ```tsx
57
+ "use client";
58
+
59
+ import { CometChatConversations } from "@cometchat/chat-uikit-react";
60
+ // This file only runs in the browser
61
+ ```
62
+
63
+ **Common mistake:** Putting `"use client"` AFTER imports. It must be the very first line, before any import statements.
64
+
65
+ ```tsx
66
+ // WRONG -- "use client" is not the first line
67
+ import React from "react";
68
+ "use client"; // too late, has no effect
69
+
70
+ // CORRECT
71
+ "use client";
72
+ import React from "react";
73
+ ```
74
+
75
+ ### App Router: dynamic import from Server Components
76
+
77
+ If you need to render a CometChat component inside a Server Component (e.g., a page that does data fetching), use `next/dynamic` with `ssr: false`:
78
+
79
+ ```tsx
80
+ // app/messages/page.tsx (this is a Server Component)
81
+ import dynamic from "next/dynamic";
82
+
83
+ const ChatView = dynamic(() => import("../../components/ChatView"), {
84
+ ssr: false,
85
+ loading: () => <div>Loading chat...</div>,
86
+ });
87
+
88
+ export default function MessagesPage() {
89
+ return <ChatView />;
90
+ }
91
+ ```
92
+
93
+ The `ChatView` component itself must still have `"use client"` at the top.
94
+
95
+ ### Pages Router: dynamic import
96
+
97
+ In the Pages Router, every page can potentially run on the server. Use `next/dynamic`:
98
+
99
+ ```tsx
100
+ // pages/messages.tsx
101
+ import dynamic from "next/dynamic";
102
+
103
+ const ChatView = dynamic(() => import("../components/ChatView"), {
104
+ ssr: false,
105
+ loading: () => <div>Loading chat...</div>,
106
+ });
107
+
108
+ export default function MessagesPage() {
109
+ return <ChatView />;
110
+ }
111
+ ```
112
+
113
+ ---
114
+
115
+ ## 3. CometChatProvider for Next.js (App Router)
116
+
117
+ ### Full implementation
118
+
119
+ ```tsx
120
+ // app/providers/CometChatProvider.tsx
121
+ "use client";
122
+
123
+ import React, { useEffect, useState, createContext, useContext } from "react";
124
+ import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";
125
+
126
+ interface CometChatContextValue {
127
+ isReady: boolean;
128
+ error: string | null;
129
+ }
130
+
131
+ const CometChatContext = createContext<CometChatContextValue>({
132
+ isReady: false,
133
+ error: null,
134
+ });
135
+
136
+ export const useCometChat = () => useContext(CometChatContext);
137
+
138
+ // Module-level state prevents both double-init AND double-login in React
139
+ // StrictMode. Without the loginInFlight guard, a second mount calls
140
+ // login() while the first is still pending and the SDK throws
141
+ // "Please wait until the previous login request ends."
142
+ let initialized = false;
143
+ let loginInFlight: Promise<unknown> | null = null;
144
+
145
+ async function ensureLoggedIn(
146
+ uid: string,
147
+ authToken?: string,
148
+ ): Promise<void> {
149
+ const existing = await CometChatUIKit.getLoggedinUser();
150
+ if (existing) return;
151
+ if (loginInFlight) {
152
+ await loginInFlight;
153
+ return;
154
+ }
155
+ loginInFlight = authToken
156
+ ? CometChatUIKit.loginWithAuthToken(authToken)
157
+ : CometChatUIKit.login(uid);
158
+ try {
159
+ await loginInFlight;
160
+ } finally {
161
+ loginInFlight = null;
162
+ }
163
+ }
164
+
165
+ interface CometChatProviderProps {
166
+ children: React.ReactNode;
167
+ }
168
+
169
+ export function CometChatProvider({ children }: CometChatProviderProps) {
170
+ const [isReady, setIsReady] = useState(false);
171
+ const [error, setError] = useState<string | null>(null);
172
+
173
+ useEffect(() => {
174
+ async function setup() {
175
+ try {
176
+ if (!initialized) {
177
+ initialized = true;
178
+
179
+ const settings = new UIKitSettingsBuilder()
180
+ .setAppId(process.env.NEXT_PUBLIC_COMETCHAT_APP_ID!)
181
+ .setRegion(process.env.NEXT_PUBLIC_COMETCHAT_REGION!)
182
+ .setAuthKey(process.env.NEXT_PUBLIC_COMETCHAT_AUTH_KEY!)
183
+ .subscribePresenceForAllUsers()
184
+ .build();
185
+
186
+ await CometChatUIKit.init(settings);
187
+ }
188
+
189
+ await ensureLoggedIn("cometchat-uid-1"); // DEVELOPMENT ONLY — see cometchat-production skill
190
+
191
+ setIsReady(true);
192
+ } catch (e) {
193
+ setError(String(e));
194
+ }
195
+ }
196
+
197
+ setup();
198
+ }, []);
199
+
200
+ if (error) {
201
+ return (
202
+ <div style={{ color: "red", padding: 16, fontFamily: "monospace" }}>
203
+ CometChat Error: {error}
204
+ </div>
205
+ );
206
+ }
207
+
208
+ if (!isReady) return null;
209
+
210
+ return (
211
+ <CometChatContext.Provider value={{ isReady, error }}>
212
+ {children}
213
+ </CometChatContext.Provider>
214
+ );
215
+ }
216
+ ```
217
+
218
+ ### Where to mount: Option A -- Global (chat available everywhere)
219
+
220
+ Wrap the entire app in `app/layout.tsx`. The layout itself is a Server Component, but the provider is a Client Component via `"use client"` in its file:
221
+
222
+ ```tsx
223
+ // app/layout.tsx (Server Component)
224
+ import { CometChatProvider } from "./providers/CometChatProvider";
225
+ import "./globals.css";
226
+
227
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
228
+ return (
229
+ <html lang="en">
230
+ <body>
231
+ <CometChatProvider>
232
+ {children}
233
+ </CometChatProvider>
234
+ </body>
235
+ </html>
236
+ );
237
+ }
238
+ ```
239
+
240
+ **Note:** Importing a `"use client"` component from a Server Component is fine. Next.js renders the Server Component on the server and defers the Client Component to the browser. The `CometChatProvider` only runs its `useEffect` (and init) in the browser.
241
+
242
+ ### Where to mount: Option B -- Scoped (chat only on chat routes)
243
+
244
+ Use a route group to scope the provider to chat-related routes:
245
+
246
+ ```
247
+ app/
248
+ layout.tsx <-- no CometChat here
249
+ page.tsx <-- home page, no chat overhead
250
+ (chat)/
251
+ layout.tsx <-- CometChatProvider wraps only this group
252
+ messages/
253
+ page.tsx <-- chat page
254
+ inbox/
255
+ page.tsx <-- another chat page
256
+ ```
257
+
258
+ ```tsx
259
+ // app/(chat)/layout.tsx
260
+ import { CometChatProvider } from "../providers/CometChatProvider";
261
+
262
+ export default function ChatLayout({ children }: { children: React.ReactNode }) {
263
+ return <CometChatProvider>{children}</CometChatProvider>;
264
+ }
265
+ ```
266
+
267
+ Option B is better for performance: CometChat's SDK and WebSocket connection are only loaded when the user visits a chat route. Option A is simpler and ensures incoming call notifications work everywhere.
268
+
269
+ ---
270
+
271
+ ## 4. CometChatProvider for Next.js (Pages Router)
272
+
273
+ In the Pages Router, mount the provider in `_app.tsx`. Use dynamic import to prevent SSR:
274
+
275
+ ```tsx
276
+ // pages/_app.tsx
277
+ import type { AppProps } from "next/app";
278
+ import dynamic from "next/dynamic";
279
+ import "../styles/globals.css";
280
+
281
+ const CometChatProvider = dynamic(
282
+ () => import("../components/CometChatProvider").then((mod) => mod.CometChatProvider),
283
+ { ssr: false }
284
+ );
285
+
286
+ export default function App({ Component, pageProps }: AppProps) {
287
+ return (
288
+ <CometChatProvider>
289
+ <Component {...pageProps} />
290
+ </CometChatProvider>
291
+ );
292
+ }
293
+ ```
294
+
295
+ The provider implementation is the same as section 3, but the file lives at `components/CometChatProvider.tsx` (no `"use client"` needed in Pages Router -- `ssr: false` handles SSR prevention).
296
+
297
+ ---
298
+
299
+ ## 5. Route placement (App Router)
300
+
301
+ Next.js App Router uses file-system routing. Creating a file at the right path automatically creates the route.
302
+
303
+ ### Create the chat page
304
+
305
+ ```tsx
306
+ // app/messages/page.tsx
307
+ "use client";
308
+
309
+ import { useState } from "react";
310
+ import {
311
+ CometChatConversations,
312
+ CometChatMessageHeader,
313
+ CometChatMessageList,
314
+ CometChatMessageComposer,
315
+ } from "@cometchat/chat-uikit-react";
316
+ import { CometChat } from "@cometchat/chat-sdk-javascript";
317
+
318
+ export default function MessagesPage() {
319
+ const [selectedUser, setSelectedUser] = useState<CometChat.User>();
320
+ const [selectedGroup, setSelectedGroup] = useState<CometChat.Group>();
321
+
322
+ function handleConversationClick(conversation: CometChat.Conversation) {
323
+ const entity = conversation.getConversationWith();
324
+ if (entity instanceof CometChat.User) {
325
+ setSelectedUser(entity);
326
+ setSelectedGroup(undefined);
327
+ } else if (entity instanceof CometChat.Group) {
328
+ setSelectedUser(undefined);
329
+ setSelectedGroup(entity);
330
+ }
331
+ }
332
+
333
+ return (
334
+ <div style={{ display: "flex", height: "100vh" }}>
335
+ <div style={{ width: "360px", borderRight: "1px solid #eee" }}>
336
+ <CometChatConversations onItemClick={handleConversationClick} />
337
+ </div>
338
+ <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
339
+ {(selectedUser || selectedGroup) ? (
340
+ <>
341
+ {selectedUser && <CometChatMessageHeader user={selectedUser} />}
342
+ {selectedGroup && <CometChatMessageHeader group={selectedGroup} />}
343
+ {selectedUser && <CometChatMessageList user={selectedUser} />}
344
+ {selectedGroup && <CometChatMessageList group={selectedGroup} />}
345
+ {selectedUser && <CometChatMessageComposer user={selectedUser} />}
346
+ {selectedGroup && <CometChatMessageComposer group={selectedGroup} />}
347
+ </>
348
+ ) : (
349
+ <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "#999" }}>
350
+ Select a conversation to start chatting
351
+ </div>
352
+ )}
353
+ </div>
354
+ </div>
355
+ );
356
+ }
357
+ ```
358
+
359
+ This page is accessible at `/messages`. No router configuration needed -- Next.js handles it via the file system.
360
+
361
+ ### Add a navigation link
362
+
363
+ Find the layout's nav component and add a link:
364
+
365
+ ```tsx
366
+ import Link from "next/link";
367
+
368
+ // In the nav, alongside existing links:
369
+ <Link href="/messages">Messages</Link>
370
+ ```
371
+
372
+ **Important:** Use Next.js's `<Link>` component (from `next/link`), not a plain `<a>` tag or React Router's `<Link>`. Next.js's Link handles client-side navigation and prefetching.
373
+
374
+ ---
375
+
376
+ ## 6. Route placement (Pages Router)
377
+
378
+ ### Create the chat page
379
+
380
+ ```tsx
381
+ // pages/messages.tsx
382
+ import dynamic from "next/dynamic";
383
+
384
+ const ChatView = dynamic(() => import("../components/ChatView"), {
385
+ ssr: false,
386
+ loading: () => (
387
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100vh" }}>
388
+ Loading chat...
389
+ </div>
390
+ ),
391
+ });
392
+
393
+ export default function MessagesPage() {
394
+ return <ChatView />;
395
+ }
396
+ ```
397
+
398
+ The `ChatView` component contains the actual CometChat composition (see `cometchat-placement` for patterns). It is dynamically imported with `ssr: false` to prevent server rendering.
399
+
400
+ ### ChatView implementation
401
+
402
+ ```tsx
403
+ // components/ChatView.tsx
404
+ import { useState } from "react";
405
+ import {
406
+ CometChatConversations,
407
+ CometChatMessageHeader,
408
+ CometChatMessageList,
409
+ CometChatMessageComposer,
410
+ } from "@cometchat/chat-uikit-react";
411
+ import { CometChat } from "@cometchat/chat-sdk-javascript";
412
+
413
+ export default function ChatView() {
414
+ const [selectedUser, setSelectedUser] = useState<CometChat.User>();
415
+ const [selectedGroup, setSelectedGroup] = useState<CometChat.Group>();
416
+
417
+ function handleConversationClick(conversation: CometChat.Conversation) {
418
+ const entity = conversation.getConversationWith();
419
+ if (entity instanceof CometChat.User) {
420
+ setSelectedUser(entity);
421
+ setSelectedGroup(undefined);
422
+ } else if (entity instanceof CometChat.Group) {
423
+ setSelectedUser(undefined);
424
+ setSelectedGroup(entity);
425
+ }
426
+ }
427
+
428
+ return (
429
+ <div style={{ display: "flex", height: "100vh" }}>
430
+ <div style={{ width: "360px", borderRight: "1px solid #eee" }}>
431
+ <CometChatConversations onItemClick={handleConversationClick} />
432
+ </div>
433
+ <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
434
+ {selectedUser && (
435
+ <>
436
+ <CometChatMessageHeader user={selectedUser} />
437
+ <CometChatMessageList user={selectedUser} />
438
+ <CometChatMessageComposer user={selectedUser} />
439
+ </>
440
+ )}
441
+ {selectedGroup && (
442
+ <>
443
+ <CometChatMessageHeader group={selectedGroup} />
444
+ <CometChatMessageList group={selectedGroup} />
445
+ <CometChatMessageComposer group={selectedGroup} />
446
+ </>
447
+ )}
448
+ </div>
449
+ </div>
450
+ );
451
+ }
452
+ ```
453
+
454
+ ---
455
+
456
+ ## 7. Modal/drawer placement
457
+
458
+ ### App Router
459
+
460
+ Create a Client Component for the drawer:
461
+
462
+ ```tsx
463
+ // components/ChatDrawer.tsx
464
+ "use client";
465
+
466
+ import { useEffect, useState } from "react";
467
+ import {
468
+ CometChatMessageHeader,
469
+ CometChatMessageList,
470
+ CometChatMessageComposer,
471
+ } from "@cometchat/chat-uikit-react";
472
+ import { CometChat } from "@cometchat/chat-sdk-javascript";
473
+
474
+ interface ChatDrawerProps {
475
+ isOpen: boolean;
476
+ onClose: () => void;
477
+ targetUserId?: string;
478
+ }
479
+
480
+ export function ChatDrawer({ isOpen, onClose, targetUserId }: ChatDrawerProps) {
481
+ const [user, setUser] = useState<CometChat.User>();
482
+
483
+ useEffect(() => {
484
+ if (!isOpen || !targetUserId) return;
485
+ CometChat.getUser(targetUserId).then(setUser);
486
+ }, [isOpen, targetUserId]);
487
+
488
+ if (!isOpen) return null;
489
+
490
+ return (
491
+ <>
492
+ <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 999, backgroundColor: "rgba(0,0,0,0.3)" }} />
493
+ <div style={{
494
+ position: "fixed", top: 0, right: 0, bottom: 0, width: "400px", zIndex: 1000,
495
+ backgroundColor: "#fff", boxShadow: "-4px 0 20px rgba(0,0,0,0.15)",
496
+ display: "flex", flexDirection: "column",
497
+ }}>
498
+ <div style={{ display: "flex", justifyContent: "space-between", padding: "12px", borderBottom: "1px solid #eee" }}>
499
+ <span style={{ fontWeight: 600 }}>Chat</span>
500
+ <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer" }}>X</button>
501
+ </div>
502
+ {user && (
503
+ <>
504
+ <CometChatMessageHeader user={user} />
505
+ <div style={{ flex: 1, overflow: "hidden" }}>
506
+ <CometChatMessageList user={user} />
507
+ </div>
508
+ <CometChatMessageComposer user={user} />
509
+ </>
510
+ )}
511
+ </div>
512
+ </>
513
+ );
514
+ }
515
+ ```
516
+
517
+ **Mounting the drawer:** The drawer component has `"use client"`, so it can be imported from either Server or Client Components. Import it in the layout or any page:
518
+
519
+ ```tsx
520
+ // In a Server Component layout -- this works because ChatDrawer is "use client"
521
+ import { ChatDrawer } from "../components/ChatDrawer";
522
+
523
+ // But state management (isOpen) must be in a Client Component.
524
+ // Option 1: wrap in a small client component
525
+ // Option 2: use a client-side context for drawer state
526
+ ```
527
+
528
+ For state lifting across the Server/Client boundary, create a small Client Component wrapper:
529
+
530
+ ```tsx
531
+ // components/ChatDrawerTrigger.tsx
532
+ "use client";
533
+
534
+ import { useState } from "react";
535
+ import { ChatDrawer } from "./ChatDrawer";
536
+
537
+ export function ChatDrawerTrigger({ targetUserId }: { targetUserId: string }) {
538
+ const [isOpen, setIsOpen] = useState(false);
539
+
540
+ return (
541
+ <>
542
+ <button onClick={() => setIsOpen(true)}>Message</button>
543
+ <ChatDrawer isOpen={isOpen} onClose={() => setIsOpen(false)} targetUserId={targetUserId} />
544
+ </>
545
+ );
546
+ }
547
+ ```
548
+
549
+ ### Pages Router
550
+
551
+ Use `dynamic` import for the drawer/modal component:
552
+
553
+ ```tsx
554
+ import dynamic from "next/dynamic";
555
+
556
+ const ChatDrawer = dynamic(() => import("../components/ChatDrawer").then(m => m.ChatDrawer), {
557
+ ssr: false,
558
+ });
559
+ ```
560
+
561
+ See `cometchat-placement` for complete modal and drawer implementations.
562
+
563
+ ---
564
+
565
+ ## 8. API route for production auth
566
+
567
+ Next.js can serve as both frontend and backend. Use an API route to generate CometChat auth tokens server-side.
568
+
569
+ ### App Router API route
570
+
571
+ ```tsx
572
+ // app/api/cometchat-token/route.ts
573
+ import { NextRequest, NextResponse } from "next/server";
574
+
575
+ const COMETCHAT_APP_ID = process.env.COMETCHAT_APP_ID!; // server-only, no NEXT_PUBLIC_ prefix
576
+ const COMETCHAT_REGION = process.env.COMETCHAT_REGION!; // server-only
577
+ const COMETCHAT_AUTH_TOKEN = process.env.COMETCHAT_AUTH_TOKEN!; // server-only secret
578
+
579
+ export async function POST(request: NextRequest) {
580
+ try {
581
+ const { uid } = await request.json();
582
+
583
+ if (!uid || typeof uid !== "string") {
584
+ return NextResponse.json({ error: "uid is required" }, { status: 400 });
585
+ }
586
+
587
+ const response = await fetch(
588
+ `https://${COMETCHAT_APP_ID}.api-${COMETCHAT_REGION}.cometchat.io/v3/users/${uid}/auth_tokens`,
589
+ {
590
+ method: "POST",
591
+ headers: {
592
+ "Content-Type": "application/json",
593
+ apiKey: COMETCHAT_AUTH_TOKEN,
594
+ appId: COMETCHAT_APP_ID,
595
+ },
596
+ body: JSON.stringify({}),
597
+ }
598
+ );
599
+
600
+ if (!response.ok) {
601
+ const error = await response.text();
602
+ return NextResponse.json({ error }, { status: response.status });
603
+ }
604
+
605
+ const data = await response.json();
606
+ return NextResponse.json({ token: data.data.authToken });
607
+ } catch (error) {
608
+ return NextResponse.json({ error: String(error) }, { status: 500 });
609
+ }
610
+ }
611
+ ```
612
+
613
+ ### Pages Router API route
614
+
615
+ ```tsx
616
+ // pages/api/cometchat-token.ts
617
+ import type { NextApiRequest, NextApiResponse } from "next";
618
+
619
+ const COMETCHAT_APP_ID = process.env.COMETCHAT_APP_ID!;
620
+ const COMETCHAT_REGION = process.env.COMETCHAT_REGION!;
621
+ const COMETCHAT_AUTH_TOKEN = process.env.COMETCHAT_AUTH_TOKEN!;
622
+
623
+ export default async function handler(req: NextApiRequest, res: NextApiResponse) {
624
+ if (req.method !== "POST") {
625
+ return res.status(405).json({ error: "Method not allowed" });
626
+ }
627
+
628
+ try {
629
+ const { uid } = req.body;
630
+
631
+ if (!uid || typeof uid !== "string") {
632
+ return res.status(400).json({ error: "uid is required" });
633
+ }
634
+
635
+ const response = await fetch(
636
+ `https://${COMETCHAT_APP_ID}.api-${COMETCHAT_REGION}.cometchat.io/v3/users/${uid}/auth_tokens`,
637
+ {
638
+ method: "POST",
639
+ headers: {
640
+ "Content-Type": "application/json",
641
+ apiKey: COMETCHAT_AUTH_TOKEN,
642
+ appId: COMETCHAT_APP_ID,
643
+ },
644
+ body: JSON.stringify({}),
645
+ }
646
+ );
647
+
648
+ if (!response.ok) {
649
+ const error = await response.text();
650
+ return res.status(response.status).json({ error });
651
+ }
652
+
653
+ const data = await response.json();
654
+ return res.status(200).json({ token: data.data.authToken });
655
+ } catch (error) {
656
+ return res.status(500).json({ error: String(error) });
657
+ }
658
+ }
659
+ ```
660
+
661
+ ### Environment variables for the API route
662
+
663
+ Add server-only variables to `.env.local` (no `NEXT_PUBLIC_` prefix -- these must NOT be exposed to the browser):
664
+
665
+ ```env
666
+ # .env.local -- server-only (no NEXT_PUBLIC_ prefix)
667
+ COMETCHAT_APP_ID=your_app_id
668
+ COMETCHAT_REGION=us
669
+ COMETCHAT_AUTH_TOKEN=your_server_auth_token
670
+
671
+ # Client-side (NEXT_PUBLIC_ prefix)
672
+ NEXT_PUBLIC_COMETCHAT_APP_ID=your_app_id
673
+ NEXT_PUBLIC_COMETCHAT_REGION=us
674
+ NEXT_PUBLIC_COMETCHAT_AUTH_KEY=your_client_auth_key
675
+ ```
676
+
677
+ **Note:** `COMETCHAT_AUTH_TOKEN` (server secret) and `COMETCHAT_AUTH_KEY` (client key) are different values from the CometChat dashboard. The auth token has higher privileges. Never prefix it with `NEXT_PUBLIC_`.
678
+
679
+ ---
680
+
681
+ ## 9. Environment variables
682
+
683
+ ### Next.js env var conventions
684
+
685
+ | Variable | Prefix | Accessible from | File |
686
+ |---|---|---|---|
687
+ | Client-side vars | `NEXT_PUBLIC_` | Browser + Server | `.env.local` |
688
+ | Server-only vars | None | Server only (API routes, Server Components) | `.env.local` |
689
+
690
+ ### .env.local file
691
+
692
+ ```env
693
+ NEXT_PUBLIC_COMETCHAT_APP_ID=your_app_id
694
+ NEXT_PUBLIC_COMETCHAT_REGION=us
695
+ NEXT_PUBLIC_COMETCHAT_AUTH_KEY=your_auth_key
696
+ ```
697
+
698
+ **Access in client code:** `process.env.NEXT_PUBLIC_COMETCHAT_APP_ID`
699
+
700
+ **Important:** `.env.local` is gitignored by default in Next.js. Unlike Vite, you do not need to manually add it to `.gitignore`.
701
+
702
+ ---
703
+
704
+ ## 10. CSS import
705
+
706
+ ### App Router
707
+
708
+ Import in `app/globals.css` or `app/layout.tsx`:
709
+
710
+ ```css
711
+ /* app/globals.css */
712
+ @import "@cometchat/chat-uikit-react/css-variables.css";
713
+
714
+ /* your styles below */
715
+ ```
716
+
717
+ Or as a JS import in the root layout:
718
+
719
+ ```tsx
720
+ // app/layout.tsx
721
+ import "@cometchat/chat-uikit-react/css-variables.css";
722
+ import "./globals.css";
723
+ ```
724
+
725
+ ### Pages Router
726
+
727
+ Import in `pages/_app.tsx` or `styles/globals.css`:
728
+
729
+ ```tsx
730
+ // pages/_app.tsx
731
+ import "@cometchat/chat-uikit-react/css-variables.css";
732
+ import "../styles/globals.css";
733
+ ```
734
+
735
+ ---
736
+
737
+ ## 11. Common pitfalls
738
+
739
+ ### Missing "use client"
740
+
741
+ **Symptom:** `ReferenceError: window is not defined` or `ReferenceError: document is not defined` during build or at runtime.
742
+
743
+ **Cause:** A file imports from `@cometchat/chat-uikit-react` without `"use client"` at the top. Next.js tries to render it on the server.
744
+
745
+ **Fix:** Add `"use client"` as the first line of the file.
746
+
747
+ ### Server/client code mixing
748
+
749
+ **Symptom:** Build errors about `next/headers`, `cookies()`, or `generateMetadata` in the same file as CometChat imports.
750
+
751
+ **Cause:** Server-only APIs and client-only APIs cannot coexist in the same file. CometChat requires `"use client"`, but `next/headers` and `cookies()` are server-only.
752
+
753
+ **Fix:** Split the file. Keep server logic in a Server Component; keep CometChat in a separate `"use client"` component that the Server Component imports.
754
+
755
+ ```tsx
756
+ // app/messages/page.tsx (Server Component -- does data fetching)
757
+ import { cookies } from "next/headers";
758
+ import dynamic from "next/dynamic";
759
+
760
+ const ChatView = dynamic(() => import("../../components/ChatView"), { ssr: false });
761
+
762
+ export default async function MessagesPage() {
763
+ const session = cookies().get("session"); // server-only
764
+ if (!session) redirect("/login");
765
+
766
+ return <ChatView />;
767
+ }
768
+ ```
769
+
770
+ ### Image optimization
771
+
772
+ CometChat renders avatars and media images via its own components. These do not conflict with `next/image`. Do not try to replace CometChat's internal images with `next/image` -- they are managed by the SDK.
773
+
774
+ ### Middleware
775
+
776
+ CometChat has no middleware requirements. Do not add CometChat-related middleware. If the project has auth middleware (e.g., protecting routes), just ensure the chat route is behind the same auth as the rest of the app.
777
+
778
+ ### ISR/SSG pages with chat
779
+
780
+ If a page uses static generation (`generateStaticParams`) or ISR, you can still add chat. Wrap the CometChat components in a Client Component. The page's static HTML ships without chat, and the Client Component hydrates and renders chat in the browser:
781
+
782
+ ```tsx
783
+ // app/products/[id]/page.tsx
784
+ export async function generateStaticParams() {
785
+ // ... returns product IDs for static generation
786
+ }
787
+
788
+ export default async function ProductPage({ params }: { params: { id: string } }) {
789
+ const product = await getProduct(params.id);
790
+
791
+ return (
792
+ <div>
793
+ <h1>{product.name}</h1>
794
+ <p>{product.description}</p>
795
+ {/* ChatPanel is "use client" -- renders only in the browser */}
796
+ <ChatPanel targetUserId={product.sellerId} />
797
+ </div>
798
+ );
799
+ }
800
+ ```
801
+
802
+ ### Turbopack
803
+
804
+ Next.js's Turbopack (dev mode with `next dev --turbo`) works with CometChat. No special configuration needed. If you encounter issues, fall back to the standard Webpack dev server (`next dev` without `--turbo`).
805
+
806
+ ### Pages Router: do NOT use CometChat from `getServerSideProps` / `getStaticProps` / `getInitialProps`
807
+
808
+ **Symptom:** `ReferenceError: window is not defined` or cryptic SDK errors during `next build` or page rendering.
809
+
810
+ **Cause:** The CometChat client SDK needs the browser (localStorage, WebSocket, etc.) and a logged-in user session. It cannot run inside `getServerSideProps`, `getStaticProps`, or `getInitialProps` — those execute on the Node.js server before the browser has hydrated.
811
+
812
+ **Fix:** Do chat-related work in client components only. If you need to pre-seed a conversation from server data, pass just the primitive IDs (user UID, group GUID) as page props and let the client component fetch the CometChat entity on mount:
813
+
814
+ ```tsx
815
+ // pages/products/[id].tsx — server-side data fetch, no CometChat
816
+ export async function getServerSideProps({ params }) {
817
+ const product = await fetchProduct(params.id);
818
+ return { props: { product } }; // pass sellerId as string, not a CometChat.User
819
+ }
820
+
821
+ export default function ProductPage({ product }) {
822
+ return (
823
+ <>
824
+ <h1>{product.name}</h1>
825
+ <ChatWithSeller sellerUid={product.sellerId} /> {/* client component */}
826
+ </>
827
+ );
828
+ }
829
+ ```
830
+
831
+ ### Pages Router: `_document.tsx` doesn't need CometChat changes
832
+
833
+ If the project has a custom `pages/_document.tsx` for font preloading or third-party SSR CSS injection, leave it alone. CometChat CSS variables are client-side only — they don't need `_document.tsx` integration. Mount the CSS import in `_app.tsx` as shown in section 10; `_document.tsx` is the wrong layer.
834
+
835
+ ---
836
+
837
+ ## 12. Complete integration checklist (App Router)
838
+
839
+ 1. Install packages: `npm install @cometchat/chat-uikit-react @cometchat/chat-sdk-javascript`
840
+ 2. Create `.env.local` with `NEXT_PUBLIC_COMETCHAT_APP_ID`, `NEXT_PUBLIC_COMETCHAT_REGION`, `NEXT_PUBLIC_COMETCHAT_AUTH_KEY`
841
+ 3. Import `@cometchat/chat-uikit-react/css-variables.css` in `app/globals.css`
842
+ 4. Create `app/providers/CometChatProvider.tsx` with `"use client"` (section 3)
843
+ 5. Mount `CometChatProvider` in `app/layout.tsx` wrapping `{children}`
844
+ 6. Create `app/messages/page.tsx` with `"use client"` (section 5)
845
+ 7. Add a `<Link href="/messages">Messages</Link>` to the layout's nav
846
+ 8. Verify: `npm run build` should succeed without SSR errors
847
+
848
+ ## 13. Complete integration checklist (Pages Router)
849
+
850
+ 1. Install packages: `npm install @cometchat/chat-uikit-react @cometchat/chat-sdk-javascript`
851
+ 2. Create `.env.local` with `NEXT_PUBLIC_COMETCHAT_APP_ID`, `NEXT_PUBLIC_COMETCHAT_REGION`, `NEXT_PUBLIC_COMETCHAT_AUTH_KEY`
852
+ 3. Import `@cometchat/chat-uikit-react/css-variables.css` in `pages/_app.tsx`
853
+ 4. Create `components/CometChatProvider.tsx` (section 3 code, without `"use client"`)
854
+ 5. Dynamically import `CometChatProvider` in `pages/_app.tsx` with `ssr: false` (section 4)
855
+ 6. Create `pages/messages.tsx` with dynamic import (section 6)
856
+ 7. Add a `<Link href="/messages">Messages</Link>` to the layout's nav
857
+ 8. Verify: `npm run build` should succeed without SSR errors