@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,960 @@
1
+ ---
2
+ name: cometchat-production
3
+ description: "Production readiness for CometChat — server-side token auth, user management CRUD, environment hardening, and security checklist. Replaces dev-mode authKey with server-side tokens."
4
+ license: "MIT"
5
+ compatibility: "Node.js >=18; @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: "cometchat production auth token security user-management rest-api"
11
+ ---
12
+
13
+ ## Purpose
14
+
15
+ This skill teaches Claude how to harden a CometChat integration for production. It covers two critical areas:
16
+
17
+ 1. **Token-based authentication** — replacing client-side `authKey` with server-side token generation
18
+ 2. **User management** — server-side CRUD for CometChat users (create on signup, update on profile change, delete on account deletion)
19
+
20
+ The `cometchat-core` skill's provider pattern supports both dev mode (`login(uid)`) and production mode (`loginWithAuthToken(token)`). This skill provides the server-side half: the token endpoint and user management endpoints.
21
+
22
+ ---
23
+
24
+ ## 1. Why production auth matters
25
+
26
+ In development mode, `CometChatUIKit.login(uid)` uses the `authKey` configured via `UIKitSettingsBuilder.setAuthKey()`. This key is embedded in your client-side JavaScript bundle. Anyone can open browser DevTools, find the auth key, and use it to log in as ANY user in your CometChat app. They can read private messages, send messages as other users, and access every conversation.
27
+
28
+ Production deployments MUST use server-side token generation. The auth key stays on your server. Clients receive short-lived tokens scoped to a single user. If a token leaks, the blast radius is one user session, not your entire app.
29
+
30
+ ---
31
+
32
+ ## 2. The token auth pattern
33
+
34
+ The production auth flow has four steps:
35
+
36
+ 1. **Client authenticates with YOUR auth system.** The user logs into your app using your existing login flow (email/password, OAuth, magic link, etc.). This step has nothing to do with CometChat.
37
+
38
+ 2. **Your server calls the CometChat REST API.** After verifying the user's identity, your server makes a POST request to CometChat's token endpoint using the REST API key (a server-only secret). CometChat returns an auth token for that specific user.
39
+
40
+ 3. **Client receives the token.** Your server sends the auth token back to the client in the API response.
41
+
42
+ 4. **Client calls `CometChatUIKit.loginWithAuthToken(token)`.** The CometChat SDK uses the token to establish a session. The auth key NEVER touches the browser.
43
+
44
+ ```
45
+ ┌─────────┐ 1. Login ┌──────────┐ 2. POST /v3/users/{uid}/auth_tokens ┌──────────────┐
46
+ │ Client │ ───────────────→ │ Your │ ──────────────────────────────────────→ │ CometChat │
47
+ │ (Browser)│ │ Server │ ←────────────────────────────────────── │ REST API │
48
+ │ │ ←─────────────── │ │ { authToken: "..." } │ │
49
+ │ │ 3. auth token │ │ │ │
50
+ │ │ └──────────┘ └──────────────┘
51
+ │ │
52
+ │ 4. CometChatUIKit.loginWithAuthToken(token)
53
+ └─────────┘
54
+ ```
55
+
56
+ ---
57
+
58
+ ## 3. Server endpoint implementations
59
+
60
+ Each endpoint does the same thing:
61
+ 1. Receives a user UID (from the authenticated session, NOT from the request body in production)
62
+ 2. Validates that the caller is authenticated
63
+ 3. POSTs to `https://{APP_ID}.api-{REGION}.cometchat.io/v3/users/{uid}/auth_tokens`
64
+ 4. Returns the auth token to the client
65
+
66
+ The CometChat REST API requires two headers:
67
+ - `appId` — your CometChat app ID
68
+ - `apiKey` — a **REST API Key** (NOT the Auth Key used in dev mode)
69
+
70
+ **Auth Key vs REST API Key — these are different keys:**
71
+
72
+ | Key type | Where to find | Purpose | Security |
73
+ |---|---|---|---|
74
+ | **Auth Key** | Dashboard → Your App → API & Auth Keys → "Auth Keys" table | Client-side SDK: `CometChatUIKit.login(uid)` in dev mode | Exposed in browser. Dev only. |
75
+ | **REST API Key** | Dashboard → Your App → API & Auth Keys → "Rest API Keys" table | Server-to-server: token generation, user CRUD, message send | Server only. Never expose to client. |
76
+
77
+ The `.env` should have both for production:
78
+ ```env
79
+ # Client-side (prefixed for the framework)
80
+ VITE_COMETCHAT_APP_ID=your_app_id
81
+ VITE_COMETCHAT_REGION=us
82
+
83
+ # Server-side (no prefix — never exposed to the client)
84
+ COMETCHAT_APP_ID=your_app_id
85
+ COMETCHAT_REGION=us
86
+ COMETCHAT_REST_API_KEY=your_rest_api_key
87
+ ```
88
+
89
+ If the user only has an Auth Key, tell them to create a REST API Key in the dashboard: **API & Auth Keys → Rest API Keys → Add Key.**
90
+
91
+ ### Next.js App Router
92
+
93
+ `app/api/cometchat-token/route.ts`
94
+
95
+ ```typescript
96
+ import { NextRequest, NextResponse } from "next/server";
97
+
98
+ const APP_ID = process.env.COMETCHAT_APP_ID!;
99
+ const REGION = process.env.COMETCHAT_REGION!;
100
+ const REST_API_KEY = process.env.COMETCHAT_REST_API_KEY!;
101
+
102
+ export async function POST(request: NextRequest) {
103
+ // TODO: Replace this with your real auth check.
104
+ // Example with NextAuth: const session = await getServerSession(authOptions);
105
+ // Example with Clerk: const { userId } = auth();
106
+ // If not authenticated, return 401.
107
+ const body = await request.json();
108
+ const uid = body.uid as string;
109
+
110
+ if (!uid || typeof uid !== "string") {
111
+ return NextResponse.json({ error: "Missing uid" }, { status: 400 });
112
+ }
113
+
114
+ // In production, derive UID from the authenticated session, not from
115
+ // the request body. The body approach is shown here as a starting point.
116
+ // Example: const uid = session.user.id;
117
+
118
+ const response = await fetch(
119
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}/auth_tokens`,
120
+ {
121
+ method: "POST",
122
+ headers: {
123
+ "Content-Type": "application/json",
124
+ appId: APP_ID,
125
+ apiKey: REST_API_KEY,
126
+ },
127
+ body: JSON.stringify({}),
128
+ }
129
+ );
130
+
131
+ if (!response.ok) {
132
+ const error = await response.text();
133
+ console.error("CometChat token error:", error);
134
+ return NextResponse.json(
135
+ { error: "Failed to generate auth token" },
136
+ { status: response.status }
137
+ );
138
+ }
139
+
140
+ const data = await response.json();
141
+ return NextResponse.json({ authToken: data.data.authToken });
142
+ }
143
+ ```
144
+
145
+ ### Next.js Pages Router
146
+
147
+ `pages/api/cometchat-token.ts`
148
+
149
+ ```typescript
150
+ import type { NextApiRequest, NextApiResponse } from "next";
151
+
152
+ const APP_ID = process.env.COMETCHAT_APP_ID!;
153
+ const REGION = process.env.COMETCHAT_REGION!;
154
+ const REST_API_KEY = process.env.COMETCHAT_REST_API_KEY!;
155
+
156
+ export default async function handler(
157
+ req: NextApiRequest,
158
+ res: NextApiResponse
159
+ ) {
160
+ if (req.method !== "POST") {
161
+ return res.status(405).json({ error: "Method not allowed" });
162
+ }
163
+
164
+ // TODO: Replace with your auth check (e.g., getServerSession, Clerk, JWT).
165
+ const { uid } = req.body;
166
+
167
+ if (!uid || typeof uid !== "string") {
168
+ return res.status(400).json({ error: "Missing uid" });
169
+ }
170
+
171
+ const response = await fetch(
172
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}/auth_tokens`,
173
+ {
174
+ method: "POST",
175
+ headers: {
176
+ "Content-Type": "application/json",
177
+ appId: APP_ID,
178
+ apiKey: REST_API_KEY,
179
+ },
180
+ body: JSON.stringify({}),
181
+ }
182
+ );
183
+
184
+ if (!response.ok) {
185
+ const error = await response.text();
186
+ console.error("CometChat token error:", error);
187
+ return res.status(response.status).json({ error: "Failed to generate auth token" });
188
+ }
189
+
190
+ const data = await response.json();
191
+ return res.status(200).json({ authToken: data.data.authToken });
192
+ }
193
+ ```
194
+
195
+ ### React Router v7 (framework mode)
196
+
197
+ In React Router framework mode, server logic lives in `action` functions within route modules. Create a resource route (no UI) for the token endpoint.
198
+
199
+ `app/routes/api.cometchat-token.ts`
200
+
201
+ ```typescript
202
+ import type { ActionFunctionArgs } from "react-router";
203
+
204
+ const APP_ID = process.env.COMETCHAT_APP_ID!;
205
+ const REGION = process.env.COMETCHAT_REGION!;
206
+ const REST_API_KEY = process.env.COMETCHAT_REST_API_KEY!;
207
+
208
+ export async function action({ request }: ActionFunctionArgs) {
209
+ if (request.method !== "POST") {
210
+ return new Response("Method not allowed", { status: 405 });
211
+ }
212
+
213
+ // TODO: Replace with your auth check (e.g., session cookie, JWT).
214
+ const body = await request.json();
215
+ const uid = body.uid as string;
216
+
217
+ if (!uid || typeof uid !== "string") {
218
+ return Response.json({ error: "Missing uid" }, { status: 400 });
219
+ }
220
+
221
+ const response = await fetch(
222
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}/auth_tokens`,
223
+ {
224
+ method: "POST",
225
+ headers: {
226
+ "Content-Type": "application/json",
227
+ appId: APP_ID,
228
+ apiKey: REST_API_KEY,
229
+ },
230
+ body: JSON.stringify({}),
231
+ }
232
+ );
233
+
234
+ if (!response.ok) {
235
+ const error = await response.text();
236
+ console.error("CometChat token error:", error);
237
+ return Response.json(
238
+ { error: "Failed to generate auth token" },
239
+ { status: response.status }
240
+ );
241
+ }
242
+
243
+ const data = await response.json();
244
+ return Response.json({ authToken: data.data.authToken });
245
+ }
246
+ ```
247
+
248
+ Register this route in your `routes.ts` (or `app/routes.ts`):
249
+
250
+ ```typescript
251
+ // Add to your route config:
252
+ route("api/cometchat-token", "routes/api.cometchat-token.ts"),
253
+ ```
254
+
255
+ ### Express / Hono standalone (React + Vite projects)
256
+
257
+ React/Vite projects have no built-in server. You need a separate backend. Here are patterns for the two most common choices.
258
+
259
+ **Express:**
260
+
261
+ ```typescript
262
+ // server/index.ts (or server.js)
263
+ import express from "express";
264
+ import cors from "cors";
265
+
266
+ const app = express();
267
+ app.use(cors({ origin: "http://localhost:5173" })); // Your Vite dev server
268
+ app.use(express.json());
269
+
270
+ const APP_ID = process.env.COMETCHAT_APP_ID!;
271
+ const REGION = process.env.COMETCHAT_REGION!;
272
+ const REST_API_KEY = process.env.COMETCHAT_REST_API_KEY!;
273
+
274
+ app.post("/api/cometchat-token", async (req, res) => {
275
+ // TODO: Replace with your auth check.
276
+ const { uid } = req.body;
277
+
278
+ if (!uid || typeof uid !== "string") {
279
+ return res.status(400).json({ error: "Missing uid" });
280
+ }
281
+
282
+ const response = await fetch(
283
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}/auth_tokens`,
284
+ {
285
+ method: "POST",
286
+ headers: {
287
+ "Content-Type": "application/json",
288
+ appId: APP_ID,
289
+ apiKey: REST_API_KEY,
290
+ },
291
+ body: JSON.stringify({}),
292
+ }
293
+ );
294
+
295
+ if (!response.ok) {
296
+ const error = await response.text();
297
+ console.error("CometChat token error:", error);
298
+ return res.status(response.status).json({ error: "Failed to generate auth token" });
299
+ }
300
+
301
+ const data = await response.json();
302
+ return res.json({ authToken: data.data.authToken });
303
+ });
304
+
305
+ app.listen(3001, () => console.log("Server running on :3001"));
306
+ ```
307
+
308
+ **Hono:**
309
+
310
+ ```typescript
311
+ // server/index.ts
312
+ import { Hono } from "hono";
313
+ import { cors } from "hono/cors";
314
+ import { serve } from "@hono/node-server";
315
+
316
+ const app = new Hono();
317
+ app.use("/*", cors({ origin: "http://localhost:5173" }));
318
+
319
+ const APP_ID = process.env.COMETCHAT_APP_ID!;
320
+ const REGION = process.env.COMETCHAT_REGION!;
321
+ const REST_API_KEY = process.env.COMETCHAT_REST_API_KEY!;
322
+
323
+ app.post("/api/cometchat-token", async (c) => {
324
+ // TODO: Replace with your auth check.
325
+ const { uid } = await c.req.json();
326
+
327
+ if (!uid || typeof uid !== "string") {
328
+ return c.json({ error: "Missing uid" }, 400);
329
+ }
330
+
331
+ const response = await fetch(
332
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}/auth_tokens`,
333
+ {
334
+ method: "POST",
335
+ headers: {
336
+ "Content-Type": "application/json",
337
+ appId: APP_ID,
338
+ apiKey: REST_API_KEY,
339
+ },
340
+ body: JSON.stringify({}),
341
+ }
342
+ );
343
+
344
+ if (!response.ok) {
345
+ const error = await response.text();
346
+ console.error("CometChat token error:", error);
347
+ return c.json({ error: "Failed to generate auth token" }, { status: response.status });
348
+ }
349
+
350
+ const data = await response.json();
351
+ return c.json({ authToken: data.data.authToken });
352
+ });
353
+
354
+ serve({ fetch: app.fetch, port: 3001 });
355
+ ```
356
+
357
+ ### Astro
358
+
359
+ `src/pages/api/cometchat-token.ts`
360
+
361
+ Astro SSR endpoints work in hybrid or server mode. Make sure your `astro.config.mjs` has `output: "server"` or `output: "hybrid"`.
362
+
363
+ ```typescript
364
+ import type { APIRoute } from "astro";
365
+
366
+ const APP_ID = import.meta.env.COMETCHAT_APP_ID;
367
+ const REGION = import.meta.env.COMETCHAT_REGION;
368
+ const REST_API_KEY = import.meta.env.COMETCHAT_REST_API_KEY;
369
+
370
+ export const POST: APIRoute = async ({ request }) => {
371
+ // TODO: Replace with your auth check (e.g., session cookie, Astro middleware).
372
+ const body = await request.json();
373
+ const uid = body.uid as string;
374
+
375
+ if (!uid || typeof uid !== "string") {
376
+ return new Response(JSON.stringify({ error: "Missing uid" }), {
377
+ status: 400,
378
+ headers: { "Content-Type": "application/json" },
379
+ });
380
+ }
381
+
382
+ const response = await fetch(
383
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}/auth_tokens`,
384
+ {
385
+ method: "POST",
386
+ headers: {
387
+ "Content-Type": "application/json",
388
+ appId: APP_ID,
389
+ apiKey: REST_API_KEY,
390
+ },
391
+ body: JSON.stringify({}),
392
+ }
393
+ );
394
+
395
+ if (!response.ok) {
396
+ const error = await response.text();
397
+ console.error("CometChat token error:", error);
398
+ return new Response(
399
+ JSON.stringify({ error: "Failed to generate auth token" }),
400
+ { status: response.status, headers: { "Content-Type": "application/json" } }
401
+ );
402
+ }
403
+
404
+ const data = await response.json();
405
+ return new Response(JSON.stringify({ authToken: data.data.authToken }), {
406
+ status: 200,
407
+ headers: { "Content-Type": "application/json" },
408
+ });
409
+ };
410
+ ```
411
+
412
+ ---
413
+
414
+ ## 4. Client-side changes
415
+
416
+ The `cometchat-core` skill's `CometChatProvider` already supports both `authKey` (dev) and `authToken` (production) props. To switch to production mode:
417
+
418
+ ### Step 1 — Create a hook to fetch the token
419
+
420
+ ```typescript
421
+ // hooks/useCometChatToken.ts
422
+ "use client"; // Required for Next.js App Router; harmless elsewhere
423
+
424
+ import { useState, useEffect } from "react";
425
+
426
+ /**
427
+ * Fetches a CometChat auth token from your server-side endpoint.
428
+ * Call this after the user is authenticated in your app.
429
+ */
430
+ export function useCometChatToken(uid: string | null) {
431
+ const [token, setToken] = useState<string | null>(null);
432
+ const [error, setError] = useState<string | null>(null);
433
+ const [loading, setLoading] = useState(false);
434
+
435
+ useEffect(() => {
436
+ if (!uid) return;
437
+
438
+ let cancelled = false;
439
+ setLoading(true);
440
+
441
+ fetch("/api/cometchat-token", {
442
+ method: "POST",
443
+ headers: { "Content-Type": "application/json" },
444
+ body: JSON.stringify({ uid }),
445
+ })
446
+ .then((res) => {
447
+ if (!res.ok) throw new Error(`Token request failed: ${res.status}`);
448
+ return res.json();
449
+ })
450
+ .then((data) => {
451
+ if (!cancelled) {
452
+ setToken(data.authToken);
453
+ setLoading(false);
454
+ }
455
+ })
456
+ .catch((err) => {
457
+ if (!cancelled) {
458
+ setError(String(err));
459
+ setLoading(false);
460
+ }
461
+ });
462
+
463
+ return () => {
464
+ cancelled = true;
465
+ };
466
+ }, [uid]);
467
+
468
+ return { token, error, loading };
469
+ }
470
+ ```
471
+
472
+ ### Step 2 — Update the CometChatProvider usage
473
+
474
+ **Before (dev mode):**
475
+
476
+ ```typescript
477
+ <CometChatProvider
478
+ appId={import.meta.env.VITE_COMETCHAT_APP_ID}
479
+ region={import.meta.env.VITE_COMETCHAT_REGION}
480
+ authKey={import.meta.env.VITE_COMETCHAT_AUTH_KEY}
481
+ uid="cometchat-uid-1"
482
+ >
483
+ <ChatPage />
484
+ </CometChatProvider>
485
+ ```
486
+
487
+ **After (production mode):**
488
+
489
+ ```typescript
490
+ function ChatWrapper() {
491
+ // Get the authenticated user's ID from your auth system
492
+ const { user } = useAuth(); // Your auth hook (NextAuth, Clerk, Supabase, etc.)
493
+ const { token, error, loading } = useCometChatToken(user?.id ?? null);
494
+
495
+ if (!user) return <LoginPage />;
496
+ if (loading) return <div>Connecting to chat...</div>;
497
+ if (error) return <div>Chat connection failed: {error}</div>;
498
+
499
+ return (
500
+ <CometChatProvider
501
+ appId={import.meta.env.VITE_COMETCHAT_APP_ID}
502
+ region={import.meta.env.VITE_COMETCHAT_REGION}
503
+ authToken={token!}
504
+ uid={user.id}
505
+ >
506
+ <ChatPage />
507
+ </CometChatProvider>
508
+ );
509
+ }
510
+ ```
511
+
512
+ Key changes:
513
+ - Removed `authKey` prop entirely
514
+ - Added `authToken` prop with the token from your server
515
+ - `uid` comes from your auth system, not a hardcoded test user
516
+ - The provider only renders after the token is fetched
517
+
518
+ ### Step 3 — Handle token refresh on 401
519
+
520
+ CometChat auth tokens expire. When a token expires, SDK calls will fail. Handle this in your provider:
521
+
522
+ ```typescript
523
+ // In your CometChatProvider or a wrapper:
524
+ import { CometChat } from "@cometchat/chat-sdk-javascript";
525
+
526
+ // Listen for auth errors
527
+ CometChat.addConnectionListener(
528
+ "auth-refresh-listener",
529
+ new CometChat.ConnectionListener({
530
+ onDisconnected: () => {
531
+ console.log("CometChat disconnected — token may have expired");
532
+ // Re-fetch token from your endpoint and call loginWithAuthToken again
533
+ },
534
+ })
535
+ );
536
+ ```
537
+
538
+ A simpler approach: if any CometChat operation returns a 401 or auth error, re-fetch the token and call `CometChatUIKit.loginWithAuthToken(newToken)`.
539
+
540
+ **Guard refresh calls with the same concurrency pattern.** If two components both see a 401 at the same time, two `loginWithAuthToken` calls race and the SDK throws *"Please wait until the previous login request ends."* Route token refresh through the same `ensureLoggedIn(uid, authToken)` helper defined in `cometchat-core`'s provider pattern — the module-level `loginInFlight` promise dedupes concurrent refreshes automatically.
541
+
542
+ ---
543
+
544
+ ## 5. User management patterns
545
+
546
+ In production, you need to keep CometChat users in sync with your app's users. CometChat users are managed via the REST API using the REST API key (server-only).
547
+
548
+ ### Create user — on signup
549
+
550
+ When a user signs up for your app, create a corresponding CometChat user.
551
+
552
+ ```typescript
553
+ // Server-side utility function
554
+ async function createCometChatUser(uid: string, name: string, avatar?: string) {
555
+ const response = await fetch(
556
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users`,
557
+ {
558
+ method: "POST",
559
+ headers: {
560
+ "Content-Type": "application/json",
561
+ appId: APP_ID,
562
+ apiKey: REST_API_KEY,
563
+ },
564
+ body: JSON.stringify({
565
+ uid,
566
+ name,
567
+ ...(avatar ? { avatar } : {}),
568
+ }),
569
+ }
570
+ );
571
+
572
+ if (!response.ok) {
573
+ const error = await response.json();
574
+ // If user already exists (409), that's OK — just log it
575
+ if (response.status === 409) {
576
+ console.log(`CometChat user ${uid} already exists`);
577
+ return;
578
+ }
579
+ throw new Error(`Failed to create CometChat user: ${JSON.stringify(error)}`);
580
+ }
581
+ }
582
+ ```
583
+
584
+ ### Update user — on profile change
585
+
586
+ When a user updates their name or avatar in your app, update the CometChat user.
587
+
588
+ ```typescript
589
+ async function updateCometChatUser(
590
+ uid: string,
591
+ updates: { name?: string; avatar?: string; metadata?: Record<string, unknown> }
592
+ ) {
593
+ const response = await fetch(
594
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}`,
595
+ {
596
+ method: "PUT",
597
+ headers: {
598
+ "Content-Type": "application/json",
599
+ appId: APP_ID,
600
+ apiKey: REST_API_KEY,
601
+ },
602
+ body: JSON.stringify(updates),
603
+ }
604
+ );
605
+
606
+ if (!response.ok) {
607
+ const error = await response.json();
608
+ throw new Error(`Failed to update CometChat user: ${JSON.stringify(error)}`);
609
+ }
610
+ }
611
+ ```
612
+
613
+ ### Delete user — on account deletion
614
+
615
+ When a user deletes their account, delete the CometChat user.
616
+
617
+ ```typescript
618
+ async function deleteCometChatUser(uid: string) {
619
+ const response = await fetch(
620
+ `https://${APP_ID}.api-${REGION}.cometchat.io/v3/users/${encodeURIComponent(uid)}`,
621
+ {
622
+ method: "DELETE",
623
+ headers: {
624
+ "Content-Type": "application/json",
625
+ appId: APP_ID,
626
+ apiKey: REST_API_KEY,
627
+ },
628
+ }
629
+ );
630
+
631
+ if (!response.ok) {
632
+ const error = await response.json();
633
+ throw new Error(`Failed to delete CometChat user: ${JSON.stringify(error)}`);
634
+ }
635
+ }
636
+ ```
637
+
638
+ ### Where to hook user management into common auth providers
639
+
640
+ **NextAuth (next-auth):**
641
+
642
+ ```typescript
643
+ // app/api/auth/[...nextauth]/route.ts or pages/api/auth/[...nextauth].ts
644
+ import NextAuth from "next-auth";
645
+
646
+ export default NextAuth({
647
+ // ... your providers ...
648
+ events: {
649
+ createUser: async ({ user }) => {
650
+ await createCometChatUser(user.id, user.name ?? user.email ?? "User");
651
+ },
652
+ // Note: NextAuth doesn't have a deleteUser event by default.
653
+ // Handle deletion in your account deletion endpoint.
654
+ },
655
+ });
656
+ ```
657
+
658
+ **Clerk:**
659
+
660
+ ```typescript
661
+ // Clerk webhook handler — app/api/webhooks/clerk/route.ts
662
+ import { NextResponse } from "next/server";
663
+ import { Webhook } from "svix";
664
+
665
+ export async function POST(req: Request) {
666
+ const body = await req.text();
667
+ // Verify webhook signature with svix (see Clerk docs)
668
+
669
+ const event = JSON.parse(body);
670
+
671
+ switch (event.type) {
672
+ case "user.created":
673
+ await createCometChatUser(
674
+ event.data.id,
675
+ `${event.data.first_name} ${event.data.last_name}`.trim(),
676
+ event.data.image_url
677
+ );
678
+ break;
679
+ case "user.updated":
680
+ await updateCometChatUser(event.data.id, {
681
+ name: `${event.data.first_name} ${event.data.last_name}`.trim(),
682
+ avatar: event.data.image_url,
683
+ });
684
+ break;
685
+ case "user.deleted":
686
+ await deleteCometChatUser(event.data.id);
687
+ break;
688
+ }
689
+
690
+ return NextResponse.json({ received: true });
691
+ }
692
+ ```
693
+
694
+ **Supabase Auth:**
695
+
696
+ ```typescript
697
+ // Supabase Edge Function or webhook handler
698
+ // Supabase fires webhooks on auth events via Database Webhooks
699
+ // pointing at the auth.users table.
700
+
701
+ // In a Next.js API route triggered by Supabase webhook:
702
+ export async function POST(req: Request) {
703
+ const { type, record } = await req.json();
704
+
705
+ if (type === "INSERT") {
706
+ await createCometChatUser(
707
+ record.id,
708
+ record.raw_user_meta_data?.full_name ?? record.email ?? "User",
709
+ record.raw_user_meta_data?.avatar_url
710
+ );
711
+ } else if (type === "UPDATE") {
712
+ await updateCometChatUser(record.id, {
713
+ name: record.raw_user_meta_data?.full_name,
714
+ avatar: record.raw_user_meta_data?.avatar_url,
715
+ });
716
+ } else if (type === "DELETE") {
717
+ await deleteCometChatUser(record.id);
718
+ }
719
+
720
+ return new Response("OK");
721
+ }
722
+ ```
723
+
724
+ **Firebase Auth:**
725
+
726
+ ```typescript
727
+ // Firebase Cloud Function triggered by auth events
728
+ import * as functions from "firebase-functions";
729
+
730
+ export const onUserCreated = functions.auth.user().onCreate(async (user) => {
731
+ await createCometChatUser(
732
+ user.uid,
733
+ user.displayName ?? user.email ?? "User",
734
+ user.photoURL ?? undefined
735
+ );
736
+ });
737
+
738
+ export const onUserDeleted = functions.auth.user().onDelete(async (user) => {
739
+ await deleteCometChatUser(user.uid);
740
+ });
741
+
742
+ // For profile updates, call updateCometChatUser from your
743
+ // profile update endpoint — Firebase Auth doesn't fire a
744
+ // Cloud Function on profile changes.
745
+ ```
746
+
747
+ ---
748
+
749
+ ## 6. Environment variables
750
+
751
+ ### Production environment variables
752
+
753
+ | Variable | Where | Description |
754
+ |---|---|---|
755
+ | `COMETCHAT_APP_ID` | Server + Client | Your app ID. Client-side copies use the framework prefix (`NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`). |
756
+ | `COMETCHAT_REGION` | Server + Client | Region code: `us`, `eu`, `in`. Client-side copies use the framework prefix. |
757
+ | `COMETCHAT_REST_API_KEY` | SERVER ONLY | The REST API key from your CometChat dashboard. Used for token generation and user management. |
758
+ | `COMETCHAT_AUTH_KEY` | REMOVE in production | The auth key used in dev mode. Remove it from `.env` in production. |
759
+
760
+ ### Critical: REST API key must be server-only
761
+
762
+ The REST API key grants full access to your CometChat app: creating users, generating tokens, deleting messages, managing groups. It MUST stay on the server.
763
+
764
+ **NEVER prefix it with:**
765
+ - `NEXT_PUBLIC_` (Next.js)
766
+ - `VITE_` (Vite / React Router)
767
+ - `PUBLIC_` (Astro)
768
+ - `REACT_APP_` (Create React App)
769
+
770
+ Any of these prefixes will bundle the key into your client-side JavaScript, exposing it to every visitor.
771
+
772
+ ### Example .env file (production)
773
+
774
+ ```bash
775
+ # Client-side (with framework prefix)
776
+ NEXT_PUBLIC_COMETCHAT_APP_ID=your-app-id
777
+ NEXT_PUBLIC_COMETCHAT_REGION=us
778
+
779
+ # Server-side ONLY (no prefix)
780
+ COMETCHAT_APP_ID=your-app-id
781
+ COMETCHAT_REGION=us
782
+ COMETCHAT_REST_API_KEY=your-rest-api-key
783
+
784
+ # REMOVED — do not include in production:
785
+ # NEXT_PUBLIC_COMETCHAT_AUTH_KEY=...
786
+ ```
787
+
788
+ ### Finding the REST API key
789
+
790
+ 1. Go to [app.cometchat.com](https://app.cometchat.com)
791
+ 2. Select your app
792
+ 3. Navigate to **API & Auth Keys**
793
+ 4. Copy the **REST API Key** (it is different from the Auth Key)
794
+
795
+ ---
796
+
797
+ ## 7. Security checklist
798
+
799
+ Before deploying to production, verify every item:
800
+
801
+ - [ ] **Auth key removed from client-side env vars.** No `NEXT_PUBLIC_COMETCHAT_AUTH_KEY`, `VITE_COMETCHAT_AUTH_KEY`, or `PUBLIC_COMETCHAT_AUTH_KEY` in your `.env` file.
802
+
803
+ - [ ] **REST API key is server-only.** The `COMETCHAT_REST_API_KEY` variable has NO framework prefix (`NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`, `REACT_APP_`).
804
+
805
+ - [ ] **Token endpoint validates the caller's identity.** The `/api/cometchat-token` endpoint checks that the request comes from an authenticated user (session cookie, JWT, etc.) before issuing a token. The example code includes `TODO` comments where you add this check.
806
+
807
+ - [ ] **UID comes from the session, not the request.** In production, the token endpoint should derive the user's UID from the authenticated session, not from the request body. This prevents users from requesting tokens for other users.
808
+
809
+ - [ ] **CORS configured.** If the token endpoint runs on a different origin than the frontend (e.g., Express on port 3001, Vite on port 5173), configure CORS to allow only your frontend origin.
810
+
811
+ - [ ] **Rate limiting on the token endpoint.** Add rate limiting to prevent abuse. Most frameworks have middleware for this (e.g., `express-rate-limit`, Next.js middleware, Astro middleware).
812
+
813
+ - [ ] **User management endpoints are authenticated.** The create/update/delete user endpoints must verify that the caller has permission to perform the operation (admin role, webhook signature, etc.).
814
+
815
+ - [ ] **UIKitSettingsBuilder does NOT call `.setAuthKey()`.** In production, remove the `setAuthKey()` call entirely. The builder should only have `setAppId()` and `setRegion()`.
816
+
817
+ ---
818
+
819
+ ## 8. Rate limits and retry
820
+
821
+ CometChat's REST API enforces per-app rate limits on the token and user-management endpoints. When limits are exceeded, the API returns **HTTP 429** with a `Retry-After` header (in seconds). Your server code should handle this gracefully — without retry logic, a burst of simultaneous logins on app startup can fail silently.
822
+
823
+ ### What to retry, and what not to
824
+
825
+ **Retry these:**
826
+ - `429 Too Many Requests` — rate limit hit, back off and retry
827
+ - `502 / 503 / 504` — transient upstream failures (gateway, unavailable, timeout)
828
+ - Network errors (`ECONNRESET`, `ETIMEDOUT`) — local/transport issues
829
+
830
+ **Do NOT retry these:**
831
+ - `400 Bad Request` — malformed payload, retry will fail identically
832
+ - `401 Unauthorized` / `403 Forbidden` — wrong API key or missing permissions, retry can't help
833
+ - `404 Not Found` — wrong endpoint or user/group doesn't exist
834
+
835
+ ### Exponential backoff pattern
836
+
837
+ The minimum useful retry is exponential backoff with a cap and full jitter. The pattern below works in any Node.js / Edge runtime (Next.js API routes, Astro endpoints, Hono, Express):
838
+
839
+ ```typescript
840
+ interface RetryOptions {
841
+ maxAttempts?: number; // default 3 (initial + 2 retries)
842
+ baseDelayMs?: number; // default 500ms
843
+ maxDelayMs?: number; // default 8000ms (cap)
844
+ }
845
+
846
+ async function fetchWithRetry(
847
+ url: string,
848
+ init: RequestInit,
849
+ opts: RetryOptions = {},
850
+ ): Promise<Response> {
851
+ const { maxAttempts = 3, baseDelayMs = 500, maxDelayMs = 8000 } = opts;
852
+ let lastError: unknown;
853
+
854
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
855
+ try {
856
+ const res = await fetch(url, init);
857
+
858
+ // Retry 429 and 5xx (except 501/505 — those are protocol-level, not transient)
859
+ if (res.status === 429 || (res.status >= 500 && res.status !== 501 && res.status !== 505)) {
860
+ if (attempt === maxAttempts) return res; // give up, return the failed response
861
+
862
+ // Prefer Retry-After header when present; otherwise exponential backoff
863
+ const retryAfter = res.headers.get("Retry-After");
864
+ const delayMs = retryAfter
865
+ ? Math.min(parseInt(retryAfter, 10) * 1000, maxDelayMs)
866
+ : Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);
867
+ const jitter = Math.random() * delayMs * 0.3; // ±30% full jitter
868
+ await new Promise((resolve) => setTimeout(resolve, delayMs + jitter));
869
+ continue;
870
+ }
871
+ return res;
872
+ } catch (err) {
873
+ lastError = err;
874
+ if (attempt === maxAttempts) throw err;
875
+ const delayMs = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);
876
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
877
+ }
878
+ }
879
+ throw lastError;
880
+ }
881
+ ```
882
+
883
+ ### Wire it into the token endpoint
884
+
885
+ Replace the bare `fetch` in Section 3's patterns with `fetchWithRetry`:
886
+
887
+ ```typescript
888
+ // Before
889
+ const response = await fetch(
890
+ `https://${COMETCHAT_APP_ID}.api-${COMETCHAT_REGION}.cometchat.io/v3/users/${uid}/auth_tokens`,
891
+ { method: "POST", headers: { ...headers } },
892
+ );
893
+
894
+ // After
895
+ const response = await fetchWithRetry(
896
+ `https://${COMETCHAT_APP_ID}.api-${COMETCHAT_REGION}.cometchat.io/v3/users/${uid}/auth_tokens`,
897
+ { method: "POST", headers: { ...headers } },
898
+ { maxAttempts: 3, baseDelayMs: 500, maxDelayMs: 4000 },
899
+ );
900
+ ```
901
+
902
+ The same wrapper applies to user-management endpoints (create/update/delete) and any other CometChat REST call.
903
+
904
+ ### Logging without leaking
905
+
906
+ When logging retry attempts for observability, **never log the request headers as-is** — the `apiKey` and `appId` headers contain secrets. Safe shape:
907
+
908
+ ```typescript
909
+ console.warn("CometChat API rate-limited", {
910
+ url: url.replace(/\/users\/[^/]+\/auth_tokens/, "/users/<redacted>/auth_tokens"),
911
+ status: res.status,
912
+ attempt,
913
+ retryAfter: res.headers.get("Retry-After"),
914
+ });
915
+ ```
916
+
917
+ Log the URL path, status, attempt number, and `Retry-After` — never the UID (user identifier), the API key, or the auth token.
918
+
919
+ ### Circuit breaker (for high-traffic endpoints)
920
+
921
+ If you're behind a load balancer with many parallel requests, a simple backoff isn't enough — every process independently retries, amplifying the pressure. For those setups, add a circuit breaker (e.g. `opossum` for Node.js) around `fetchWithRetry` so repeated failures stop traffic to CometChat for a cooldown window instead of continuing to hammer it.
922
+
923
+ **Don't prematurely add a circuit breaker** — it's only worth it once you have production metrics showing sustained 429s under normal load.
924
+
925
+ ---
926
+
927
+ ## 9. CLI complement
928
+
929
+ The CLI has `production-auth` and `add-user-mgmt` commands that can scaffold the token endpoint and user management routes for supported frameworks:
930
+
931
+ ```bash
932
+ npx @cometchat/skills-cli production-auth --json
933
+ npx @cometchat/skills-cli add-user-mgmt --json
934
+ ```
935
+
936
+ These commands:
937
+ - Read `.cometchat/state.json` to detect the framework
938
+ - Create the API route file from a template
939
+ - Auto-patch the client login flow (replacing `CometChatUIKit.login(uid)` with `loginWithAuthToken`)
940
+ - Update the integration state
941
+
942
+ **Supported frameworks:** Next.js, React Router (framework mode), Astro.
943
+
944
+ **Not supported:** React/Vite (no built-in server). For React/Vite projects, use the Express or Hono patterns in Section 3 of this skill.
945
+
946
+ The CLI templates are a starting point. This skill's patterns are more complete (they cover more frameworks, show auth provider integration, and include the security checklist). Use the CLI for scaffolding, then refer to this skill for the full picture.
947
+
948
+ ---
949
+
950
+ ## 10. Common mistakes
951
+
952
+ 1. **Using the Auth Key instead of the REST API Key on the server.** The Auth Key (`setAuthKey()`) is for client-side dev mode. The REST API Key is for server-side API calls. They are different keys with different permissions.
953
+
954
+ 2. **Exposing the REST API Key to the client.** Adding `NEXT_PUBLIC_` or `VITE_` prefix to the REST API Key variable bundles it into the client. This is worse than exposing the Auth Key because the REST API Key can create and delete users.
955
+
956
+ 3. **Not validating the caller before issuing tokens.** If your token endpoint accepts any UID without checking the caller's identity, anyone can request tokens for any user. Always validate the session first.
957
+
958
+ 4. **Forgetting to create CometChat users.** If you use token auth but never create the CometChat user via the REST API, `loginWithAuthToken` will fail with "User not found." Always create the CometChat user when the app user signs up.
959
+
960
+ 5. **Hardcoding UIDs in production.** The example code uses `"cometchat-uid-1"` as a placeholder. In production, the UID must come from your authentication system.