Skip to content
Back to search

chatpack

Open-source chat infrastructure for developers.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/chddaniel--chatpack/badge.svg)](/listings/chddaniel--chatpack)

HTML

<a href="/listings/chddaniel--chatpack"><img src="/api/listings/chddaniel--chatpack/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

> Prefer learning from a complete app? [`examples/messenger`](./examples/messenger) > is a full 1:1 messenger - sidebar, live messages, read receipts - in vanilla > HTML+JS with a step-by-step tutorial README.

1. Install

Both packages are needed for the quickstart - `@chatpack/core` is the engine, `@chatpack/adapter-memory` is the storage it plugs into:

# pick your package manager
npm  install @chatpack/core @chatpack/adapter-memory
pnpm add     @chatpack/core @chatpack/adapter-memory
bun  add     @chatpack/core @chatpack/adapter-memory

> **Bun note:** if Bun's supply-chain guard (`minimumReleaseAge`) is enabled, > versions published in the last 24 h are skipped and Bun silently resolves an > older release. If you get an unexpectedly old version right after a release, > that's the guard - not a broken package. Check with > `npm view @chatpack/core dist-tags`.

2. Create your chat server

// lib/chat.ts
import { chatpack } from "@chatpack/core";
import { memoryAdapter } from "@chatpack/adapter-memory";

export const chat = chatpack({
  storage: memoryAdapter(),
  // resolve the current user from a request - the ONLY auth touchpoint.
  // Concrete example with a session cookie (works with any auth library):
  auth: async (req) => {
    const session = await getSessionFromCookie(req.headers.get("cookie"));
    return session ? { id: session.userId } : null;
  },
});

> **The `auth` hook must return `ChatpackUser | null`** - an object with at > least `{ id: string }` (extra fields are allowed and ignored), or `null` > for unauthenticated requests. Returning a bare string is treated as > unauthenticated and every request will get a `401`. > > **Prefer cookie-based sessions** over `Authorization` headers: the browser > sends cookies automatically on every request - including the SSE stream in > step 6, where custom headers are impossible. > > The hook receives a raw Web-standard `Request` - there is no > `request.cookies` helper. Parse the `cookie` header yourself: > > ```ts > // demo auth: a plain cookie naming the user (swap for your auth library) > auth: (request) => { > const cookie = request.headers.get("cookie") ?? ""; > const id = /(?:^|;\s*)demo_user=([^;]+)/.exec(cookie)?.[1] ?? null; > return id ? { id: decodeURIComponent(id) } : null; > }, > ``` > > **Setting the demo cookie in an embedded preview (Lovable, v0, Bolt, ...)?** > Those editors show your app inside a cross-site iframe, where browsers > silently drop `SameSite=Lax` cookies - the app 401s in the preview pane but > works in a real tab. Set demo cookies with iframe-proof attributes: > > ```ts > document.cookie = "demo_user=alice; Path=/; Max-Age=86400; SameSite=None; Secure; Partitioned"; > ```

For production, swap the storage line for Postgres - [`@chatpack/adapter-drizzle`](./packages/adapter-drizzle):

import { drizzle } from "drizzle-orm/node-postgres";
import { drizzleAdapter } from "@chatpack/adapter-drizzle";

export const chat = chatpack({
  storage: drizzleAdapter(drizzle(process.env.DATABASE_URL!)),
  auth: async (req) => getSessionUser(req),
});

If your application already uses Prisma ORM 7, use the server-only [`@chatpack/adapter-prisma`](./packages/adapter-prisma) adapter. Copy its Prisma models and migration into your app, generate your own client, and pass it to `prismaAdapter(client)`. Verified provider is PostgreSQL 16; Prisma 8 and other providers are not claimed compatible.

> **No direct Postgres connection string?** Platforms that only expose a > database client (Supabase's JS client, Convex, and most AI-builder clouds) > are supported through a custom `StorageAdapter`. The full guide - reference > schema, invariants, skeleton, and a verification checklist - is Part 2 of > [`llms.txt`](./llms.txt). > > **Building with an AI assistant or app builder?** [`llms.txt`](./llms.txt) > is the single-fetch integration guide (hard rules, wiring, per-framework

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 954 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. # Chatpack
  3. **Open-source chat infrastructure for developers.**
  4. Install a package, wire up your database and auth, and get a production-ready
  5. chat backend - 1:1 and group conversations, messages, permissions, read-state,
  6. and real-time delivery - without rebuilding it from scratch.
  7. [![CI](https://github.com/chddaniel/chatpack/actions/workflows/ci.yml/badge.svg)](https://github.com/chddaniel/chatpack/actions/workflows/ci.yml)
  8. [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
  9. [![Discord](https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white)](https://discord.gg/gY3GCTRv5Y)
  10. [![X](https://img.shields.io/badge/X-@chatpackdev-000000?logo=x&logoColor=white)](https://x.com/chatpackdev)
  11. [![npm](https://img.shields.io/npm/v/@chatpack/core?logo=npm&color=CB3837&label=@chatpack/core)](https://www.npmjs.com/package/@chatpack/core)
  12. [![AllMCPs Verified](https://allmcps.com/api/badge/chatpack-mcp)](https://allmcps.com/mcp/chatpack-mcp?verify=487b08d3-e285-4de5-a2b7-fc05dc12c352)
  13. **[Documentation → docs.chatpack.dev](https://docs.chatpack.dev)** -
  14. quickstart, concepts, real-time, storage adapters, framework guides, and the
  15. full REST reference. (Source in [`apps/docs`](./apps/docs); run locally with
  16. `pnpm --filter @chatpack/docs dev`.)
  17. A project by **[CH Daniel](https://github.com/chddaniel)** and
  18. **[DavidCH](https://github.com/chhddavid)** ·
  19. [all contributors](https://github.com/chddaniel/chatpack/graphs/contributors)
  20. </div>
  21. ---
  22. > **Status: `0.x` - v0 MVP + real-time plugins + unread counts + browser
  23. > client + reactions + search + group chats + mentions + forwarding, live on
  24. > npm.** The v0 MVP (core engine,
  25. > HTTP handler, real-time SSE, Postgres adapter) plus the opt-in real-time
  26. > plugins - **`typing()`, `presence()`, and `receipts()`, all shipping today
  27. > inside `@chatpack/core` under the `@chatpack/core/plugins` subpath** (see
  28. > [Real-time plugins](#real-time-plugins-typing-presence-read-ticks)) - are
  29. > published and installable now, along with the first-party
  30. > [`@chatpack/client`](./packages/client), which provides the matching typed
  31. > REST, SSE, and React client. The API is young - expect minor breaking
  32. > changes before `1.0`. Follow along or [contribute](./CONTRIBUTING.md).
  33. ## Why
  34. Every app that needs messaging ends up rebuilding the same things: conversations,
  35. messages, permissions, read receipts, real-time delivery, group membership and
  36. roles, and countless edge cases.
  37. Chatpack removes that repetition - the same way BetterAuth did for authentication.
  38. You bring your **auth** and your **frontend**; Chatpack gives you a small,
  39. well-designed chat backend that just works.
  40. Real-time comes built in: your frontend opens **one `EventSource`** and gets
  41. live messages with automatic reconnection and missed-message backfill - no
  42. WebSocket server, no Socket.IO, no reconnect code to write.
  43. ## How it fits together
  44. ```text
  45. Your frontend ── fetch("/api/chat/…") + EventSource("/api/chat/stream")
  46. │
  47. ▼
  48. chat.handler() one Web-standard handler (Request → Response)
  49. │
  50. ├── auth hook your session → { id: userId } (you own users)
  51. ▼
  52. chat.api.* domain logic, permissions (also callable directly)
  53. │
  54. ▼
  55. StorageAdapter memory · Drizzle/Postgres · Drizzle/SQLite · Turso/libSQL · Supabase · your own
  56. │
  57. ▼
  58. Your database
  59. ```
  60. ## Quickstart
  61. > Prefer learning from a complete app? [`examples/messenger`](./examples/messenger)
  62. > is a full 1:1 messenger - sidebar, live messages, read receipts - in vanilla
  63. > HTML+JS with a step-by-step tutorial README.
  64. ### 1. Install
  65. Both packages are needed for the quickstart - `@chatpack/core` is the engine,
  66. `@chatpack/adapter-memory` is the storage it plugs into:
  67. ```sh
  68. # pick your package manager
  69. npm install @chatpack/core @chatpack/adapter-memory
  70. pnpm add @chatpack/core @chatpack/adapter-memory
  71. bun add @chatpack/core @chatpack/adapter-memory
  72. ```
  73. > **Bun note:** if Bun's supply-chain guard (`minimumReleaseAge`) is enabled,
  74. > versions published in the last 24 h are skipped and Bun silently resolves an
  75. > older release. If you get an unexpectedly old version right after a release,
  76. > that's the guard - not a broken package. Check with
  77. > `npm view @chatpack/core dist-tags`.
  78. ### 2. Create your chat server
  79. ```ts
  80. // lib/chat.ts
  81. import { chatpack } from "@chatpack/core";
  82. import { memoryAdapter } from "@chatpack/adapter-memory";
  83. export const chat = chatpack({
  84. storage: memoryAdapter(),
  85. // resolve the current user from a request - the ONLY auth touchpoint.
  86. // Concrete example with a session cookie (works with any auth library):
  87. auth: async (req) => {
  88. const session = await getSessionFromCookie(req.headers.get("cookie"));
  89. return session ? { id: session.userId } : null;
  90. },
  91. });
  92. ```
  93. > **The `auth` hook must return `ChatpackUser | null`** - an object with at
  94. > least `{ id: string }` (extra fields are allowed and ignored), or `null`
  95. > for unauthenticated requests. Returning a bare string is treated as
  96. > unauthenticated and every request will get a `401`.
  97. >
  98. > **Prefer cookie-based sessions** over `Authorization` headers: the browser
  99. > sends cookies automatically on every request - including the SSE stream in
  100. > step 6, where custom headers are impossible.
  101. >
  102. > The hook receives a raw Web-standard `Request` - there is no
  103. > `request.cookies` helper. Parse the `cookie` header yourself:
  104. >
  105. > ```ts
  106. > // demo auth: a plain cookie naming the user (swap for your auth library)
  107. > auth: (request) => {
  108. > const cookie = request.headers.get("cookie") ?? "";
  109. > const id = /(?:^|;\s*)demo_user=([^;]+)/.exec(cookie)?.[1] ?? null;
  110. > return id ? { id: decodeURIComponent(id) } : null;
  111. > },
  112. > ```
  113. >
  114. > **Setting the demo cookie in an embedded preview (Lovable, v0, Bolt, ...)?**
  115. > Those editors show your app inside a cross-site iframe, where browsers
  116. > silently drop `SameSite=Lax` cookies - the app 401s in the preview pane but
  117. > works in a real tab. Set demo cookies with iframe-proof attributes:
  118. >
  119. > ```ts
  120. > document.cookie = "demo_user=alice; Path=/; Max-Age=86400; SameSite=None; Secure; Partitioned";
  121. > ```
  122. For production, swap the storage line for Postgres -
  123. [`@chatpack/adapter-drizzle`](./packages/adapter-drizzle):
  124. ```ts
  125. import { drizzle } from "drizzle-orm/node-postgres";
  126. import { drizzleAdapter } from "@chatpack/adapter-drizzle";
  127. export const chat = chatpack({
  128. storage: drizzleAdapter(drizzle(process.env.DATABASE_URL!)),
  129. auth: async (req) => getSessionUser(req),
  130. });
  131. ```
  132. If your application already uses Prisma ORM 7, use the server-only
  133. [`@chatpack/adapter-prisma`](./packages/adapter-prisma) adapter. Copy its
  134. Prisma models and migration into your app, generate your own client, and pass
  135. it to `prismaAdapter(client)`. Verified provider is PostgreSQL 16; Prisma 8
  136. and other providers are not claimed compatible.
  137. > **No direct Postgres connection string?** Platforms that only expose a
  138. > database client (Supabase's JS client, Convex, and most AI-builder clouds)
  139. > are supported through a custom `StorageAdapter`. The full guide - reference
  140. > schema, invariants, skeleton, and a verification checklist - is Part 2 of
  141. > [`llms.txt`](./llms.txt).
  142. >
  143. > **Building with an AI assistant or app builder?** [`llms.txt`](./llms.txt)
  144. > is the single-fetch integration guide (hard rules, wiring, per-framework
  145. > mount recipes, preview-iframe cookie recipe, verification steps). It also
  146. > ships inside every `@chatpack/*` npm package as `llms.txt` - point your
  147. > agent at `node_modules/@chatpack/core/llms.txt`.
  148. For Turso/libSQL, install `@chatpack/adapter-turso`, `@libsql/client`, and
  149. `drizzle-orm`, then run its exported migration statements before creating the
  150. Chatpack instance. See the [Turso adapter guide](./apps/docs/content/docs/storage/turso.mdx).
  151. For MySQL 8, install `@chatpack/adapter-mysql`, `mysql2`, and `drizzle-orm`,
  152. create a server-side transaction-capable pool, and run its exported migration
  153. statements before creating the Chatpack instance. See the [MySQL adapter
  154. guide](./apps/docs/content/docs/storage/mysql.mdx). This package does not claim
  155. MariaDB, PlanetScale, Aurora, serverless/HTTP drivers, or edge-runtime support.
  156. > Using a coding agent (Claude Code, Cursor, Codex)? Install the
  157. > [Chatpack agent skill](./skills) into your app's repo so the agent follows
  158. > the correct workflow automatically:
  159. >
  160. > ```sh
  161. > npx skills add chddaniel/chatpack
  162. > ```
  163. For MCP clients, [`@chatpack/mcp`](./packages/mcp) provides read-only tools for
  164. documentation search, framework guides, and React UI source. See its README for
  165. local setup and client configuration.
  166. ### 3. Mount the API (Next.js App Router)
  167. ```ts
  168. // app/api/chat/[...chatpack]/route.ts
  169. import { chat } from "@/lib/chat";
  170. export const { GET, POST, PATCH, DELETE, PUT } = chat.handler();
  171. ```
  172. Or, with the [`@chatpack/next`](./packages/next) helper (same result, reads
  173. better):
  174. ```ts
  175. import { toNextRouteHandlers } from "@chatpack/next";
  176. import { chat } from "@/lib/chat";
  177. export const { GET, POST, PATCH, DELETE, PUT } = toNextRouteHandlers(chat);
  178. ```
  179. > **The route file must be a catch-all** (`[...chatpack]` in Next.js) -
  180. > Chatpack serves many sub-paths under `basePath` (default `/api/chat`), so a
  181. > single `app/api/chat/route.ts` would 404 everything but the root.
  182. >
  183. > **Never hand-write your own message or stream routes.** The one handler
  184. > already serves every route - conversations, messages, read-state, plugins,
  185. > and the SSE stream. Custom `/api/messages`-style routes split state and
  186. > break live delivery.
  187. Your chat backend is now live at `/api/chat` - find-or-create conversations,
  188. send/list/edit/delete messages, read-state, and a **live SSE stream** at
  189. `/api/chat/stream`, with your auth enforced on every request.
  190. Not on Next.js? The handler is Web-standard (`Request` → `Response`) and
  191. `GET`/`POST`/`PATCH`/`DELETE`/`PUT`/`fetch` are **all the same function** - the
  192. method names only exist so they can be re-exported from a Next.js route file.
  193. Any of them serves every route, including `/stream`:
  194. ```ts
  195. const handler = chat.handler();
  196. Bun.serve({ fetch: handler.fetch }); // Bun / Deno / Cloudflare Workers
  197. app.all("/api/chat/*", (c) => handler.fetch(c.req.raw)); // Hono
  198. app.all("/api/chat/*", ({ request }) => handler.fetch(request)); // Elysia
  199. ```
  200. TanStack Start (`src/routes/api/chat.$.ts` catch-all) and Express recipes
  201. live in [`@chatpack/core`'s README](./packages/core#rest-api) and
  202. [`llms.txt`](./llms.txt). For plain Node, see
  203. [`examples/node-server`](./examples/node-server).
  204. ### 4. Call it over HTTP
  205. Find-or-create a conversation (the authenticated user + `otherUserId`):
  206. ```sh
  207. curl -X POST /api/chat/conversations \
  208. -H 'content-type: application/json' \
  209. -d '{"otherUserId": "bob"}'
  210. ```
  211. > **Chatpack never owns a users table.** Configure `userExists(userId)` to
  212. > validate direct-chat targets and new group participants against your own
  213. > identity store. Without the optional hook, previous opaque-id behavior is
  214. > preserved.
  215. ```json
  216. {
  217. "conversation": {
  218. "id": "conv_1",
  219. "pairKey": "alice:bob",
  220. "createdAt": "2026-07-22T19:47:47.945Z",
  221. "metadata": {},
  222. "participants": [
  223. { "conversationId": "conv_1", "userId": "alice", "joinedAt": "…", "lastReadMessageId": null },
  224. { "conversationId": "conv_1", "userId": "bob", "joinedAt": "…", "lastReadMessageId": null }
  225. ],
  226. "unreadCount": 0
  227. }
  228. }
  229. ```
  230. Every conversation object carries the **viewer's `unreadCount`** (messages
  231. newer than their read-state, excluding their own) - the badge number comes
  232. from the API, no client-side counting.
  233. Groups are **created, never found** - a separate route, because two groups with
  234. the same members are still two different groups:
  235. ```sh
  236. curl -X POST /api/chat/conversations/group \
  237. -H 'content-type: application/json' \
  238. -d '{"name": "Standup", "userIds": ["bob", "carol"]}'
  239. ```
  240. The caller becomes an `admin`, everyone in `userIds` a `member`, and the
  241. conversation comes back with `type: "group"`, `pairKey: null`, and the `name`.
  242. Managing it afterwards is four admin-only routes - rename
  243. (`PATCH /conversations/:id`), add (`POST /conversations/:id/participants`),
  244. remove (`DELETE`, and any member may pass their own id to leave), and change a
  245. role (`PATCH …/participants`). Groups hold 1-256 participants and always keep at
  246. least one admin.
  247. For the people whose user ids you don't have, mint an **invite link** instead:
  248. ```sh
  249. curl -X POST /api/chat/conversations/conv_2/invites \
  250. -H 'content-type: application/json' \
  251. -d '{"expiresInSeconds": 86400, "maxUses": 5}'
  252. ```
  253. You get back a 43-character `code` to build your own `/join/:code` page from.
  254. `GET /invites/:code` previews what it admits to - a participant **count**, never
  255. the member list, since a non-member can call it - and
  256. `POST /invites/:code/accept` redeems it. Add `"requiresApproval": true` and
  257. redeeming files a **join request** for an admin to approve instead, which is the
  258. same queue any user lands in by asking directly
  259. (`POST /conversations/:id/join-requests`). Either way, joining publishes the
  260. existing `participant.added` event, so live clients need no new code.
  261. When you want people to find the room themselves, publish the group as a
  262. **public channel** - a group with `visibility: "public"`, not a third
  263. conversation type:
  264. ```sh
  265. curl -X PATCH /api/chat/conversations/conv_2 \
  266. -H 'content-type: application/json' \
  267. -d '{"visibility": "public", "joinPolicy": "open"}'
  268. ```
  269. `GET /channels` is then a browsable directory for any signed-in user, returning
  270. thin previews - a name, a participant **count**, and two viewer-relative flags -
  271. and `POST /conversations/:id/join` gets them in: instantly when the policy is
  272. `"open"`, or as a join request when it's `"approval"` (the default, because a
  273. stranger in a queue is recoverable and a stranger in the room isn't).
  274. **Discoverable is not readable**: browsing grants nothing, so reading the
  275. transcript still means joining first.
  276. Letting strangers in needs the other half too, so `/moderation/*` covers blocks,
  277. mutes, reports, and bans. Blocking, muting, and filing a report are
  278. self-service:
  279. ```sh
  280. curl -X POST /api/chat/moderation/blocks \
  281. -H 'content-type: application/json' \
  282. -d '{"targetUserId": "bob"}'
  283. ```
  284. A block stops new DMs and direct writes **both ways** while leaving the existing
  285. history readable, and does nothing inside a shared group. A mute is a hint for
  286. your own UI - unread counts and SSE delivery don't change. The report queue and
  287. the ban routes are for your moderators, so they need a hook:
  288. ```ts
  289. chatpack({
  290. storage,
  291. auth,
  292. moderation: { canModerate: ({ user }) => user.role === "staff" },
  293. });
  294. ```
  295. Without it, `GET /moderation/reports` and every ban route answer `403
  296. NOT_MODERATOR`. With it, an active ban is checked **before routing** - a banned
  297. user gets `403 USER_BANNED` on every route including `/stream`. Configuring
  298. `moderation` at all is what switches that enforcement on, so an app that doesn't
  299. use bans pays no per-request lookup; add `enforceBans: true` if ban rows are
  300. written outside Chatpack.
  301. Send a message - note the field is **`body`**:
  302. ```sh
  303. curl -X POST /api/chat/conversations/conv_1/messages \
  304. -H 'content-type: application/json' \
  305. -d '{"body": "hey bob!"}'
  306. ```
  307. ```json
  308. {
  309. "message": {
  310. "id": "msg_1",
  311. "conversationId": "conv_1",
  312. "senderId": "alice",
  313. "body": "hey bob!",
  314. "role": "user",
  315. "seq": 1,
  316. "createdAt": "2026-07-22T19:48:06.416Z",
  317. "editedAt": null,
  318. "deletedAt": null,
  319. "metadata": {},
  320. "replyToMessageId": null,
  321. "replyTo": null,
  322. "reactions": [],
  323. "mentions": [],
  324. "forwardedFrom": null
  325. }
  326. }
  327. ```
  328. Quote-reply by passing `replyToMessageId`, and react with a `POST` (removing is
  329. the same route with `DELETE`; the emoji travels in the body, not the path):
  330. ```sh
  331. curl -X POST /api/chat/conversations/conv_1/messages \
  332. -H 'content-type: application/json' \
  333. -d '{"body": "hey alice!", "replyToMessageId": "msg_1"}'
  334. curl -X POST /api/chat/messages/msg_1/reactions \
  335. -H 'content-type: application/json' \
  336. -d '{"emoji": "👍"}'
  337. ```
  338. A reply carries a read-only `replyTo` preview
  339. (`{ id, senderId, excerpt, deleted }`) hydrated per request - edit the parent
  340. and the quote bar follows. Reaction routes are idempotent and always return the
  341. message with its **complete** reaction set
  342. (`[{ emoji, count, userIds }]`). These are quote-replies, not threads, and a
  343. reaction is not a message: it has no `seq` and never reorders the conversation
  344. list.
  345. **Mentions** are ids you supply, not text Chatpack parses - it has no users table
  346. to resolve a name against, and `body` stays opaque. **Forwarding** copies a
  347. message into another conversation:
  348. ```sh
  349. curl -X POST /api/chat/conversations/conv_2/messages \
  350. -H 'content-type: application/json' \
  351. -d '{"body": "@carol ship it", "mentions": ["carol"]}'
  352. curl -X POST /api/chat/messages/msg_1/forward \
  353. -H 'content-type: application/json' \
  354. -d '{"conversationId": "conv_2"}'
  355. ```
  356. Every mentioned id must be a current participant, or the whole call is `400
  357. MENTION_NOT_PARTICIPANT` - never a silent drop, because a drop nobody sees looks
  358. exactly like a notification that fired. On edit, omitting `mentions` leaves the
  359. stored set alone and `[]` clears it. Chatpack notifies nobody and keeps no mention
  360. inbox: `afterMessageMutation` hands you `mentions` next to `recipientIds`, which is
  361. where a push integration belongs.
  362. A forward is a **copy**, never a live pointer: a new message in the target with
  363. your id as sender, its own `seq`, and `forwardedFrom`
  364. (`{ messageId, conversationId, senderId }`) frozen at forward time. Editing or
  365. deleting the original changes nothing about the copy. One hop, like replies -
  366. and deliberately no excerpt and no source conversation _name_, since whoever reads
  367. the copy may have no access to where it came from. Reactions, the reply pointer,
  368. mentions, metadata and `role` don't travel.
  369. List history (newest first, keyset-paginated):
  370. ```sh
  371. curl '/api/chat/conversations/conv_1/messages?limit=50'
  372. ```
  373. ```json
  374. { "messages": [{ "id": "msg_1", "body": "hey bob!", "seq": 1, "…": "…" }], "nextCursor": null }
  375. ```
  376. Search participant conversations across message bodies. Search is
  377. case-insensitive, punctuation-separated, relevance-ranked, and excludes
  378. tombstones:
  379. ```sh
  380. curl '/api/chat/search/messages?q=hello&limit=50'
  381. ```
  382. The response is `{ "messages": [...], "nextCursor": null }`. Core applies
  383. `canRead` to the participant-scoped results. Dynamic access to conversations
  384. where the user is not a participant is not supported by this initial design.
  385. Errors are JSON with a stable machine-readable code and a mapped HTTP status -
  386. `401` when `auth` returns `null`, `400` for invalid input, `403`/`404`/`409`
  387. for domain errors:
  388. ```json
  389. { "error": { "code": "FORBIDDEN_READ", "message": "…" } }
  390. ```
  391. The full endpoint reference (every route, request/response shapes, error
  392. codes) lives in [`@chatpack/core`'s README](./packages/core#rest-api).
  393. ### 5. Use the first-party client (optional)
  394. The server setup above remains the same. Add the client when you want typed
  395. REST methods, one managed SSE connection, a small shared cache, and React
  396. hooks:
  397. ```sh
  398. npm install @chatpack/client react
  399. ```
  400. Create one shared client instance in its own module:
  401. ```ts
  402. // lib/chat-client.ts
  403. import { createChatClient } from "@chatpack/client/react";
  404. import { typingClient, presenceClient, receiptsClient } from "@chatpack/client/plugins";
  405. export const chatClient = createChatClient({
  406. // Omit baseURL when the client and handler share an origin.
  407. baseURL: "http://localhost:3000",
  408. credentials: "include",
  409. plugins: [typingClient(), presenceClient(), receiptsClient()],
  410. });
  411. ```
  412. Then read with hooks and write with actions - every action returns
  413. `{ data, error }` instead of throwing:
  414. ```tsx
  415. // components/messages.tsx
  416. "use client";
  417. import { chatClient } from "../lib/chat-client";
  418. export function Messages({ conversationId }: { conversationId: string }) {
  419. const result = chatClient.useMessages({ conversationId, limit: 50 });
  420. async function send() {
  421. const sent = await chatClient.messages.send({
  422. conversationId,
  423. body: "hey bob!",
  424. });
  425. if (sent.error) console.error(sent.error.message);
  426. }
  427. return (
  428. <>
  429. <ul>
  430. {result.data?.messages.map((message) => (
  431. <li key={message.id}>{message.body}</li>
  432. ))}
  433. </ul>
  434. <button onClick={send}>Send</button>
  435. </>
  436. );
  437. }
  438. ```
  439. The client uses the authenticated identity resolved by the server's `auth`
  440. hook. It does not implement login, sessions, or user lookup. Same-origin
  441. cookies work by default; use `credentials: "include"` for cross-origin cookie
  442. sessions. Native `EventSource` cannot send custom headers, so cookie auth is
  443. also required for browser realtime unless you provide a custom EventSource.
  444. Where SSE can't work - serverless function timeouts, buffering proxies, React
  445. Native - the client falls back to refetching on an interval by itself, so a
  446. serverless deploy needs no frontend change. Typing, presence and receipts are
  447. unavailable while polling, since ephemeral events are never stored.
  448. Group management is wrapped too (client 0.5.0+): `conversations.createGroup`,
  449. `addParticipants`, `removeParticipant` (your own id = leave),
  450. `setParticipantRole`, and `update` for renames - and membership events keep
  451. the cache in sync, including dropping a conversation you were removed from.
  452. Invites, join requests, and channels are wrapped by `chatClient.invites`,
  453. `chatClient.joinRequests`, and `chatClient.channels`. Invite and channel joins
  454. return either a joined conversation or a pending request; expected HTTP failures
  455. remain structured client results. `chatClient.moderation` wraps all thirteen
  456. moderation calls the same way - note that none of them touch the query cache, so
  457. refetch the lists you show after a block or a mute.
  458. `messages.send` and `messages.edit` take `mentions`, and `messages.forward`
  459. copies a message into another conversation - resolving with the copy and echoing
  460. it into the target thread just like a send. The destination is
  461. `toConversationId` in the client input even though the wire field is a plain
  462. `conversationId`, because the route already names the source.
  463. See [`@chatpack/client`](./packages/client) for the framework-agnostic API,
  464. React hooks, the polling fallback, and client plugin usage.
  465. ### 6. Go live in the browser
  466. ```ts
  467. const events = new EventSource("/api/chat/stream");
  468. // TypeScript: custom event names fall outside EventSourceEventMap, so the
  469. // listener parameter is typed `Event` - cast to MessageEvent for `.data`.
  470. events.addEventListener("message.created", (e) => {
  471. const { message } = JSON.parse((e as MessageEvent).data);
  472. // render it - reconnection & missed-message backfill are automatic
  473. });
  474. events.addEventListener("reaction.added", (e) => {
  475. const { message } = JSON.parse((e as MessageEvent).data);
  476. // message.reactions is the COMPLETE set after the change - replace, don't merge
  477. });
  478. events.addEventListener("participant.removed", (e) => {
  479. const { affectedUserIds, conversation } = JSON.parse((e as MessageEvent).data);
  480. // If affectedUserIds includes YOUR id, you were removed - drop the
  481. // conversation. Otherwise replace your cached copy with `conversation`.
  482. });
  483. // participant.added and conversation.updated (rename / role change) match.
  484. events.onerror = () => {
  485. if (events.readyState === EventSource.CLOSED) {
  486. // Fatal (e.g. 401 from your auth hook): the browser will NOT retry.
  487. // Re-authenticate, then create a new EventSource.
  488. }
  489. // Otherwise it's a dropped connection: EventSource retries automatically
  490. // and sends Last-Event-ID - no action needed.
  491. };
  492. ```
  493. If the connection drops, `EventSource` reconnects with `Last-Event-ID` and
  494. Chatpack replays whatever was missed **from storage** - durable-first delivery,
  495. no lost messages.
  496. Four things to know before going live:
  497. - **Membership changes are live too, and also not replayed.**
  498. `participant.added` / `participant.removed` / `conversation.updated` carry
  499. `{ actorId, affectedUserIds, conversation }` - a complete snapshot, so replace
  500. your cached conversation rather than patching it. Compare `affectedUserIds`
  501. against your own id to tell "I was removed" (drop it; it's the last event
  502. you'll see for that conversation) from "someone else was".
  503. - **Reactions are live but not replayed.** `reaction.added` /
  504. `reaction.removed` are stored, unlike ephemeral plugin events, but reactions
  505. have no `seq` - so their frames carry no `id:` (emitting one would rewind
  506. `Last-Event-ID`) and they are **not** gap-filled. A reaction applied while the
  507. client was offline appears on the next refetch of that conversation.
  508. - **Browser auth must be cookie-based for SSE** - `EventSource` can't send
  509. custom headers, so your `auth` hook needs to resolve the user from a session
  510. cookie (sent automatically same-origin). Bearer-token headers work for the
  511. REST routes but not `/stream` - if your app uses them, write the `auth`
  512. hook to accept either (header first, cookie fallback); worked example in
  513. [`@chatpack/core`'s README](./packages/core#real-time-sse). If the app runs
  514. inside an embedded preview iframe (AI-builder editors), the cookie needs
  515. `SameSite=None; Secure` - see the quickstart note in step 2.
  516. - **SSE + `memoryAdapter` need one long-lived process.** The default transport
  517. fans out inside a single process, so with 2+ app servers a message sent on one
  518. node never reaches a stream on another - drop in
  519. [`@chatpack/transport-redis`](./packages/transport-redis) (one line) to relay
  520. events between nodes. On serverless/edge (Workers, Lambda) each isolate has
  521. its own memory - use a [database adapter](./packages/adapter-drizzle) there and
  522. poll for new messages; SSE is a poor fit regardless of transport, since the
  523. function lifetime is the blocker. `@chatpack/client` falls back to polling on
  524. its own, so a serverless deploy needs no frontend change. Details in
  525. [`@chatpack/core`'s README](./packages/core#real-time-sse).
  526. ### 7. Or call it straight from server code
  527. ```ts
  528. // find-or-create a 1:1 conversation between two users
  529. const conversation = await chat.api.getOrCreateConversation({
  530. userId: "alice",
  531. otherUserId: "bob",
  532. });
  533. // send a message
  534. await chat.api.sendMessage({
  535. userId: "alice",
  536. conversationId: conversation.id,
  537. body: "hey bob!",
  538. });
  539. // read the history
  540. const { messages } = await chat.api.listMessages({
  541. userId: "bob",
  542. conversationId: conversation.id,
  543. });
  544. // react to a message (idempotent - returns the full reaction set)
  545. await chat.api.addReaction({ userId: "bob", messageId: messages[0].id, emoji: "👍" });
  546. await chat.api.removeReaction({ userId: "bob", messageId: messages[0].id, emoji: "👍" });
  547. ```
  548. Groups use a different first call - `createGroupConversation` always creates,
  549. and everything after it is the same API:
  550. ```ts
  551. const group = await chat.api.createGroupConversation({
  552. userId: "alice", // becomes the group's first admin
  553. userIds: ["bob", "carol"], // joined as members
  554. name: "Standup",
  555. });
  556. await chat.api.addParticipants({ userId: "alice", conversationId: group.id, userIds: ["dave"] });
  557. await chat.api.setParticipantRole({
  558. userId: "alice",
  559. conversationId: group.id,
  560. targetUserId: "bob",
  561. role: "admin",
  562. });
  563. await chat.api.removeParticipant({
  564. userId: "carol", // passing your own id = leaving; no admin needed
  565. conversationId: group.id,
  566. targetUserId: "carol",
  567. });
  568. ```
  569. That's it. Only participants can read or write - enforced by default,
  570. customizable via the `permissions` hooks (`canRead`, `canWrite`, `canManage` for
  571. the group-management methods including publishing a channel, and `canInvite` for
  572. minting links - the last two default to admins only, and browsing or joining a
  573. public channel is gated by neither). Platform-wide moderators are a separate
  574. hook, `moderation: { canModerate }`, because being an admin of one conversation
  575. shouldn't open the report queue for all of them. Need content
  576. rules (length caps, profanity filters) or post-send side-effects? Add
  577. `hooks: { beforeMessageSend, afterMessageMutation }` - block or rewrite a
  578. message before it persists, react after send/edit/delete persistence (see [`@chatpack/core`'s
  579. README](./packages/core#message-hooks)).
  580. ### 8. Bonus: chat with an AI assistant
  581. To Chatpack, an AI assistant is **just another participant** - pick a
  582. synthetic user id (any string you'll never issue to a real user, e.g.
  583. `ai:assistant`) and have your backend send its replies. No special AI support
  584. needed, and the same permissions apply (drop the same id into a group's
  585. `userIds` for a shared assistant):
  586. ```ts
  587. const ASSISTANT_ID = "ai:assistant";
  588. // find-or-create the user's conversation with the assistant
  589. const conversation = await chat.api.getOrCreateConversation({
  590. userId: user.id,
  591. otherUserId: ASSISTANT_ID,
  592. });
  593. // the user's message arrives (via your route or the REST API)...
  594. await chat.api.sendMessage({
  595. userId: user.id,
  596. conversationId: conversation.id,
  597. body: userText,
  598. });
  599. // ...your backend calls your LLM of choice with your own keys...
  600. const reply = await generateReply(userText); // OpenAI, Anthropic, Gemini, ...
  601. // ...and sends the answer as the assistant participant
  602. await chat.api.sendMessage({
  603. userId: ASSISTANT_ID,
  604. conversationId: conversation.id,
  605. body: reply,
  606. role: "assistant", // "user" | "assistant" | "system" - stored & returned as-is
  607. });
  608. ```
  609. Chatpack stores, orders, and delivers the messages; the LLM call is yours
  610. (model, keys, prompts, streaming). `role` is a plain label for your UI -
  611. core never behaves differently based on it. Since `otherUserId` accepts any
  612. non-empty string, make sure your `auth`/validation layer prevents real users
  613. from registering ids in your synthetic namespace (e.g. reserve the `ai:`
  614. prefix).
  615. ## Real-time plugins: typing, presence, read ticks
  616. The "feels alive" features are **opt-in plugins** that ship inside
  617. `@chatpack/core` - no extra install:
  618. ```ts
  619. import { chatpack } from "@chatpack/core";
  620. import { typing, presence, receipts } from "@chatpack/core/plugins";
  621. export const chat = chatpack({
  622. storage: memoryAdapter(),
  623. auth: async (req) => getSessionUser(req),
  624. plugins: [typing(), presence(), receipts()],
  625. });
  626. ```
  627. They publish **ephemeral events** on the same `/stream` connection you already
  628. have: fire-and-forget signals that are never stored and never replayed on
  629. reconnect (miss a typing ping and it's gone - that's correct; durable state
  630. like `lastReadMessageId` stays in core). Listen exactly like message events:
  631. ```ts
  632. events.addEventListener("typing.started", (e) => {
  633. const { senderId, conversationId } = JSON.parse((e as MessageEvent).data);
  634. // show "… is typing" - and hide it if no new ping arrives within ~5s
  635. });
  636. events.addEventListener("presence.online", (e) => {
  637. /* light up the dot */
  638. });
  639. events.addEventListener("receipt.read", (e) => {
  640. const { payload } = JSON.parse((e as MessageEvent).data);
  641. // mark everything up to payload.messageId as ✓✓
  642. });
  643. ```
  644. What each plugin adds:
  645. | Plugin | Routes | Events published |
  646. | ------------ | -------------------------------- | ------------------------------------- |
  647. | `typing()` | `POST /conversations/:id/typing` | `typing.started`, `typing.stopped` |
  648. | `presence()` | `GET /presence?userIds=a,b` | `presence.online`, `presence.offline` |
  649. | `receipts()` | - (hooks into send + mark-read) | `receipt.delivered`, `receipt.read` |
  650. Notes that keep the design honest:
  651. - **Typing** is stateless: while the user types, `POST …/typing` at most once
  652. every few seconds; the other side clears the indicator if no ping arrives
  653. within ~5s. Send `{ "isTyping": false }` to clear it eagerly. In a group the
  654. ping goes to every other participant, so key your indicator by `senderId` -
  655. several people can be typing at once.
  656. - **Presence needs no heartbeat endpoint** - the SSE connection _is_ the
  657. heartbeat. Multi-tab safe; a short grace period (default 5s,
  658. `presence({ offlineDelayMs })`) stops the online dot from blinking during
  659. `EventSource` auto-reconnects. Snapshots via `GET /presence` only reveal
  660. users the caller shares a conversation with.
  661. - **Receipts** are instant ✓/✓✓ pings while both sides are online:
  662. `receipt.delivered` fires to the sender the moment a recipient's stream
  663. receives the message; `receipt.read` fires when someone else calls mark-read.
  664. Ticks are at-least-once - dedupe by `payload.messageId`. Each tick is
  665. **per-user**, so in a group collect `senderId`s rather than treating one tick
  666. as "everyone read it". The durable truth is still `lastReadMessageId`.
  667. - Plugin state is in-memory by default. For several long-lived app servers,
  668. [`@chatpack/transport-redis`](./packages/transport-redis) relays events and
  669. `redisPresenceStore()` shares presence leases across nodes.
  670. Want to write your own plugin? The seam is public - see `ChatpackPlugin` in
  671. [`@chatpack/core`](./packages/core) and
  672. [ADR 0008](./docs/decisions/0008-ephemeral-events-in-core-plugins.md).
  673. ## What's in v0
  674. | Feature | Status |
  675. | ---------------------------------------- | ----------------- |
  676. | 1:1 conversations (find-or-create) | ✅ Done (M1) |
  677. | Text messages: send, list, edit, delete | ✅ Done (M1) |
  678. | Participant-only permissions + hooks | ✅ Done (M1) |
  679. | Durable read-state (`last_read`) | ✅ Done (M1) |
  680. | In-memory storage adapter | ✅ Done (M1) |
  681. | HTTP handler (Next.js App Router) | ✅ Done (M2) |
  682. | Real-time delivery (SSE) | ✅ Done (M3) |
  683. | SSE reconnect gap-fill | ✅ Done (M3) |
  684. | Drizzle/Postgres adapter | ✅ Done (M4) |
  685. | Turso/libSQL adapter | ✅ Done (v1.next) |
  686. | Launch polish + npm release | ✅ Done (M5) |
  687. | Typing / presence / read-tick plugins | ✅ Done (v0.next) |
  688. | Unread counts (`unreadCount`) | ✅ Done (v0.next) |
  689. | Redis transport (multi-node SSE) | ✅ Done (v0.next) |
  690. | Browser client + React hooks | ✅ Done (v0.next) |
  691. | Client polling fallback | ✅ Done (v0.next) |
  692. | Reactions + quote-replies | ✅ Done (v0.next) |
  693. | Mentions (validated, supplied ids) | ✅ Done (v1.next) |
  694. | Message forwarding (copy + provenance) | ✅ Done (v1.next) |
  695. | Participant-scoped message search | ✅ Done (v0.next) |
  696. | Post-persistence message mutation hook | ✅ Done (v0.next) |
  697. | `@chatpack/cli init` + starter templates | ✅ Done (v1.next) |
  698. | Group chats: membership, roles, admin | ✅ Done (v0.next) |
  699. | File attachments (`@chatpack/file`) | ✅ Done (v0.next) |
  700. | Invite links + join requests | ✅ Done (v0.next) |
  701. | Public channels (browsable directory) | ✅ Done (v0.next) |
  702. | Moderation: blocks, mutes, reports, bans | ✅ Done (v1.next) |
  703. | Multi-node presence | ✅ Done (v1.next) |
  704. Push notification providers and true message threads have not shipped.
  705. Reusable UI blocks are available through `@chatpack/ui`. Multi-node presence is
  706. available through the shared Redis presence store. Replies are flat pointers, not
  707. threads. See [docs/MVP.md](./docs/MVP.md) for the full scope and reasoning.
  708. ## Packages
  709. | Package | Description |
  710. | ----------------------------------------------------------- | ------------------------------------------------ |
  711. | [`@chatpack/core`](./packages/core) | The chat engine: domain logic, permissions, API |
  712. | [`@chatpack/adapter-drizzle`](./packages/adapter-drizzle) | Drizzle/Postgres storage (production) |
  713. | [`@chatpack/adapter-prisma`](./packages/adapter-prisma) | Prisma 7/Postgres storage (server-only) |
  714. | [`@chatpack/adapter-mysql`](./packages/adapter-mysql) | MySQL 8 storage via Drizzle/mysql2 (server-side) |
  715. | [`@chatpack/adapter-turso`](./packages/adapter-turso) | Turso/libSQL storage via Drizzle |
  716. | [`@chatpack/adapter-sqlite`](./packages/adapter-sqlite) | Drizzle/SQLite storage (local, single node) |
  717. | [`@chatpack/adapter-memory`](./packages/adapter-memory) | In-memory storage (demos, tests) |
  718. | [`@chatpack/adapter-supabase`](./packages/adapter-supabase) | Supabase/Postgres storage (server-side) |
  719. | [`@chatpack/next`](./packages/next) | Next.js App Router integration |
  720. | [`@chatpack/client`](./packages/client) | Typed REST, SSE, React hooks, and client plugins |
  721. | [`@chatpack/cli`](./packages/cli) | Project setup and full starter CLI |
  722. | [`@chatpack/transport-redis`](./packages/transport-redis) | Redis pub/sub transport (multi-node SSE) |
  723. | [`@chatpack/file`](./packages/file) | Filepack-backed message attachments |
  724. | [`@chatpack/ui`](./packages/ui) | Reusable React chat UI blocks |
  725. ## Examples
  726. | Example | What it shows |
  727. | -------------------------------------------------- | -------------------------------------------------------- |
  728. | [`examples/messenger`](./examples/messenger) | **A complete 1:1 messenger** - vanilla HTML+JS, tutorial |
  729. | [`examples/next-backend`](./examples/next-backend) | The quickstart, runnable: Next.js App Router + SSE |
  730. | [`examples/node-server`](./examples/node-server) | Plain Node http server, in-memory or Postgres storage |
  731. ## Design principles
  732. - **Developers bring their own auth** - Chatpack never owns a users table.
  733. - **Adapter-driven** - storage is an interface; Postgres, MySQL, or in-memory
  734. are just adapters.
  735. - **Durable-first real-time** - a message is persisted before anyone is
  736. notified about it.
  737. - **Small surface, no magic** - every feature must justify its existence.
  738. Read more in [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md).
  739. ## Telemetry
  740. Chatpack ships **anonymous, opt-out telemetry**: aggregate counters only.
  741. Twice a day (at most) it POSTs a small JSON body - counter deltas
  742. (`messagesSent`, `conversationsCreated`), the library version, and a random
  743. per-process id that is never persisted. Never message bodies, user ids,
  744. conversation ids, or hostnames. The payload shape is a documented public type
  745. ([`TelemetryPayload`](./packages/core/src/telemetry.ts)) so you can audit
  746. exactly what leaves your server.
  747. Opt out any time - either works:
  748. ```ts
  749. chatpack({ storage, telemetry: false });
  750. ```
  751. ```sh
  752. CHATPACK_TELEMETRY=0
  753. ```
  754. Failures are silently ignored and the flush timer never keeps your process
  755. alive. Details in [docs/MVP.md §12](./docs/MVP.md).
  756. ## Community
  757. - **[Discord](https://discord.gg/gY3GCTRv5Y)** — chat with the team and other developers
  758. - **[GitHub Discussions](https://github.com/chddaniel/chatpack/discussions)** — questions, show-and-tell, and feedback
  759. - **[X](https://x.com/chatpackdev)** — releases and updates
  760. - **[Docs](https://docs.chatpack.dev)** — the full documentation site
  761. - **[npm](https://www.npmjs.com/package/@chatpack/core)** — every `@chatpack/*` package
  762. - **[Open an issue](https://github.com/chddaniel/chatpack/issues/new/choose)** — bugs and feature requests
  763. If you've built something with Chatpack, got stuck installing it, or have opinions about the API — we want to hear from you. The team reads everything.
  764. ## Contributing
  765. Contributions are very welcome - see [CONTRIBUTING.md](./CONTRIBUTING.md) for
  766. repo layout, dev workflow, and the adapter contract.
  767. ## Credits
  768. Chatpack is a project by **[CH Daniel](https://github.com/chddaniel)** and
  769. **[DavidCH](https://github.com/chhddavid)**, who own and maintain it.
  770. **[Ikem Peter](https://github.com/ikemHood)** contributes to Chatpack — the
  771. moderation suite, the client's message search and its invite, join-request and
  772. channel wrappers, and the CLI refresh. **[DavidCH](https://github.com/chhddavid)**
  773. contributes to the code as well as co-owning the project.
  774. | Role | |
  775. | --------------------------------------------- | ---------------------------------- |
  776. | **[CH Daniel](https://github.com/chddaniel)** | Project co-owner, maintainer |
  777. | **[DavidCH](https://github.com/chhddavid)** | Project co-owner, contributor |
  778. | **[Ikem Peter](https://github.com/ikemHood)** | Contributing developer, maintainer |
  779. Who wrote what is verifiable rather than asserted — see the
  780. [contributor graph](https://github.com/chddaniel/chatpack/graphs/contributors)
  781. or run `git shortlog -sne` in a clone.
  782. Citing Chatpack in a paper or writeup? See [`CITATION.cff`](./CITATION.cff), or
  783. use the "Cite this repository" button in the GitHub sidebar.
  784. ## License
  785. [MIT](./LICENSE)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.