Getting started
Adding chat to your service takes three things: an app created in the console, one backend endpoint that issues tokens, and the SDK in the browser.
npm install @kispi/chatThere are two entry points. The SDK has no runtime dependencies and includes type declarations.
| Entry point | Where | Key it uses |
|---|---|---|
@kispi/chat |
Browser (and Node) | publishable key (pk_) |
@kispi/chat/server |
Your backend | secret key (sk_) |
1. Create an app in the console
Sign up, then click New app. Each app is a tenant — users, rooms, messages, and keys are all scoped to the app. As soon as you create it, you get two keys.
| Key | Where it lives | What it does |
|---|---|---|
Publishable key (pk_…) |
Frontend code | Identifies the app, nothing more. It's public |
Secret key (sk_…) |
Backend environment variable | Grants access to all of the app's data. Used to issue tokens and call the server API |
The sk_ is shown only once, when you create it. The console doesn't store it, so move it to your
secrets store right away. If you lose it, issue a new sk_ and revoke the old one
(Rotating keys).
If you would rather create the app from a script or an AI than by clicking, one account key (ck_) is enough. See the Console API.
Allowed origins
The allowed origins you enter when creating the app are the origins of pages allowed to use this pk_
in the browser.
- Scheme, host, and port must match exactly.
https://example.comandhttps://www.example.comare different origins. - So are
http://localhost:3000andhttp://127.0.0.1:3000. Add your development origins separately. - Using the key from a page that isn't on the list is refused with
unauthorized. Change the list by clicking the allowed origins cell on the Keys screen.
2. Issue tokens on your backend
The engine doesn't know who anyone is. It verifies the token's signature and trusts the user id inside it at face value. Your service already knows who's logged in, so all you need is an endpoint that issues a token for that person.
// src/routes/api/chat-token/+server.ts (SvelteKit) — the shape is the same in any framework
import { json } from '@sveltejs/kit'
import { createChatServer } from '@kispi/chat/server'
import { env } from '$env/dynamic/private'
const chat = createChatServer({
secretKey: env.CHAT_SECRET_KEY // sk_…
})
export const POST = async ({ locals }) => {
const user = locals.user // your service's session
if (!user) return new Response(null, { status: 401 })
return json({
token: chat.token({
userId: String(user.id), // this person's id
name: user.nickname,
avatar: user.avatarUrl, // optional
ttlSeconds: 3600 // optional. Defaults to 1 hour, max 24 hours
})
})
}# chat_token() lives on the "Server integration" page — this only calls it
@app.post("/api/chat-token")
def issue_chat_token():
user = current_user() # your service's session
if user is None:
return "", 401
return {"token": chat_token(SK, str(user.id), user.nickname, ttl=3600)}// chatToken() lives on the "Server integration" page — this only calls it
func issueChatToken(w http.ResponseWriter, r *http.Request) {
user, ok := currentUser(r) // your service's session
if !ok {
http.Error(w, "", http.StatusUnauthorized)
return
}
token, err := chatToken(sk, user.ID, user.Nickname, time.Hour)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]string{"token": token})
}// chatToken() lives on the "Server integration" page — this only calls it
@PostMapping("/api/chat-token")
fun issueChatToken(session: HttpSession): Map<String, String> {
val user = session.user ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED)
return mapOf("token" to chatToken(sk, user.id.toString(), user.nickname))
}chat.token() signs locally without a network call, so it's fine to call it on every request — and the
same is true in every other language, since signing never touches the engine. name wins on every
connect. The token spec itself is in Server integration; for visitors who aren't
logged in, Guest users shows how the same endpoint issues them an identity.
3. Send and receive in the browser
On iOS, Android or Flutter, or in a language outside JS such as Swift, Kotlin, Dart or Python, follow the real-time protocol (WebSocket) and the REST API instead of this step's SDK. Step 2, issuing tokens, stays the same.
// chat.ts
import { createChatClient } from '@kispi/chat'
export const chat = createChatClient({
key: import.meta.env.VITE_CHAT_PK, // pk_…
token: async () => {
const res = await fetch('/api/chat-token', { method: 'POST' })
return (await res.json()).token
}
})
chat.on('state', (s) => setStatus(s)) // connecting | open | reconnecting | closed
chat.connect().catch(() => {})Reconnecting and token refresh are the SDK's job. Your backend creates rooms — opening a room by key
doesn't create it, and subscribing to a key that doesn't exist gives you not_found. rooms.ensure is
get-or-create: it returns the room if it already exists.
// Backend — the createChatServer instance from step 2
await chat.rooms.ensure({ key: 'lobby', type: 'public' })A room key uses only ASCII letters, digits, and _ . : -, 1 to 128 characters
(^[A-Za-z0-9_.:-]{1,128}$). Anything else, such as Korean text or a space, gets 400 invalid, so put the
human-readable title in name and keep key an ASCII alias like order-1234.
Everything below is back in the browser, on the createChatClient from step 3.
const room = chat.roomByKey('lobby')
await room.subscribe() // live feed + the latest 20 messages (the engine's default page)
room.on('messages', (all) => render(all)) // the whole list, every time it changes
room.on('message.created', (m) => append(m)) // or one new message at a time
const ack = await room.send({ text: 'Hello' }) // { messageId, seq }
await room.send({ text: 'Check this out', attachments: [{ type: 'image', url, key }] })
await room.react(ack.messageId, '👍')
await room.markRead(room.lastSeq)
room.typing()
const { hasMore } = await room.loadOlder() // as the user scrolls up. false at the beginningroom.messages is always in ascending seq order, with no gaps. It's a new array every time it changes,
so drop it straight into state that compares by reference (Svelte $state.raw, React useState,
Vue shallowRef). The engine doesn't store files — upload them to your own storage (S3 or similar)
and put the address in attachments (url must start with https://).
Always handle these two events.
reset— The SDK discarded the list and refilled it. Throw away what you rendered and redraw fromroom.messages.error— Reading history failed. The room resubscribes itself, so just surface it.
| Persisted? | After reconnecting | |
|---|---|---|
| Messages | Yes | The SDK fills the gaps |
| Reactions | Yes | Come with history. Changes made while disconnected (reactions, thread counts, edits, deletes) are applied by the SDK to the room's latest page (20 messages) on reconnect. For older rows, use reload() |
Read cursor (markRead) |
Yes | Reflected in the unread counts from rooms.list() |
| presence | No | Received fresh |
| typing | No | Fine to miss. It arrives at most once every 3 seconds per person, so show it for about 5 seconds after the last one. A room announces at most 3 people per 3-second window, so in a crowded room someone can be typing without being announced |
typing is also sent back to the sender — if you render "X is typing," skip your own userId.
Failures throw a ChatError; if err.code is rate_limited, wait err.retryAfterMs before retrying.
Limits
Rate and size limits are per app. The defaults are below; see and change them per app on the Limits tab in the console.
| Limit | Default | Counted per |
|---|---|---|
| Sending messages | 5 per second, burst of 10 | user |
| Reactions | 10 per second | user |
typing |
20 per second | user |
| Editing messages | 2 per second | user |
| Connecting | 10 per minute | user |
| Concurrent connections | 10 | user |
| Connection setup | 60 per minute | pk_ + IP |
| Subscriptions | 100 | connection |
| Message length | 4000 characters | message |
| Attachments | 10 | message |
| Distinct reactions | 20 | message |
| Frame size | 64 KB | connection |
| Stored messages | unlimited | app |
| Edit window | unlimited | message |
- Messages sent through the server API (
sk_) are not subject to the rate limits or the edit window. - Stored messages counts deleted messages (tombstones) too. When an app that has a cap is full, new messages
are refused with
quota_exceeded(REST 403). Waiting doesn't clear it, so don't retry. - You can raise rates and sizes up to the app's ceiling. Lowering works too, but the frame size can't go below
the 64 KB default. The send queue (
sendQueueSize) is fixed at the same value for every app. - Changes reach open connections within 30 seconds. Values fixed at connect time (connection rates, concurrent
connections, subscriptions, frame size) apply from the next connection. The current values also arrive in
hello.limitswhen you connect.
4. Webhooks (optional)
Use these when your backend needs to hear about publishes, edits, and deletes — push notifications, search
indexing, audit logs. There's also before_publish, which steps in before a message is published to
reject it or rewrite its body. The receiving code and signature verification are in
Webhooks.
Next
- Server integration — token spec, server API, key rotation.
- SDK reference — every method and event.
- Real-time protocol and REST API — for iOS, Android, Flutter and other languages without the SDK. There is a five-minute check from a terminal.
- Architecture and benchmarks — how much it holds, how we measured, and what we did not measure.