
Add chat to your app with ZabMessaging
Channels, stored history, typing and read receipts. One server address and one access key, with SDKs for web, mobile and backends.
Quick start How messaging works API reference Product details
ZabMessaging SDKs
A self-hosted messaging platform: channels with stored history, instant delivery, typing indicators and delivered / seen receipts, for live-stream comment sections, chat rooms and conversations. Connect from any platform with one server URL and one access key, subscribe to channels by name, and everything sent inside a channel is delivered to everyone subscribed to it.
Customer → App → Access key. Every access key (zk_…) opens exactly one app's private channels. Apps never see each other's channels or messages, even when they use the same channel names.
Choose your platform
Web & JavaScript
Browsers and Node.js. Zero dependencies: uses the platform WebSocket and fetch.
Tested against a live serverA provider and hooks: live values, lists and connection status in components.
Tested against a live serverNNext.jsApp Router and Pages Router: a server-side REST client plus live hooks for Client Components.
Tested against a live serverMobile & Desktop
Android, iOS, web and desktop. One app-wide connection, per-screen subscriptions.
Tested against a live serverCoroutines, StateFlow and Flow over an OkHttp WebSocket. Also runs on the plain JVM.
Build & test once before shippingA Swift Package with async/await and AsyncStream over URLSessionWebSocketTask. No dependencies.
Build & test once before shippingBackend & Desktop
ASP.NET Core, MAUI, WPF, Xamarin and Unity. ClientWebSocket, async/await, System.Text.Json.
Build & test once before shippingAn asyncio realtime client and a dependency-free blocking REST client.
Tested against a live serverGoGoA WebSocket client with channels and auto-reconnect, plus a stateless REST client.
Tested against a live serverPPHPA dependency-free REST client for Laravel, Symfony, WordPress and plain PHP.
Tested against a live serverAny other language
Everything the SDKs do is plain WebSocket JSON or REST. See the protocol reference to build a client for Ruby, Java, Rust, C++ or anything else in an afternoon.
What every SDK gives you
- Channels:
joina channel,sendmessages, get every new message instantly, loadhistoryseparately, show typing andseenreceipts. Whether ajoinbrings the old messages is an app option in the admin console. - Subscribe, send, store:
joinseveral channels at once,sendto everyone in a channel (you included) ortospecific users only, keep a message in the channel history or send it live-only with oneisStoreparameter, andleaveone channel orleaveAll. - Offline-safe: calls wait for the connection, your channels are joined again after every reconnect and the messages missed while offline are delivered.
- Server-aware: a wrong or revoked key stops retrying (the server locks an address out after 10 wrong keys a minute); a disabled key, suspended app, blocked IP or full connection limit is retried every 60 seconds. State and reason are exposed.
Status labels. Tested against a live server means our test suite for that SDK was run against a running ZabMessaging server. Build & test once before shipping means the code is complete; build and test it in your own project before you ship.
Why ZabMessaging
Most apps need the same thing: messages that several users or devices see as they happen, without you building and running a realtime backend first.
The problem it solves
A chat, a live-stream comment section, a notification feed or a support conversation needs a server that holds open connections, authenticates every client, keeps customers' messages apart, limits abuse and survives flaky mobile networks. That is weeks of work and a lot to get wrong. ZabMessaging is that backend, ready to run: you install it once on your server and your clients connect with a URL and a key.
How the pieces fit
your apps (Web, React, Next.js, Flutter, Android, iOS, .NET) your backends (Python, Go, PHP, Node, Next.js server)
| WebSocket: subscribe, send, receive | REST: post, history, moderate
v v
+---------------------------- ZabMessaging server ----------------------------+
| access key -> one APP -> its own channels and messages (quotas apply) |
+------------------------------------------------------------------------------+
admin console: customers, apps, keys, IP blocks, activity log, monitorWhy each part exists
| Part | Why it is there |
|---|---|
| Access key | One secret that says which app you are, with no user accounts to build. Each key opens exactly one app. Revoking or disabling it cuts that client off instantly, without touching anyone else. |
| Customer → App → Key | Lets one server host many customers (or many of your own products). Storage quota and connection limit are set on each app, so every project can have its own; every app is isolated, so a leak in one never exposes another. Channel names are per app: general in two apps is two separate channels. |
| Channels | A named room. Subscribing (join) is how a client starts receiving it. Everything that happens inside a channel (a new message, an edit, a delete) is broadcast to every subscriber, the sender included. |
| Store or not | One parameter per message, isStore: a stored message is kept in the channel and can be loaded as history; a live-only one is delivered now and never kept. A message is stored only when the app's Store messages setting is on and the sender passes isStore: true. |
| Private messages | to addresses a message to specific users inside the channel: only they (and the sender) receive it or see it in the history. Without to it goes to everyone. |
| Offline-safe SDKs | Phones lose signal. The SDKs queue calls until the connection is back, join your channels again after a reconnect and deliver the messages missed meanwhile, so a screen never stays stale. |
| WebSocket and REST | WebSocket for clients that listen live; REST for backends that just post or read. A message posted over REST reaches the live subscribers at once. |
| Heartbeat and probe | A connection can die silently (a Wi-Fi router unplugged). The SDK pings, notices within seconds, and asks the server why a connection failed, so it can tell “network down, retry” from “your key was revoked, stop”. See Reliability. |
| Per-platform SDKs | The wire protocol is plain JSON, but reconnection, backoff, rejoining channels, state reporting and idiomatic APIs are the hard part. The SDKs do it once, correctly, for each language, and all behave the same way. |
When not to use it
- You need per-channel security rules (who may join which channel) beyond the access key: not available yet; anyone holding an app's key can join any of its channels.
- Your message history is far larger than memory: each app's messages are held in RAM (bounded per channel by the Keep per channel setting) and journaled to disk.
- You need multi-server scale-out: one server today.
Quickstart
From zero to a live chat in five minutes.
- Sign in to the admin console at
https://your-server/admin. - Create a customer (name and e-mail).
- Create an app on the customer page, for example “Mobile app”: pick its platforms and set its storage quota and connection limit.
- Generate a key on the app page. It looks like
zk_plus 40 characters. Show key displays it again later. - Test the key with the console's API key tester, or from a shell:
curl -H "Authorization: Bearer zk_YOUR_ACCESS_KEY" https://your-server/whoamiThen give your app the server URL (https://your-server; wss://your-server/ws is accepted too) and the access key.
Pick your platform
JavaScript / Node.js SDK
npm install ./sdk/web/zab-messaging-js<script src="zab-messaging-js/dist/zab-messaging.global.js"></script>
<!-- or -->
<script type="module">
import { ZabMessaging } from './zab-messaging-js/dist/zab-messaging.mjs';
</script>npm install wsimport { ZabMessaging } from 'zab-messaging';
const zab = new ZabMessaging('https://your-server', { accessKey: 'zk_YOUR_ACCESS_KEY', userId: 'alice' });
await zab.connect(); // rejects if the key is refused
const room = zab.channel('live-stream-1'); // one channel per live stream / room
room.onMessage((m) => addComment(m)); // every new message, instantly
room.onTyping(({ users }) => showTyping(users)); // who is typing now
room.onReceipt((r) => tick(r.kind, r.upToSeq)); // 'delivered' | 'seen' for your messages
const joined = await room.join({ history: true, limit: 30 }); // LOAD OLD MESSAGES with the join: the 30 latest come back instantly, then only new ones arrive live
// (no option = follow the app's "history on join"; { history: false } = none)
// joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
await room.send('Hello everyone', { isStore: true }); // isStore: true = kept in the channel history; left out = live only
await room.send('psst', { to: 'bob' }); // PRIVATE: only bob (and you) get it; { to: ['bob', 'carol'] } for several
// bob receives it in the same room.onMessage(...) listener: m.to = ['bob'] marks a private message
await room.send('hearts!', { isStore: false }); // live only: delivered now, never in history (this is also the default when isStore is left out)
const page = await room.history({ limit: 30 }); // load old messages separately, any time (oldest first)
const older = await room.loadMore(); // the page before the oldest message loaded
room.setTyping(true); // call on every key press: the SDK throttles and stops it
await room.markSeen(); // everything up to the newest messageReact SDK
npm install ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-jsimport { ZabProvider, useZabChannel } from 'zab-messaging-react';
export default function App() {
return <ZabProvider url="https://your-server" accessKey="zk_YOUR_ACCESS_KEY" userId="alice"><Comments /></ZabProvider>;
}
function Comments() {
// joins on mount, leaves on unmount; messages = the history that comes with join (when the app enables it) + every new message
const { messages, send, typingUsers, setTyping, loadMore, hasMore, loading } = useZabChannel('live-stream-1');
return (<>
{hasMore && <button onClick={() => loadMore(20)}>Older comments</button>}
{messages.map((m) => <p key={m.id}>{m.from}: {m.deleted ? 'deleted' : m.text}</p>)}
{typingUsers.length > 0 && <small>{typingUsers.join(', ')} typing…</small>}
<input onChange={() => setTyping(true)} onKeyDown={(e) => e.key === 'Enter' && send(e.currentTarget.value)} />
</>);
}Next.js SDK
npm install ./sdk/nextjs/zab-messaging-next ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-jsZAB_URL=https://chat.example.com
ZAB_ACCESS_KEY=zk_SERVER_KEY # server only: never reaches the browser
NEXT_PUBLIC_ZAB_URL=https://chat.example.com
NEXT_PUBLIC_ZAB_ACCESS_KEY=zk_BROWSER_KEY # visible in the browser: use a separate, revocable keymodule.exports = { transpilePackages: ['zab-messaging-next', 'zab-messaging-react', 'zab-messaging'] };// Server code (Route Handler, Server Action): post and moderate messages with the server key. app/api/notice/route.js
import { createZabServer } from 'zab-messaging-next/server';
const zab = createZabServer(); // reads ZAB_URL and ZAB_ACCESS_KEY
export async function POST() {
const m = await zab.messages.send('live-stream-1', { text: 'The stream starts now', from: 'system' }); // reaches everyone joined at once
return Response.json(m);
}
// const { messages } = await zab.messages.history('live-stream-1', { limit: 50 });
// Client Component: the same hook as the React SDK
'use client';
import { ZabProvider, useZabChannel } from 'zab-messaging-next/client';
export function Comments() {
const { messages, send, typingUsers, setTyping } = useZabChannel('live-stream-1');
return messages.map((m) => <p key={m.id}>{m.from}: {m.text}</p>);
}Flutter SDK
dependencies:
zab_messaging:
path: ../ZabMessaging/sdk/flutter/zab_messaging # or your git / pub.dev sourceimport 'package:zab_messaging/zab_messaging.dart';
// main(): open the connection once
ZabMessagingIO.init('https://your-server', accessKey: 'zk_YOUR_ACCESS_KEY', userId: 'alice').open();
// a screen:
final room = ZabMessagingIO.instance.channel('live-stream-1'); // one channel per live stream / room
room.messages.listen((m) => setState(() => comments.add(m))); // every new message, instantly
room.typing.listen((t) => setState(() => typingNow = t.users));
room.receipts.listen((r) => print(r.userId + ' ' + r.kind + ' up to ' + r.upToSeq.toString()));
final joined = await room.join(); // joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
await room.send('Hello everyone'); // or room.send(null, data: {'gift': 'rose'})
await room.send('psst', to: ['bob']); // PRIVATE: only bob (and you) get it; bob listens on room.messages, m.isPrivate
final page = await room.history(limit: 30); // load old messages separately, any time (oldest first)
final older = await room.loadMore(); // the page before the oldest message loaded
room.setTyping(true); // call on every key press: the SDK throttles and stops it
await room.markSeen(); // everything up to the newest messageAndroid (Kotlin) SDK
include(":zab-messaging")
project(":zab-messaging").projectDir = file("path/to/ZabMessaging/sdk/android/zab-messaging")dependencies { implementation(project(":zab-messaging")) }
// or, after ./gradlew :zab-messaging:publishToMavenLocal:
// implementation("com.zabsys:zab-messaging:1.0.0")<!-- http://10.0.2.2:8080 needs cleartext traffic; use https in production -->
<application android:usesCleartextTraffic="true" ... />val zab = ZabMessaging("https://your-server", "zk_YOUR_ACCESS_KEY", ZabOptions(userId = "alice")) // ONE instance for the whole app
zab.connect()
val room = zab.channel("live-stream-1") // one channel per live stream / room
room.onMessage { m -> println(m.from + ": " + m.text) } // every new message, instantly (or: room.messages.collect { ... })
room.onTyping { t -> println(t.users.toString() + " typing") }
val joined = room.join() // joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
room.send("Hello everyone") // or room.send(data = mapOf("gift" to "rose"))
val page = room.history(limit = 30) // load old messages separately, any time (oldest first)
val older = room.loadMore() // the page before the oldest message loaded
room.setTyping(true) // call on every key press: the SDK throttles and stops it
room.markSeen() // everything up to the newest messageiOS & macOS (Swift) SDK
File → Add Package Dependencies… → Add Local… → choose sdk/iosdependencies: [ .package(path: "../ZabMessaging/sdk/ios") ], // or your Git URL once published
targets: [ .target(name: "MyApp", dependencies: [.product(name: "ZabMessaging", package: "ios")]) ]import ZabMessaging
let zab = try ZabMessaging(url: "https://your-server", accessKey: "zk_YOUR_ACCESS_KEY", options: ZabOptions(userId: "alice")) // ONE instance for the app
try await zab.connect()
let room = try zab.channel("live-stream-1") // one channel per live stream / room
let sub = room.onMessage { m in print(m.from, m.text ?? "") } // every new message, instantly (or: for await m in room.messages())
let typing = room.onTyping { t in print(t.users, "typing") }
let joined = try await room.join() // joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
try await room.send("Hello everyone") // or room.send(data: ["gift": "rose"])
let page = try await room.history(limit: 30) // load old messages separately, any time (oldest first)
let older = try await room.loadMore() // the page before the oldest message loaded
room.setTyping(true) // call on every key press: the SDK throttles and stops it
try await room.markSeen() // everything up to the newest message.NET (C#) SDK
dotnet add reference ./sdk/dotnet/ZabMessaging/ZabMessaging.csproj
# or: dotnet pack ./sdk/dotnet/ZabMessaging -c Release then publish ZabSys.Messaging to your NuGet feedusing ZabSys.Messaging;
await using var zab = new ZabMessaging("https://your-server", "zk_YOUR_ACCESS_KEY", new ZabOptions { UserId = "alice" }); // ONE instance per app
await zab.ConnectAsync();
var room = zab.Channel("live-stream-1"); // one channel per live stream / room
room.MessageReceived += m => Console.WriteLine($"{m.From}: {m.Text}"); // every new message, instantly (or: await foreach (var m in room.MessagesAsync()))
room.TypingChanged += t => Console.WriteLine($"{string.Join(", ", t.Users)} typing");
var joined = await room.JoinAsync(); // joined.Messages = latest messages when you join with the history option on (or the app has "history on join" on)
await room.SendAsync("Hello everyone"); // or room.SendAsync(data: new { gift = "rose" })
var page = await room.HistoryAsync(limit: 30); // load old messages separately, any time (oldest first)
var older = await room.LoadMoreAsync(); // the page before the oldest message loaded
room.SetTyping(true); // call on every key press: the SDK throttles and stops it
await room.MarkSeenAsync(); // everything up to the newest messagePython SDK
pip install ./sdk/pythonimport asyncio
from zab_messaging import ZabMessaging, ZabRest
async def main():
async with ZabMessaging("https://your-server", access_key="zk_YOUR_ACCESS_KEY", user_id="alice") as zab: # connects, disconnects on exit
room = zab.channel("live-stream-1") # one channel per live stream / room
room.on_message(lambda m: print(m["from"], m["text"])) # every new message, instantly
room.on_typing(lambda t: print(t["users"], "typing"))
joined = await room.join() # joined["messages"] = latest messages when you join with the history option on (or the app has "history on join" on)
await room.send("Hello everyone", is_store=True) # is_store=True = kept in the channel history; left out = live only
await room.send("psst", to="bob") # PRIVATE: only bob (and you) get it; to=["bob", "carol"] for several
page = await room.history(limit=30) # load old messages separately, any time (oldest first)
older = await room.load_more() # the page before the oldest message loaded
room.set_typing(True) # call on every key press: the client throttles and stops it
await room.mark_seen() # everything up to the newest message
await asyncio.sleep(60)
asyncio.run(main())
# A script or web view (blocking, no websocket): post as the server
ZabRest("https://your-server", "zk_YOUR_ACCESS_KEY").send("live-stream-1", "The stream starts now", from_user="system")Go SDK
go get github.com/zabsys/zabmessaging-go
# from the SDK folder:
go mod edit -replace github.com/zabsys/zabmessaging-go=./sdk/goclient, _ := zabmessaging.New("https://your-server", "zk_YOUR_ACCESS_KEY", zabmessaging.Options{UserID: "alice"})
ctx := context.Background()
_ = client.Connect(ctx)
defer client.Close()
room, _ := client.Channel("live-stream-1") // one channel per live stream / room
room.OnMessage(func(m zabmessaging.Message) { fmt.Println(m.From, m.Text) }) // every new message, instantly
room.OnTyping(func(t zabmessaging.TypingEvent) { fmt.Println(t.Users, "typing") })
joined, _ := room.Join(ctx) // joined.Messages = latest messages when you join with the history option on (or the app has "history on join" on)
room.Send(ctx, "Hello everyone") // or room.Send(ctx, "", zabmessaging.SendOptions{Data: map[string]any{"gift": "rose"}})
page, _ := room.History(ctx, zabmessaging.HistoryOptions{Limit: 30}) // load old messages separately, any time (oldest first)
older, _ := room.LoadMore(ctx, 30) // the page before the oldest message loaded
room.SetTyping(true) // call on every key press: the client throttles and stops it
room.MarkSeen(ctx, "") // everything up to the newest messagePHP SDK
composer require zabsys/zab-messaging
# or a path repository pointing at ./sdk/phpuse ZabMessaging\ZabMessaging;
// PHP requests are short-lived, so PHP does not hold a live channel: it posts and reads over REST. Browsers and apps join.
$zab = new ZabMessaging('https://your-server', 'zk_YOUR_ACCESS_KEY');
$m = $zab->send('live-stream-1', 'The stream starts now', ['kind' => 'notice'], 'system'); // reaches everyone joined at once
$page = $zab->history('live-stream-1', limit: 30); // oldest first: ['messages' => [...], 'hasMore' => bool, 'lastSeq' => int]
$older = $zab->history('live-stream-1', limit: 30, before: $page['messages'][0]['seq']);
$zab->editMessage('live-stream-1', $m['id'], 'The stream starts in 5 minutes');
$zab->deleteMessage('live-stream-1', $m['id']);
$zab->clearChannel('live-stream-1'); // moderation: delete every message
$channels = $zab->channels(); // newest activity firstMessaging (channels)
zab.isConnected (and zab.status) tell whether you are connected, zab.joinedChannels / zab.isJoined(name) which channels you are subscribed to, await zab.members(channel) the users online in any channel (no join needed), and await zab.stats({ users: true }) the app-wide totals (users, connections, active channels) with the busiest channels and who is in each. Every SDK has the same functions; the backend REST API has GET /msg?view=stats and GET /msg/<channel>?view=members.setTyping(true) on key presses, markSeen() when the chat is on screen. The authors get delivered and seen receipts.History on join is an app option
In the admin console open the app, then Messaging → Settings:
| Option | Default | Meaning |
|---|---|---|
| Clients may create channels | on | On: the first join or message creates a channel. Off: only channels you create in the admin console (Create channel) or your backend creates (PUT /msg/<channel>) exist. |
| Store messages | on | Asked when the app is created. On: a message is stored only when the sender passes isStore: true (anything else is live only: delivered now, never in history). Off: nothing is stored, even with isStore: true. |
| History on join | off | On: join() returns the latest N messages, so a viewer sees earlier comments the moment they join. Off: nothing comes with join; the client calls history() when it wants old messages. history() always works. |
| Messages sent on join | 50 | 1 to 1000. Older pages: history({before: seq}) or loadMore(). |
| Keep per channel | 10,000 | The oldest messages beyond this are dropped. |
| Typing / receipts / presence | on | Each can be switched off for the app. |
Channels belong to one app. The same channel name in two apps (even of the same customer) is two separate channels: separate messages, members and numbering, and an access key only ever reaches its own app's channels.
The join call decides, too. join({history: true}) loads the latest messages with that join even when the app option is off, join({history: false}) skips them even when it is on, and no option follows the app. limit asks for fewer messages than the app's Messages sent on join, never for more (older pages: history({before})).
Message storage counts toward the app's storage quota.
Messages
| Field | Meaning |
|---|---|
id, seq | Unique id, and a number that grows by one inside the channel. Remember the newest seq to catch up after a disconnect (the SDKs do it for you). |
from | The user id of the sender: the id you pass when connecting (userId / user_id). It is a label, not a credential: anyone with the app's key can claim any id, so hand out ids from your own backend. |
text, data | Up to 8,000 bytes of text and/or up to 16 KB of any JSON (a gift, a sticker, a vote). |
to | Private message: the user ids it was addressed to (up to 100). Only they and the sender receive it, see it in history, in unread counts and receipts, and get its edits and deletes. Absent on a message for the whole channel. The backend REST API and the admin console see every message. |
ts, editedAt, deleted | Milliseconds since the epoch. A deleted message stays as a tombstone so the numbering does not change. |
Receipts, typing and presence
- Delivered: the server records it when it hands a message to a connected member. Seen: reported by the client with
markSeen(). Only the authors of the newly delivered / seen messages are told. - Typing expires on the server after 6 seconds; the SDKs throttle updates and stop typing when you send.
- Large channels: above 500 members join / leave events are not broadcast; above 200 members receipts are not generated. Messages, history and typing work at any size.
From your backend (REST)
curl -X POST https://your-server/msg/live-stream-1 \
-H "Authorization: Bearer zk_YOUR_ACCESS_KEY" -H "Content-Type: application/json" \
-d '{"text":"The stream starts now","from":"system"}'
# private message to two users only: -d '{"text":"hi","from":"system","to":["bob","carol"]}'
# history, newest page: GET /msg/live-stream-1?limit=30 older: ...&before=120
# edit PATCH /msg/<channel>/<id> delete DELETE /msg/<channel>/<id> clear DELETE /msg/<channel>WebSocket protocol
Operations are msg.* on the same connection (wss://your-server/ws?key=zk_…&user_id=alice): the channel goes in path, arguments in data.
{"id":"1","op":"msg.join","path":"live-stream-1"}
{"id":"2","op":"msg.send","path":"live-stream-1","data":{"text":"hello"}}
{"id":"3","op":"msg.history","path":"live-stream-1","data":{"limit":30,"before":120}}
{"id":"4","op":"msg.typing","path":"live-stream-1","data":{"typing":true}}
{"id":"5","op":"msg.seen","path":"live-stream-1","data":{"upTo":"<message id>"}}| Operation | Arguments | Result |
|---|---|---|
msg.join | history, limit, after | online, lastSeq, unread, historyOnJoin, messages?, hasMore? |
msg.send | text and/or data, replyTo, clientId, isStore, to | message, delivered (to = private message to those user ids) |
msg.history | limit, before, after, receipts | messages (oldest first), hasMore, lastSeq |
msg.edit / msg.delete | id (+ text / data) | message (author only) |
msg.typing, msg.seen, msg.delivered | typing / upTo, upToSeq | |
msg.members, msg.stats, msg.channels, msg.unread, msg.receipts, msg.config, msg.leave |
Events pushed to joined connections: msg.message, msg.updated, msg.deleted, msg.typing, msg.receipt, msg.presence, msg.cleared. Socket.IO uses the same names as events with acks.
Try it all in the messaging playground served by your ZabMessaging server (/playground).
Core concepts
Five ideas: the access key, the channel, the message, the user id and the private message.
Channels
A channel is a name (1 to 128 characters, no /). A client subscribes by joining it and then receives everything that happens inside: new messages, edits, deletions, who is typing, delivered / seen receipts, who joins and leaves. Subscribe to as many channels as you like on one connection (up to 100) and leave any of them, or all, at any time. Channels belong to one app: the same name in two apps is two separate channels.
Messages
| Call | What it does |
|---|---|
| send | Sends a message into a channel you joined. It is delivered to every subscriber, including you (your own message arrives through the same listener as everybody's). |
| isStore | One parameter per message. true: kept in the channel history. false or omitted: live only, delivered now and never kept. Stored only while the app's Store messages setting is on. Stored messages belong to their channel only. |
| to | A user id or a list of ids: a private message inside the channel. Only those users and the sender receive it or see it in the history. Omitted: everyone in the channel. |
| join(history) | Subscribes. history: true loads the old (stored) messages with the join, after which only new messages arrive live; false skips them; omitted follows the app setting. |
| history | Loads old messages separately, any time, oldest first, in pages (before / after). |
| edit / delete | The author changes or removes a message; everyone subscribed is told (the message stays as a tombstone so the numbering does not change). |
| leave / leaveAll | Unsubscribes from one channel or from every channel. Nothing is deleted: leaving only stops the stream. |
{ "id": "-Oxk3…", "channel": "live-42", "seq": 17, "from": "alice", "text": "hi", "ts": 1710000000000, "to": ["bob"] }User IDs
Every connection and request can carry an optional user ID: any string you choose (your own user id, an e-mail, a device name, up to 128 characters). It is the from of your messages and what to is matched against, and the admin console shows it on every row of the activity log, so you can see who sent each request, filter to one user, and search by it.
- It is a label for people, not a credential: it grants nothing and is not checked against anything. Anyone holding the app's key can claim any id, so hand out ids (and keys) from your own backend when private messages must stay private.
- Not provided? The SDK generates a random id (
u_+ 8 hex characters) and keeps it for the life of the client (browsers remember it between page loads). Clients that send nothing at all (curl, a bare WebSocket) get ananon_…id from the server: random per realtime connection, and derived from the client's address for stateless REST calls so one client keeps one id. - Backends that act for many end users (a web server, a worker) should pass the end user's id on each call:
zab.as(userId),rest.as_user(id),rest.As(id),$zab->as($id). - Signed in later?
setUserIdre-identifies the live connection and keeps your channels.
Customer, app, key
| Level | Meaning |
|---|---|
| Customer | Your client or tenant. Groups apps and can be suspended: that cuts every live connection of every one of its apps. |
| App | One private messaging space with its own storage quota and connection limit. A customer's “Mobile app” and “Website” never see each other's channels and can have different limits. |
| User ID | Optional label for the end user behind a request, shown in the activity log. Yours, or generated when you send none. |
| Access key | zk_ + 40 characters. Opens exactly one app. Can be disabled and enabled again, or revoked permanently. Both cut live connections immediately. |
JavaScript / Node.js SDK
Browsers and Node.js. Zero dependencies: uses the platform WebSocket and fetch.
Why this SDK? Use it for any web page, a Node.js service, a CLI or a bot. It has no dependencies, so it adds almost nothing to your bundle, and it is the base the React and Next.js SDKs are built on. Pick it when you want live channels in the browser or in Node.js without a framework.
Requirements
- Any modern browser
- Node.js 18+ (22+ has WebSocket built in)
- ES module, CommonJS and <script> builds
- TypeScript types included
Install
npm (from the SDK folder)
npm install ./sdk/web/zab-messaging-jsBrowser, without a bundler
<script src="zab-messaging-js/dist/zab-messaging.global.js"></script>
<!-- or -->
<script type="module">
import { ZabMessaging } from './zab-messaging-js/dist/zab-messaging.mjs';
</script>Node.js 18 / 20 (no built-in WebSocket)
npm install wsQuick start: subscribe, send, receive
import { ZabMessaging } from 'zab-messaging';
const zab = new ZabMessaging('https://your-server', { accessKey: 'zk_YOUR_ACCESS_KEY', userId: 'alice' });
await zab.connect(); // rejects if the key is refused
const room = zab.channel('live-stream-1'); // one channel per live stream / room
room.onMessage((m) => addComment(m)); // every new message, instantly
room.onTyping(({ users }) => showTyping(users)); // who is typing now
room.onReceipt((r) => tick(r.kind, r.upToSeq)); // 'delivered' | 'seen' for your messages
const joined = await room.join({ history: true, limit: 30 }); // LOAD OLD MESSAGES with the join: the 30 latest come back instantly, then only new ones arrive live
// (no option = follow the app's "history on join"; { history: false } = none)
// joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
await room.send('Hello everyone', { isStore: true }); // isStore: true = kept in the channel history; left out = live only
await room.send('psst', { to: 'bob' }); // PRIVATE: only bob (and you) get it; { to: ['bob', 'carol'] } for several
// bob receives it in the same room.onMessage(...) listener: m.to = ['bob'] marks a private message
await room.send('hearts!', { isStore: false }); // live only: delivered now, never in history (this is also the default when isStore is left out)
const page = await room.history({ limit: 30 }); // load old messages separately, any time (oldest first)
const older = await room.loadMore(); // the page before the oldest message loaded
room.setTyping(true); // call on every key press: the SDK throttles and stops it
await room.markSeen(); // everything up to the newest messagejoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | const r = await room.join({ history?: true | false, limit? }) (history: true = load old messages with the join) |
| Send a message | await room.send(text | { text, data, replyTo }, { isStore?, to? }) (to: user id or [ids] = private message) |
| Receive (live) | room.onMessage(cb) · onUpdated · onDeleted · onTyping · onReceipt · onPresence · onCleared |
| Load old messages (separate) | await room.history({ limit, before, after, receipts }) |
| Load an older page | await room.loadMore(limit) |
| Typing indicator | room.setTyping(true | false) |
| Mark seen (receipts) | await room.markSeen(upToMessage?) |
| Edit / delete | await room.edit(id, text) · await room.delete(id) |
| Members, unread, receipts, channels | await room.members() · room.unread() · room.receipts(id) · zab.channels() · zab.messagingConfig() |
| Connected? joined channels? who is online? stats | zab.isConnected · zab.status · zab.joinedChannels · zab.isJoined(name) · await zab.members(channel) (users of ANY channel) · await zab.stats({ prefix, users: true, limit }) (totals + users per channel) |
| Leave (one / all) | await room.leave() (this channel) · await zab.leaveAll() (every channel) · zab.joinedChannels |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
Node.js: index.mjs
import { ZabMessaging } from 'zab-messaging';
// Node 22+ has WebSocket built in. On Node 18 / 20: import WebSocket from 'ws'; and pass { accessKey, WebSocket }
const zab = new ZabMessaging(process.env.ZAB_URL, { // e.g. https://chat.example.com
accessKey: process.env.ZAB_ACCESS_KEY, // zk_...
userId: 'alice', // optional: empty = generated
});
zab.on('state', (state, reason) => console.log('connection:', state, reason ?? ''));
try {
await zab.connect(); // rejects with code 'unauthorized' when the key is refused
} catch (e) {
console.error('cannot connect:', e.code, e.message);
process.exit(1);
}
// 1. subscribe to channels by name: join() is the subscription
const room = zab.channel('live-42');
room.onMessage((m) => console.log(m.from + ':', m.text)); // everything new, for everyone in the channel (you too)
room.onUpdated((m) => console.log('edited:', m.id, m.text));
room.onDeleted((d) => console.log('deleted:', d.id));
const { messages } = await room.join({ history: true, limit: 30 }); // + the 30 latest old messages
messages.forEach((m) => console.log('(old)', m.from + ':', m.text));
// 2. send: only possible inside a channel you joined
await room.send('Hello everyone', { isStore: true }); // isStore: true = kept in the history; broadcast to all
await room.send('psst', { to: ['bob'] }); // private: only bob (and you)
await room.send('hearts!', { isStore: false }); // live only: never in history
// 3. leave one channel, or all of them, and close
await room.leave();
await zab.leaveAll();
zab.destroy();Browser: index.html
<!doctype html>
<html>
<body>
<input id="channel" placeholder="channel name"> <button id="join">Subscribe</button>
<ul id="list"></ul>
<input id="text" disabled> <button id="send" disabled>Send</button>
<script type="module">
import { ZabMessaging } from './zab-messaging-js/dist/zab-messaging.mjs';
const zab = new ZabMessaging('https://chat.example.com', { accessKey: 'zk_YOUR_ACCESS_KEY' });
await zab.connect();
let room = null;
document.getElementById('join').onclick = async () => {
room = zab.channel(document.getElementById('channel').value);
room.onMessage((m) => { // everything new in the channel, your own messages included
const li = document.createElement('li'); li.textContent = m.from + ': ' + m.text;
document.getElementById('list').append(li);
});
await room.join({ history: true }); // subscribe + the old messages
document.getElementById('text').disabled = document.getElementById('send').disabled = false;
};
document.getElementById('send').onclick = () => room.send(document.getElementById('text').value);
</script>
</body>
</html>User ID (optional)
Pass any id you like for the end user. Without one, the SDK generates a random id (u_ + 8 hex characters) and, in browsers, remembers it between page loads. It is the from of your messages and what to (private messages) is matched against.
const zab = new ZabMessaging(url, { accessKey, userId: 'alice@example.com' });
console.log(zab.userId); // alice@example.com (or the generated id)
// the user signs in later: re-identify the live connection, joined channels are kept
zab.setUserId('bob@example.com');Many channels at once
Subscribe to as many channels as you like on the one connection, leave one, or leave all.
const news = zab.channel('news'), sports = zab.channel('sports');
news.onMessage((m) => console.log('news:', m.text));
sports.onMessage((m) => console.log('sports:', m.text));
await Promise.all([news.join({ history: true }), sports.join()]);
console.log(zab.joinedChannels); // ['news', 'sports']
await news.leave(); // unsubscribe from one channel
await zab.leaveAll(); // unsubscribe from every channelPrivate messages and Store
Everything you send is broadcast to every subscriber of the channel, including you. to narrows it to those users (and you); isStore decides whether it is kept in the channel history.
await room.send('hello everyone'); // everybody in the channel
await room.send('psst', { to: ['bob', 'carol'] }); // only bob, carol (and you)
await room.send('hearts!', { isStore: false }); // live only: never in history
const { messages } = await room.join({ history: true, limit: 30 }); // old messages come WITH the joinConnection state and errors
The SDK reconnects by itself and joins your channels again. When the server refuses the key it stops: a wrong, revoked or deleted key ends in rejected (and connect() rejects with unauthorized); a suspended account or a disabled key is retried gently every minute.
zab.on('state', (state, reason) => console.log(state, reason)); // disconnected | connecting | connected | rejected
try {
await zab.connect();
} catch (e) {
if (e.code === 'unauthorized') showLogin(); // wrong / revoked key
else console.warn(e.code, e.message); // rejected | timeout | disconnected | invalid | server
}
zab.useAccessKey('zk_NEW_KEY'); // swap keys without losing your channelsNode.js 18 / 20
Pass the WebSocket class from the ws package.
import WebSocket from 'ws';
const zab = new ZabMessaging(url, { accessKey, WebSocket });Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
React SDK
A provider and hooks: live values, lists and connection status in components.
Why this SDK? React re-renders when state changes, but messages arrive from outside React. The useZabChannel hook bridges the two: it subscribes when a component mounts, unsubscribes when it unmounts, keeps the message list up to date (new messages, edits and deletions) and fills in what was missed during a disconnect.
Requirements
- React 18+
- Depends on zab-messaging (the JavaScript SDK)
- Works with Vite, CRA, Remix, Expo web
Install
npm (from the SDK folder)
npm install ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-jsQuick start: subscribe, send, receive
import { ZabProvider, useZabChannel } from 'zab-messaging-react';
export default function App() {
return <ZabProvider url="https://your-server" accessKey="zk_YOUR_ACCESS_KEY" userId="alice"><Comments /></ZabProvider>;
}
function Comments() {
// joins on mount, leaves on unmount; messages = the history that comes with join (when the app enables it) + every new message
const { messages, send, typingUsers, setTyping, loadMore, hasMore, loading } = useZabChannel('live-stream-1');
return (<>
{hasMore && <button onClick={() => loadMore(20)}>Older comments</button>}
{messages.map((m) => <p key={m.id}>{m.from}: {m.deleted ? 'deleted' : m.text}</p>)}
{typingUsers.length > 0 && <small>{typingUsers.join(', ')} typing…</small>}
<input onChange={() => setTyping(true)} onKeyDown={(e) => e.key === 'Enter' && send(e.currentTarget.value)} />
</>);
}join subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | const chat = useZabChannel(name, { history, limit, autoSeen }) (joins on mount; history: true loads old messages with the join) |
| Send a message | await chat.send(text | { text, data }) |
| Receive (live) | chat.messages · chat.typingUsers · chat.online · chat.unread · chat.loading · chat.error |
| Load old messages (separate) | chat.messages already holds the history that came with join; await chat.loadMore(n) for older ones |
| Load an older page | await chat.loadMore(limit) · chat.hasMore |
| Typing indicator | chat.setTyping(true) |
| Mark seen (receipts) | await chat.markSeen(upToMessage?) (or autoSeen: true) |
| Edit / delete | await chat.edit(id, text) · await chat.remove(id) |
| Members, unread, receipts, channels | chat.channel (the underlying channel object for members(), receipts()...) |
| Connected? joined channels? who is online? stats | const { isConnected, joinedChannels } = useZabState() · const { members, online } = useZabMembers(channel) · const { stats } = useZabStats({ users: true }) |
| Leave (one / all) | (leaves on unmount) |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
src/main.jsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { ZabProvider } from 'zab-messaging-react';
import App from './App';
createRoot(document.getElementById('root')).render(
<ZabProvider url={import.meta.env.VITE_ZAB_URL} accessKey={import.meta.env.VITE_ZAB_KEY} userId="alice">
<App />
</ZabProvider>,
);src/App.jsx
import { useState } from 'react';
import { useZabChannel, useZabState } from 'zab-messaging-react';
function Chat({ name }) {
// joins on mount, leaves on unmount; history: true loads the old messages with the join
const { messages, send, typingUsers, setTyping, loading, error } = useZabChannel(name, { history: true, autoSeen: true });
const [text, setText] = useState('');
if (error) return <p>Could not subscribe: {error.message}</p>;
return (
<div>
{loading && <p>Joining…</p>}
{messages.map((m) => <p key={m.id}>{m.from}: {m.deleted ? '(deleted)' : m.text}</p>)}
{typingUsers.length > 0 && <small>{typingUsers.join(', ')} typing…</small>}
<input value={text} onChange={(e) => { setText(e.target.value); setTyping(true); }} />
<button onClick={() => { send(text); setText(''); }}>Send</button>
<button onClick={() => send(text, { to: ['bob'] })}>Send only to bob</button>
</div>
);
}
export default function App() {
const { state, lastError } = useZabState();
const [channel, setChannel] = useState('');
const [joined, setJoined] = useState(null);
return (
<>
{state === 'rejected' && <p>The server refused this key: {lastError}</p>}
<input value={channel} onChange={(e) => setChannel(e.target.value)} placeholder="channel name" />
<button onClick={() => setJoined(channel)}>Subscribe</button>
<button onClick={() => setJoined(null)}>Unsubscribe</button>
{joined && <Chat name={joined} />}
</>
);
}.env
VITE_ZAB_URL=https://chat.example.com
VITE_ZAB_KEY=zk_YOUR_ACCESS_KEYUser ID
Pass the signed-in user's id to the provider. When it changes (sign-in, sign-out) the live connection is re-identified without losing the joined channels.
The channel hook
| Name | Description |
|---|---|
useZabChannel(name, { history, limit, autoSeen }) | Joins on mount, leaves on unmount. Returns { messages, send, edit, remove, typingUsers, setTyping, markSeen, loadMore, hasMore, online, unread, loading, error, channel }. history: true loads the old messages with the join. |
useZabState() | { state, isConnected, lastError }: the connection status. |
useZab() | The underlying client, for anything the hooks do not cover (joinedChannels, leaveAll(), channels()). |
Private messages and Store
const { send } = useZabChannel('live-42');
send('hello everyone'); // everybody subscribed (you too)
send('psst', { to: ['bob'] }); // only bob (and you)
send('hearts!', { isStore: false }); // live only: never in historyConnection banner
function Banner() {
const { state, lastError } = useZabState();
if (state === 'connected') return null;
return <div className="banner">{state === 'rejected' ? 'The server refused this key: ' + lastError : 'Reconnecting…'}</div>;
}Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
NNext.js SDK
App Router and Pages Router: a server-side REST client plus live hooks for Client Components.
Why this SDK? Next.js runs code in two places. Server code (Server Components, Route Handlers, Server Actions) is short-lived and keeps secrets, so it uses stateless REST with a server-only key to post and moderate messages. Browser code (Client Components) uses the live hook with a browser key, so each side gets the right tool and the right key.
Requirements
- Next.js 13.4+ (App Router or Pages Router)
- React 18+
/serverentry: Route Handlers, Server Components, Server Actions, middleware/cliententry: Client Components
Install
npm (from the SDK folder)
npm install ./sdk/nextjs/zab-messaging-next ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-js.env.local
ZAB_URL=https://chat.example.com
ZAB_ACCESS_KEY=zk_SERVER_KEY # server only: never reaches the browser
NEXT_PUBLIC_ZAB_URL=https://chat.example.com
NEXT_PUBLIC_ZAB_ACCESS_KEY=zk_BROWSER_KEY # visible in the browser: use a separate, revocable keynext.config.js (when installed from a local folder)
module.exports = { transpilePackages: ['zab-messaging-next', 'zab-messaging-react', 'zab-messaging'] };Quick start: subscribe, send, receive
// Server code (Route Handler, Server Action): post and moderate messages with the server key. app/api/notice/route.js
import { createZabServer } from 'zab-messaging-next/server';
const zab = createZabServer(); // reads ZAB_URL and ZAB_ACCESS_KEY
export async function POST() {
const m = await zab.messages.send('live-stream-1', { text: 'The stream starts now', from: 'system' }); // reaches everyone joined at once
return Response.json(m);
}
// const { messages } = await zab.messages.history('live-stream-1', { limit: 50 });
// Client Component: the same hook as the React SDK
'use client';
import { ZabProvider, useZabChannel } from 'zab-messaging-next/client';
export function Comments() {
const { messages, send, typingUsers, setTyping } = useZabChannel('live-stream-1');
return messages.map((m) => <p key={m.id}>{m.from}: {m.text}</p>);
}join subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | 'use client': useZabChannel(name) (joins on mount) |
| Send a message | client: chat.send(text) · server: await zab.messages.send(channel, text | { text, data, from }) |
| Receive (live) | client: chat.messages · chat.typingUsers |
| Load old messages (separate) | server: await zab.messages.history(channel, { limit, before, after }) · client: chat.loadMore(n) |
| Load an older page | chat.loadMore(limit) |
| Typing indicator | client: chat.setTyping(true) |
| Mark seen (receipts) | client: chat.markSeen() |
| Edit / delete | server: zab.messages.edit(ch, id, text) · delete(ch, id) · clear(ch) |
| Members, unread, receipts, channels | server: zab.messages.channels({ prefix }) |
| Connected? joined channels? who is online? stats | await zab.messages.members(channel) · await zab.messages.stats({ prefix, users: true, limit }) (server side, over REST) |
| Leave (one / all) | (leaves on unmount) |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
app/providers.jsx
'use client';
import { ZabProvider } from 'zab-messaging-next/client';
export default function Providers({ children }) {
return <ZabProvider>{children}</ZabProvider>; // url and key come from NEXT_PUBLIC_ZAB_URL / NEXT_PUBLIC_ZAB_ACCESS_KEY
}app/layout.jsx
import Providers from './providers';
export default function RootLayout({ children }) {
return <html><body><Providers>{children}</Providers></body></html>;
}app/chat/page.jsx (Server Component: first paint from the server)
import { createZabServer } from 'zab-messaging-next/server';
import Live from './live';
export const dynamic = 'force-dynamic';
export default async function Page() {
const zab = createZabServer(); // ZAB_URL + ZAB_ACCESS_KEY (server-only variables)
const { messages } = await zab.messages.history('live-42', { limit: 30 });
return <Live initial={messages} />;
}app/chat/live.jsx (Client Component: live after that)
'use client';
import { useZabChannel } from 'zab-messaging-next/client';
export default function Live({ initial }) {
const { messages, send } = useZabChannel('live-42'); // subscribes on mount, every new message arrives live
const all = messages.length ? messages : initial;
return (
<div>
{all.map((m) => <p key={m.id}>{m.from}: {m.text}</p>)}
<button onClick={() => send('hi')}>Send</button>
</div>
);
}app/api/send/route.js (Route Handler: post from the server)
import { NextResponse } from 'next/server';
import { createZabServer } from 'zab-messaging-next/server';
const zab = createZabServer();
export async function POST(req) {
const { text, to } = await req.json();
const m = await zab.messages.send('live-42', { text, from: 'system', ...(to ? { to } : {}) }); // reaches everyone subscribed at once
return NextResponse.json(m);
}.env.local
ZAB_URL=https://chat.example.com
ZAB_ACCESS_KEY=zk_SERVER_ONLY_KEY
NEXT_PUBLIC_ZAB_URL=https://chat.example.com
NEXT_PUBLIC_ZAB_ACCESS_KEY=zk_BROWSER_KEYUser ID
On the server, zab.as(userId) returns the same client acting for one end user, so every REST call it makes is logged under that id. Client Components pass userId to <ZabProvider>.
Provider (App Router)
// app/providers.jsx
'use client';
import { ZabProvider } from 'zab-messaging-next/client';
export default function Providers({ children }) { return <ZabProvider userId="alice">{children}</ZabProvider>; }
// a Client Component: subscribe, send, everything in the channel is broadcast to everyone (you too)
'use client';
import { useZabChannel } from 'zab-messaging-next/client';
export function Chat() {
const { messages, send } = useZabChannel('live-42', { history: true });
return <>{messages.map((m) => <p key={m.id}>{m.from}: {m.text}</p>)}<button onClick={() => send('hi')}>Send</button></>;
}Route Handler / Server Action
// app/api/notice/route.js: post into a channel from the server with the server-only key
import { createZabServer } from 'zab-messaging-next/server';
const zab = createZabServer();
export async function POST(req) {
const { text } = await req.json();
const m = await zab.messages.send('live-42', { text, from: 'system' }); // reaches everyone subscribed at once
await zab.messages.send('live-42', { text: 'only for bob', to: ['bob'] }); // a private message
return Response.json(m);
}Server errors
Server calls throw ZabServerError with an HTTP status: 401 wrong or revoked key, 403 suspended or blocked, 400 bad input (for example an invalid channel name), 507 storage quota exceeded, 0 when the server cannot be reached.
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
Flutter SDK
Android, iOS, web and desktop. One app-wide connection, per-screen subscriptions.
Why this SDK? One Dart codebase for Android, iOS, web and desktop. The SDK keeps a single app-wide connection, joins your channels again after every reconnect and replays the messages missed while the phone was offline, so a chat screen stays correct on a flaky mobile network.
Requirements
- Flutter 3.x / Dart 3
- Android, iOS, web, Windows, macOS, Linux
- Uses socket_io_client
Install
pubspec.yaml
dependencies:
zab_messaging:
path: ../ZabMessaging/sdk/flutter/zab_messaging # or your git / pub.dev sourceQuick start: subscribe, send, receive
import 'package:zab_messaging/zab_messaging.dart';
// main(): open the connection once
ZabMessagingIO.init('https://your-server', accessKey: 'zk_YOUR_ACCESS_KEY', userId: 'alice').open();
// a screen:
final room = ZabMessagingIO.instance.channel('live-stream-1'); // one channel per live stream / room
room.messages.listen((m) => setState(() => comments.add(m))); // every new message, instantly
room.typing.listen((t) => setState(() => typingNow = t.users));
room.receipts.listen((r) => print(r.userId + ' ' + r.kind + ' up to ' + r.upToSeq.toString()));
final joined = await room.join(); // joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
await room.send('Hello everyone'); // or room.send(null, data: {'gift': 'rose'})
await room.send('psst', to: ['bob']); // PRIVATE: only bob (and you) get it; bob listens on room.messages, m.isPrivate
final page = await room.history(limit: 30); // load old messages separately, any time (oldest first)
final older = await room.loadMore(); // the page before the oldest message loaded
room.setTyping(true); // call on every key press: the SDK throttles and stops it
await room.markSeen(); // everything up to the newest messagejoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | final r = await room.join(history: true, limit: n) (true = load old messages with the join, false = none, omitted = the app's setting) |
| Send a message | await room.send(text, data: {...}, replyTo: id, to: [userIds]) (to = private message) |
| Receive (live) | room.messages · updates · deletions · typing · receipts · presence · cleared (Streams) |
| Load old messages (separate) | await room.history(limit: n, before: seq, after: seq, receipts: true) |
| Load an older page | await room.loadMore([limit]) |
| Typing indicator | room.setTyping(true) |
| Mark seen (receipts) | await room.markSeen([upTo]) |
| Edit / delete | await room.edit(id, text: "…") · await room.delete(id) |
| Members, unread, receipts, channels | await room.members() · room.unread() · room.receiptsOf(id) · db.channels() · db.messagingConfig() |
| Connected? joined channels? who is online? stats | zab.isConnected · zab.joinedChannels · zab.isJoined(name) · await zab.members(channel) · await zab.stats(prefix: p, users: true, limit: n) |
| Leave (one / all) | await room.leave() (this channel) · await db.leaveAll() (every channel) · db.joinedChannels |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
lib/main.dart
import 'package:flutter/material.dart';
import 'package:zab_messaging/zab_messaging.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
ZabMessagingIO.init('https://chat.example.com', accessKey: 'zk_YOUR_ACCESS_KEY', userId: 'alice').open(); // once; userId optional
runApp(const MaterialApp(home: ChatScreen()));
}
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final db = ZabMessagingIO.instance;
final _channel = TextEditingController(), _text = TextEditingController();
ZabChannel? room;
final messages = <ZabMessage>[];
Future<void> subscribe() async {
final r = db.channel(_channel.text.trim());
r.messages.listen((m) => setState(() => messages.add(m))); // everything new, for everyone in the channel (you too)
final joined = await r.join(history: true); // + the old messages
setState(() { room = r; messages..clear()..addAll(joined.messages); });
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(room == null ? 'Subscribe to a channel' : '# \${room!.name}')),
body: Column(children: [
Row(children: [
Expanded(child: TextField(controller: _channel, decoration: const InputDecoration(hintText: 'channel name'))),
FilledButton(onPressed: subscribe, child: const Text('Subscribe')),
]),
Expanded(child: ListView(children: [for (final m in messages) ListTile(title: Text(m.text ?? ''), subtitle: Text(m.from))])),
Row(children: [
Expanded(child: TextField(controller: _text, enabled: room != null)),
IconButton(icon: const Icon(Icons.send), onPressed: room == null ? null : () { room!.send(_text.text); _text.clear(); }),
]),
]),
);
}User ID
Pass any id for the end user. Without one a random id is generated. setUserId re-identifies the live connection without losing the joined channels.
Many channels, private messages, Store
final news = db.channel('news'), sports = db.channel('sports');
news.messages.listen((m) => print('news: ${m.text}'));
await Future.wait([news.join(history: true), sports.join()]);
await news.send('hello everyone'); // everybody subscribed, you too
await news.send('psst', to: ['bob']); // only bob (and you); m.isPrivate / m.to on the receiving side
await news.send('hearts', isStore: false); // live only: never in history
print(db.joinedChannels); // [news, sports]
await news.leave(); // unsubscribe from one channel
await db.leaveAll(); // unsubscribe from every channelConnection status
ValueListenableBuilder<ZabConnectionState>(
valueListenable: ZabMessagingIO.instance.state,
builder: (_, s, __) => s == ZabConnectionState.rejected
? Text('The server refused this key: ${ZabMessagingIO.instance.lastError.value}')
: s == ZabConnectionState.connected ? const SizedBox() : const Text('Reconnecting…'),
)Android emulator
Use http://10.0.2.2:8080 for a server on your machine. Pass https:// (not wss://): Socket.IO upgrades to a WebSocket by itself. Plain http:// is blocked by Android release builds and iOS: use https:// in production.
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
Android (Kotlin) SDK
Coroutines, StateFlow and Flow over an OkHttp WebSocket. Also runs on the plain JVM.
Why this SDK? A native Android app needs the connection to survive Wi-Fi to mobile switches, tunnels and Doze. The Kotlin SDK exposes the connection as StateFlow and each channel as Flow, so it fits ViewModels and Jetpack Compose without extra glue.
Requirements
- Android 5.0+ (API 21), compileSdk 34
- Kotlin 1.9+, Java 8 target
- OkHttp 4 and kotlinx-coroutines (pulled in automatically)
Install
settings.gradle.kts
include(":zab-messaging")
project(":zab-messaging").projectDir = file("path/to/ZabMessaging/sdk/android/zab-messaging")app/build.gradle.kts
dependencies { implementation(project(":zab-messaging")) }
// or, after ./gradlew :zab-messaging:publishToMavenLocal:
// implementation("com.zabsys:zab-messaging:1.0.0")Local server on the emulator
<!-- http://10.0.2.2:8080 needs cleartext traffic; use https in production -->
<application android:usesCleartextTraffic="true" ... />Quick start: subscribe, send, receive
val zab = ZabMessaging("https://your-server", "zk_YOUR_ACCESS_KEY", ZabOptions(userId = "alice")) // ONE instance for the whole app
zab.connect()
val room = zab.channel("live-stream-1") // one channel per live stream / room
room.onMessage { m -> println(m.from + ": " + m.text) } // every new message, instantly (or: room.messages.collect { ... })
room.onTyping { t -> println(t.users.toString() + " typing") }
val joined = room.join() // joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
room.send("Hello everyone") // or room.send(data = mapOf("gift" to "rose"))
val page = room.history(limit = 30) // load old messages separately, any time (oldest first)
val older = room.loadMore() // the page before the oldest message loaded
room.setTyping(true) // call on every key press: the SDK throttles and stops it
room.markSeen() // everything up to the newest messagejoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | val r = room.join(history = true, limit = n) (true = load old messages with the join, false = none, null = the app's setting) |
| Send a message | room.send(text, data = map, replyTo = id) |
| Receive (live) | room.onMessage { } · onUpdated · onDeleted · onTyping · onReceipt · onPresence · room.messages (Flow) |
| Load old messages (separate) | room.history(limit, before, after, receipts) |
| Load an older page | room.loadMore(limit) |
| Typing indicator | room.setTyping(true) |
| Mark seen (receipts) | room.markSeen(upToId?) |
| Edit / delete | room.edit(id, text) · room.delete(id) |
| Members, unread, receipts, channels | room.members() · room.unread() · room.receiptsOf(id) · zab.channels() · zab.messagingConfig() |
| Connected? joined channels? who is online? stats | zab.isConnected · zab.joinedChannels · zab.isJoined(name) · zab.members(channel) · zab.stats(prefix, users = true, limit) |
| Leave (one / all) | room.leave() (this channel) · zab.leaveAll() (every channel) · zab.joinedChannels |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
App.kt
import android.app.Application
import com.zabsys.zabmessaging.*
class App : Application() {
// ONE instance for the whole app; userId is optional (empty = generated)
val zab by lazy { ZabMessaging("https://chat.example.com", "zk_YOUR_ACCESS_KEY", ZabOptions(userId = "alice")) }
}ChatViewModel.kt
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
class ChatViewModel(private val zab: ZabMessaging) : ViewModel() {
val messages = MutableStateFlow<List<ZabMessage>>(emptyList())
private var room: ZabChannel? = null
fun subscribe(name: String) = viewModelScope.launch {
zab.connect()
val r = zab.channel(name)
room = r
messages.value = r.join(history = true).messages // the old messages come WITH the join
r.messages.collect { m -> messages.value = messages.value + m } // every new message, for everyone (you too)
}
fun send(text: String, only: List<String>? = null) = viewModelScope.launch { room?.send(text, to = only) }
fun unsubscribe() = viewModelScope.launch { room?.leave(); room = null }
}AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application android:usesCleartextTraffic="false" ... /> <!-- use https:// in production -->
</manifest>User ID
Pass any id for the end user in ZabOptions. Without one a random id is generated. setUserId re-identifies the live connection without losing the joined channels.
Compose
@Composable
fun Chat(zab: ZabMessaging) {
val room = remember { zab.channel("live-42") }
var messages by remember { mutableStateOf(listOf<ZabMessage>()) }
LaunchedEffect(room) {
room.join(history = true).also { messages = it.messages }
room.messages.collect { m -> messages = messages + m } // every new message, for everyone (you too)
}
DisposableEffect(room) { onDispose { /* room.leave() in a coroutine */ } }
LazyColumn { items(messages) { m -> Text("${m.from}: ${m.text}") } }
}Private messages, Store, many channels
room.send("hello everyone") // everybody subscribed (you too)
room.send("psst", to = listOf("bob")) // only bob (and you)
room.send("hearts", isStore = false) // live only: never in history
println(zab.joinedChannels) // names of the channels you are subscribed to
room.leave() // one channel
zab.leaveAll() // every channelBuild check
This module was written without an Android toolchain in the repository environment. Run ./gradlew :zab-messaging:test and build the app once before shipping.
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
iOS & macOS (Swift) SDK
A Swift Package with async/await and AsyncStream over URLSessionWebSocketTask. No dependencies.
Why this SDK? A native iOS or macOS app should not pull in third-party networking code just to get a live channel. This package is built on URLSessionWebSocketTask and Swift concurrency: async/await for requests and plain callbacks (or AsyncStream) for incoming messages.
Requirements
- iOS 15+, macOS 12+, tvOS 15+, watchOS 8+
- Swift 5.7+ / Xcode 14+
- No third-party dependencies
Install
Xcode
File → Add Package Dependencies… → Add Local… → choose sdk/iosPackage.swift
dependencies: [ .package(path: "../ZabMessaging/sdk/ios") ], // or your Git URL once published
targets: [ .target(name: "MyApp", dependencies: [.product(name: "ZabMessaging", package: "ios")]) ]Quick start: subscribe, send, receive
import ZabMessaging
let zab = try ZabMessaging(url: "https://your-server", accessKey: "zk_YOUR_ACCESS_KEY", options: ZabOptions(userId: "alice")) // ONE instance for the app
try await zab.connect()
let room = try zab.channel("live-stream-1") // one channel per live stream / room
let sub = room.onMessage { m in print(m.from, m.text ?? "") } // every new message, instantly (or: for await m in room.messages())
let typing = room.onTyping { t in print(t.users, "typing") }
let joined = try await room.join() // joined.messages = latest messages when you join with the history option on (or the app has "history on join" on)
try await room.send("Hello everyone") // or room.send(data: ["gift": "rose"])
let page = try await room.history(limit: 30) // load old messages separately, any time (oldest first)
let older = try await room.loadMore() // the page before the oldest message loaded
room.setTyping(true) // call on every key press: the SDK throttles and stops it
try await room.markSeen() // everything up to the newest messagejoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | let r = try await room.join(history: true, limit: n) (true = load old messages with the join, false = none, nil = the app's setting) |
| Send a message | try await room.send(text, data: [...], replyTo: id) |
| Receive (live) | room.onMessage { } · onUpdated · onDeleted · onTyping · onReceipt · onPresence · room.messages() (AsyncStream) |
| Load old messages (separate) | try await room.history(limit:, before:, after:, receipts:) |
| Load an older page | try await room.loadMore(limit) |
| Typing indicator | room.setTyping(true) |
| Mark seen (receipts) | try await room.markSeen(upToId) |
| Edit / delete | try await room.edit(id, text:) · try await room.delete(id) |
| Members, unread, receipts, channels | try await room.members() · room.unread() · room.receipts(of: id) · zab.channels() |
| Connected? joined channels? who is online? stats | zab.isConnected · zab.joinedChannels · zab.isJoined(name) · try await zab.members(of: channel) · try await zab.stats(prefix:users:limit:) |
| Leave (one / all) | await room.leave() |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
MyApp.swift
import SwiftUI
import ZabMessaging
@main
struct MyApp: App {
// ONE instance for the app; userId is optional (empty = generated)
static let zab = try! ZabMessaging(url: "https://chat.example.com", accessKey: "zk_YOUR_ACCESS_KEY")
var body: some Scene { WindowGroup { ChatView() } }
}ChatModel.swift
import Foundation
import ZabMessaging
@MainActor final class ChatModel: ObservableObject {
@Published var messages: [ZabMessage] = []
@Published var channelName = ""
private var room: ZabChannel?
private var sub: ZabSubscription?
func subscribe(_ name: String) async throws {
try await MyApp.zab.connect()
let r = try MyApp.zab.channel(name)
room = r
sub = r.onMessage { [weak self] m in Task { @MainActor in self?.messages.append(m) } } // for everyone in the channel (you too)
messages = try await r.join(history: true).messages // the old messages come WITH the join
channelName = name
}
func send(_ text: String, only: [String]? = nil) async throws { _ = try await room?.send(text, to: only) }
func unsubscribe() async { sub?.cancel(); await room?.leave(); room = nil; channelName = "" }
}ChatView.swift
import SwiftUI
struct ChatView: View {
@StateObject private var chat = ChatModel()
@State private var name = "", text = ""
var body: some View {
VStack {
HStack { TextField("channel name", text: $name); Button("Subscribe") { Task { try? await chat.subscribe(name) } } }
List(chat.messages, id: \.id) { m in Text("\\(m.from): \\(m.text ?? "")") }
HStack {
TextField("message", text: $text)
Button("Send") { Task { try? await chat.send(text); text = "" } }.disabled(chat.channelName.isEmpty)
}
}
}
}User ID
Set userId in ZabOptions. Without one a random id is generated. setUserId re-identifies the live connection without losing the joined channels.
SwiftUI
@MainActor final class Room: ObservableObject {
@Published var messages: [ZabMessage] = []
private var sub: ZabSubscription?
func start(_ zab: ZabMessaging) async throws {
let room = try zab.channel("live-42")
sub = room.onMessage { [weak self] m in Task { @MainActor in self?.messages.append(m) } } // for everyone, you too
messages = try await room.join(history: true).messages
}
}Private messages, Store, many channels
try await room.send("hello everyone") // everybody subscribed (you too)
try await room.send("psst", to: ["bob"]) // only bob (and you)
try await room.send("hearts", isStore: false) // live only: never in history
print(zab.joinedChannels) // names of the channels you are subscribed to
await room.leave() // one channel
await zab.leaveAll() // every channelBuild check
This package was written without a Swift toolchain in the repository environment. Run swift build and swift test once before shipping.
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
.NET (C#) SDK
ASP.NET Core, MAUI, WPF, Xamarin and Unity. ClientWebSocket, async/await, System.Text.Json.
Why this SDK? For ASP.NET Core services, desktop apps (WPF, WinForms, MAUI), Xamarin and Unity games. It is idiomatic C#: async methods with cancellation tokens, IAsyncEnumerable for message streams, IAsyncDisposable for clean shutdown.
Requirements
- .NET 8+ or .NET Standard 2.1
- Unity 2021.2+, MAUI, Xamarin
- System.Text.Json (no other dependencies)
Install
Project reference
dotnet add reference ./sdk/dotnet/ZabMessaging/ZabMessaging.csproj
# or: dotnet pack ./sdk/dotnet/ZabMessaging -c Release then publish ZabSys.Messaging to your NuGet feedQuick start: subscribe, send, receive
using ZabSys.Messaging;
await using var zab = new ZabMessaging("https://your-server", "zk_YOUR_ACCESS_KEY", new ZabOptions { UserId = "alice" }); // ONE instance per app
await zab.ConnectAsync();
var room = zab.Channel("live-stream-1"); // one channel per live stream / room
room.MessageReceived += m => Console.WriteLine($"{m.From}: {m.Text}"); // every new message, instantly (or: await foreach (var m in room.MessagesAsync()))
room.TypingChanged += t => Console.WriteLine($"{string.Join(", ", t.Users)} typing");
var joined = await room.JoinAsync(); // joined.Messages = latest messages when you join with the history option on (or the app has "history on join" on)
await room.SendAsync("Hello everyone"); // or room.SendAsync(data: new { gift = "rose" })
var page = await room.HistoryAsync(limit: 30); // load old messages separately, any time (oldest first)
var older = await room.LoadMoreAsync(); // the page before the oldest message loaded
room.SetTyping(true); // call on every key press: the SDK throttles and stops it
await room.MarkSeenAsync(); // everything up to the newest messagejoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | var r = await room.JoinAsync(history: true, limit: n) (true = load old messages with the join, false = none, null = the app's setting) |
| Send a message | await room.SendAsync(text, data, replyTo) |
| Receive (live) | room.MessageReceived · Updated · Deleted · TypingChanged · ReceiptReceived · PresenceChanged · room.MessagesAsync() |
| Load old messages (separate) | await room.HistoryAsync(limit, before, after, receipts) |
| Load an older page | await room.LoadMoreAsync(limit) |
| Typing indicator | room.SetTyping(true) |
| Mark seen (receipts) | await room.MarkSeenAsync(upToId) |
| Edit / delete | await room.EditAsync(id, text) · await room.DeleteAsync(id) |
| Members, unread, receipts, channels | await room.MembersAsync() · UnreadAsync() · ReceiptsAsync(id) · zab.ChannelsAsync() |
| Connected? joined channels? who is online? stats | zab.IsConnected · zab.JoinedChannels · zab.IsJoined(name) · await zab.MembersAsync(channel) · await zab.StatsAsync(prefix, users: true, limit) |
| Leave (one / all) | await room.LeaveAsync() (this channel) · await zab.LeaveAllAsync() (every channel) · zab.JoinedChannels |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
Program.cs (console or worker service)
using ZabSys.Messaging;
await using var zab = new ZabMessaging("https://chat.example.com", "zk_YOUR_ACCESS_KEY", new ZabOptions { UserId = "alice" }); // UserId optional
zab.StateChanged += (s, why) => Console.WriteLine($"connection: {s} {why}");
try { await zab.ConnectAsync(); }
catch (ZabException e) when (e.Code == ZabErrorCode.Unauthorized) { Console.WriteLine("the key was refused"); return; }
var room = zab.Channel("live-42");
room.MessageReceived += m => Console.WriteLine($"{m.From}: {m.Text}"); // everything new, for everyone (you too)
var joined = await room.JoinAsync(history: true); // + the old messages
foreach (var m in joined.Messages) Console.WriteLine($"(old) {m.From}: {m.Text}");
await room.SendAsync("Hello everyone", isStore: true); // isStore: true = kept in the history; broadcast to all
await room.SendAsync("psst", to: new[] { "bob" }); // private: only bob (and you)
await room.SendAsync("hearts", isStore: false); // live only: never in history
await zab.LeaveAllAsync(); // unsubscribe from every channelUser ID
Set UserId in ZabOptions. Without one a random id is generated. SetUserIdAsync re-identifies the live connection without losing the joined channels.
ASP.NET Core
builder.Services.AddSingleton(sp => new ZabMessaging(cfg["Zab:Url"]!, cfg["Zab:AccessKey"]!, new ZabOptions { UserId = "my-service" }));
// anywhere: post into a channel, everyone subscribed receives it
var room = zab.Channel("live-42");
await room.JoinAsync();
await room.SendAsync("The stream starts now");Private messages, Store, many channels
await room.SendAsync("hello everyone"); // everybody subscribed (you too)
await room.SendAsync("psst", to: new[] { "bob" }); // only bob (and you)
await room.SendAsync("hearts", isStore: false); // live only: never in history
Console.WriteLine(string.Join(",", zab.JoinedChannels)); // the channels you are subscribed to
await room.LeaveAsync(); // one channel
await zab.LeaveAllAsync(); // every channelBuild check
This project was written without a .NET SDK in the repository environment. Run dotnet build and dotnet test once before shipping.
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
Python SDK
An asyncio realtime client and a dependency-free blocking REST client.
Why this SDK? Use the asyncio client for bots, dashboards and FastAPI services that need to receive messages live. Use the blocking REST client for scripts, cron jobs and Django or Flask views, where you only need to post a message or read the history.
Requirements
- Python 3.8+
ZabMessaging(asyncio) needswebsocketsZabRestneeds nothing
Install
pip (from the SDK folder)
pip install ./sdk/pythonQuick start: subscribe, send, receive
import asyncio
from zab_messaging import ZabMessaging, ZabRest
async def main():
async with ZabMessaging("https://your-server", access_key="zk_YOUR_ACCESS_KEY", user_id="alice") as zab: # connects, disconnects on exit
room = zab.channel("live-stream-1") # one channel per live stream / room
room.on_message(lambda m: print(m["from"], m["text"])) # every new message, instantly
room.on_typing(lambda t: print(t["users"], "typing"))
joined = await room.join() # joined["messages"] = latest messages when you join with the history option on (or the app has "history on join" on)
await room.send("Hello everyone", is_store=True) # is_store=True = kept in the channel history; left out = live only
await room.send("psst", to="bob") # PRIVATE: only bob (and you) get it; to=["bob", "carol"] for several
page = await room.history(limit=30) # load old messages separately, any time (oldest first)
older = await room.load_more() # the page before the oldest message loaded
room.set_typing(True) # call on every key press: the client throttles and stops it
await room.mark_seen() # everything up to the newest message
await asyncio.sleep(60)
asyncio.run(main())
# A script or web view (blocking, no websocket): post as the server
ZabRest("https://your-server", "zk_YOUR_ACCESS_KEY").send("live-stream-1", "The stream starts now", from_user="system")join subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | r = await room.join(history=True, limit=n) (True = load old messages with the join, False = none, None = the app's setting) |
| Send a message | await room.send(text, data=…, reply_to=id, to=user_id | [ids]) (to = private message) |
| Receive (live) | room.on_message(cb) · on_updated · on_deleted · on_typing · on_receipt · on_presence |
| Load old messages (separate) | await room.history(limit, before, after, receipts) |
| Load an older page | await room.load_more(limit) |
| Typing indicator | room.set_typing(True) |
| Mark seen (receipts) | await room.mark_seen(up_to) |
| Edit / delete | await room.edit(id, text) · await room.delete(id) |
| Members, unread, receipts, channels | await room.members() · room.unread() · room.receipts(id) · zab.channels() · ZabRest.send / history / channels / edit_message / delete_message / clear_channel |
| Connected? joined channels? who is online? stats | zab.is_connected · zab.joined_channels · zab.is_joined(name) · await zab.members(channel) · await zab.stats(prefix=, users=True, limit=) · ZabRest.members / stats |
| Leave (one / all) | await room.leave() (this channel) · await db.leave_all() (every channel) · db.joined_channels |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
app.py
import asyncio
import os
from zab_messaging import ZabMessaging, ZabError
async def main():
zab = ZabMessaging(os.environ["ZAB_URL"], access_key=os.environ["ZAB_ACCESS_KEY"], user_id="alice") # user_id optional
zab.on_state(lambda state, reason: print("connection:", state, reason or ""))
try:
await zab.connect() # raises ZabError (code "unauthorized") when the key is refused
except ZabError as e:
raise SystemExit(f"cannot connect: {e.code} {e}")
room = zab.channel("live-42")
room.on_message(lambda m: print(m["from"] + ":", m.get("text"))) # everything new, for everyone (you too)
joined = await room.join(history=True, limit=30) # + the 30 latest old messages
for m in joined["messages"]:
print("(old)", m["from"] + ":", m.get("text"))
await room.send("Hello everyone", is_store=True) # is_store=True = kept in the history; broadcast to all
await room.send("psst", to=["bob"]) # private: only bob (and you)
await room.send("hearts", is_store=False) # live only: never in history
await asyncio.sleep(1)
await zab.leave_all() # unsubscribe from every channel
await zab.disconnect()
asyncio.run(main())REST in a web handler (FastAPI / Flask / Django)
import os
from zab_messaging import ZabRest
zab = ZabRest(os.environ["ZAB_URL"], access_key=os.environ["ZAB_ACCESS_KEY"])
def notify(request):
m = zab.as_user(request.user.id).send("orders", "New order received") # logged under that user, reaches every subscriber
return {"id": m["id"]}User ID
Pass user_id to the realtime client (a random id is generated when omitted). A REST client has no id of its own: pass one with user_id= or as_user() to log its calls under an end user.
zab = ZabMessaging(url, access_key=key, user_id="alice")
rest = ZabRest(url, access_key=key)
rest.as_user("alice").send("live-42", "hi") # logged under that userBlocking REST client
For scripts, cron jobs and Django / Flask / FastAPI handlers. No dependencies. Everything you send reaches the subscribers of the channel at once.
from zab_messaging import ZabRest
zab = ZabRest("https://your-server", access_key="zk_YOUR_ACCESS_KEY")
zab.send("live-42", "The stream starts now", from_user="system") # everybody subscribed
zab.send("live-42", "only for bob", from_user="system", to="bob") # a private message
print(zab.history("live-42", limit=30)["messages"]) # the server side sees every message
zab.clear_channel("live-42")Many channels, private messages, Store
async with ZabMessaging(url, access_key=key) as zab:
a, b = zab.channel("news"), zab.channel("sports")
a.on_message(print)
await a.join(history=True)
await b.join()
await a.send("hello everyone") # everybody subscribed (you too)
await a.send("psst", to=["bob"]) # only bob (and you)
await a.send("hearts", is_store=False) # live only: never in history
print(zab.joined_channels)
await a.leave() # one channel
await zab.leave_all() # every channelErrors
Every call raises ZabError with code (rejected, unauthorized, timeout, disconnected, invalid, server) and, for REST, status.
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
GoGo SDK
A WebSocket client with channels and auto-reconnect, plus a stateless REST client.
Why this SDK? Go services (APIs, workers, IoT gateways) usually want a small, dependency-light client with context support. The Client keeps a live connection with channels and automatic reconnection; the REST client is the stateless option for handlers and jobs.
Requirements
- Go 1.22+
- gorilla/websocket
Install
go get / replace
go get github.com/zabsys/zabmessaging-go
# from the SDK folder:
go mod edit -replace github.com/zabsys/zabmessaging-go=./sdk/goQuick start: subscribe, send, receive
client, _ := zabmessaging.New("https://your-server", "zk_YOUR_ACCESS_KEY", zabmessaging.Options{UserID: "alice"})
ctx := context.Background()
_ = client.Connect(ctx)
defer client.Close()
room, _ := client.Channel("live-stream-1") // one channel per live stream / room
room.OnMessage(func(m zabmessaging.Message) { fmt.Println(m.From, m.Text) }) // every new message, instantly
room.OnTyping(func(t zabmessaging.TypingEvent) { fmt.Println(t.Users, "typing") })
joined, _ := room.Join(ctx) // joined.Messages = latest messages when you join with the history option on (or the app has "history on join" on)
room.Send(ctx, "Hello everyone") // or room.Send(ctx, "", zabmessaging.SendOptions{Data: map[string]any{"gift": "rose"}})
page, _ := room.History(ctx, zabmessaging.HistoryOptions{Limit: 30}) // load old messages separately, any time (oldest first)
older, _ := room.LoadMore(ctx, 30) // the page before the oldest message loaded
room.SetTyping(true) // call on every key press: the client throttles and stops it
room.MarkSeen(ctx, "") // everything up to the newest messagejoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | r, err := room.Join(ctx, JoinOptions{LoadHistory, NoHistory, Limit}) (LoadHistory = old messages come with the join) |
| Send a message | room.Send(ctx, text, SendOptions{Data, ReplyTo}) |
| Receive (live) | room.OnMessage(cb) · OnUpdated · OnDeleted · OnTyping · OnReceipt · OnPresence · OnCleared |
| Load old messages (separate) | room.History(ctx, HistoryOptions{Limit, Before, After, Receipts}) |
| Load an older page | room.LoadMore(ctx, limit) |
| Typing indicator | room.SetTyping(true) |
| Mark seen (receipts) | room.MarkSeen(ctx, upToID) |
| Edit / delete | room.Edit(ctx, id, text) · room.Delete(ctx, id) |
| Members, unread, receipts, channels | room.Members(ctx) · Unread(ctx) · Receipts(ctx, id) · client.Channels(ctx, prefix, limit) |
| Connected? joined channels? who is online? stats | client.IsConnected() · client.JoinedChannels() · client.IsJoined(name) · client.MembersOf(ctx, channel) · client.Stats(ctx, zab.StatsOptions{Prefix, Users, Limit}) · rest.MembersOf / Stats |
| Leave (one / all) | room.Leave(ctx) (this channel) · client.LeaveAll(ctx) (every channel) · client.JoinedChannels() |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
main.go
package main
import (
"context"
"fmt"
"log"
"os"
"time"
zab "github.com/zabsys/zabmessaging-go"
)
func main() {
ctx := context.Background()
db, err := zab.New(os.Getenv("ZAB_URL"), os.Getenv("ZAB_ACCESS_KEY"), zab.Options{UserID: "alice"}) // UserID optional
if err != nil {
log.Fatal(err)
}
db.OnState(func(s zab.State, why string) { fmt.Println("connection:", s, why) })
if err := db.Connect(ctx); err != nil { // fails when the key is refused
log.Fatal(err)
}
defer db.Close()
room, _ := db.Channel("live-42")
room.OnMessage(func(m zab.Message) { fmt.Println(m.From+":", m.Text) }) // everything new, for everyone (you too)
jr, err := room.Join(ctx, zab.JoinOptions{LoadHistory: true, Limit: 30}) // + the 30 latest old messages
if err != nil {
log.Fatal(err)
}
for _, m := range jr.Messages {
fmt.Println("(old)", m.From+":", m.Text)
}
yes := true
room.Send(ctx, "Hello everyone", zab.SendOptions{IsStore: &yes}) // IsStore true = kept in the history; broadcast to all
room.Send(ctx, "psst", zab.SendOptions{To: []string{"bob"}}) // private: only bob (and you)
time.Sleep(time.Second)
db.LeaveAll(ctx) // unsubscribe from every channel
}REST in an HTTP handler
var zrest, _ = zab.NewREST(os.Getenv("ZAB_URL"), os.Getenv("ZAB_ACCESS_KEY"))
func notify(w http.ResponseWriter, r *http.Request) {
m, err := zrest.As(userID(r)).Send(r.Context(), "orders", "New order received") // reaches every subscriber at once
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
fmt.Fprint(w, m.ID)
}User ID
Set Options.UserID (a random id is generated when empty). A REST client has no id of its own unless you pass Options.UserID; As(id) acts for one end user.
Stateless REST
For HTTP handlers and jobs: no connection to manage. Everything you send reaches the subscribers of the channel at once.
zab, _ := zabmessaging.NewREST("https://your-server", "zk_YOUR_ACCESS_KEY")
zab.Send(ctx, "live-42", "The stream starts now", zabmessaging.RESTSend{From: "system"})
zab.Send(ctx, "live-42", "only for bob", zabmessaging.RESTSend{From: "system", To: []string{"bob"}})
h, _ := zab.History(ctx, "live-42", zabmessaging.HistoryOptions{Limit: 30}) // the server side sees every messageMany channels, private messages, Store
news, _ := db.Channel("news")
sports, _ := db.Channel("sports")
news.Join(ctx, zabmessaging.JoinOptions{LoadHistory: true})
sports.Join(ctx)
news.Send(ctx, "hello everyone") // everybody subscribed (you too)
news.Send(ctx, "psst", zabmessaging.SendOptions{To: []string{"bob"}}) // only bob (and you)
no := false
news.Send(ctx, "hearts", zabmessaging.SendOptions{IsStore: &no}) // live only: never in history
fmt.Println(db.JoinedChannels())
news.Leave(ctx) // one channel
db.LeaveAll(ctx) // every channelErrors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
PPHP SDK
A dependency-free REST client for Laravel, Symfony, WordPress and plain PHP.
Why this SDK? PHP requests start and end within a page load, so keeping a WebSocket open makes no sense there. This client does the one thing PHP needs: post messages into channels, read their history and moderate them over REST from Laravel, Symfony, WordPress or plain scripts. Everything you send reaches the live subscribers of the other SDKs at once.
Requirements
- PHP 8.0+
- ext-json
- REST only: PHP requests are short-lived, so there are no live subscriptions
Install
Composer
composer require zabsys/zab-messaging
# or a path repository pointing at ./sdk/phpQuick start: subscribe, send, receive
use ZabMessaging\ZabMessaging;
// PHP requests are short-lived, so PHP does not hold a live channel: it posts and reads over REST. Browsers and apps join.
$zab = new ZabMessaging('https://your-server', 'zk_YOUR_ACCESS_KEY');
$m = $zab->send('live-stream-1', 'The stream starts now', ['kind' => 'notice'], 'system'); // reaches everyone joined at once
$page = $zab->history('live-stream-1', limit: 30); // oldest first: ['messages' => [...], 'hasMore' => bool, 'lastSeq' => int]
$older = $zab->history('live-stream-1', limit: 30, before: $page['messages'][0]['seq']);
$zab->editMessage('live-stream-1', $m['id'], 'The stream starts in 5 minutes');
$zab->deleteMessage('live-stream-1', $m['id']);
$zab->clearChannel('live-stream-1'); // moderation: delete every message
$channels = $zab->channels(); // newest activity firstjoin subscribes. With the history option on it also brings the old messages, with it off only new messages arrive. Everything sent inside the channel reaches every subscriber, you included; to narrows a message to specific users and isStore decides whether it is kept in the channel history. See Messaging for the model, limits and protocol.
API at a glance
| Operation | Call |
|---|---|
| Join a channel | (PHP does not join: it is REST only) |
| Send a message | $zab->send($channel, $text, $data, $from, $replyTo) |
| Receive (live) | (REST only) |
| Load old messages (separate) | $zab->history($channel, $limit, $before, $after) |
| Load an older page | $zab->history($channel, before: $oldestSeq) |
| Typing indicator | (REST only) |
| Mark seen (receipts) | (REST only) |
| Edit / delete | $zab->editMessage($ch, $id, $text) · deleteMessage($ch, $id) · clearChannel($ch) |
| Members, unread, receipts, channels | $zab->channels($prefix) |
| Connected? joined channels? who is online? stats | $zab->members($channel) · $zab->stats($prefix, $users, $limit) (REST: PHP does not hold a live connection) |
| Leave (one / all) | (REST only) |
Complete example
A full, copy-paste setup: configuration, connecting with error handling, subscribing to a channel, sending, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
order.php
<?php
require __DIR__ . '/vendor/autoload.php';
use ZabMessaging\\ZabMessaging;
use ZabMessaging\\ZabException;
$zab = new ZabMessaging(getenv('ZAB_URL'), getenv('ZAB_ACCESS_KEY'));
try {
$m = $zab->send('orders', 'New order #1001', from: 'shop'); // reaches everyone subscribed at once
$zab->send('orders', 'Only for the warehouse', from: 'shop', to: ['warehouse']); // a private message
print_r($zab->history('orders', limit: 10)['messages']); // the server side sees every message
} catch (ZabException $e) {
error_log("ZabMessaging {$e->zabCode}: " . $e->getMessage());
}User ID
Pass a user id as the fourth constructor argument, or use as() to act for the end user behind each request.
Laravel
// app/Providers/AppServiceProvider.php
$this->app->singleton(\ZabMessaging\ZabMessaging::class, fn () => new \ZabMessaging\ZabMessaging(config('zab.url'), config('zab.key')));
// anywhere: post into a channel, everyone subscribed receives it
app(\ZabMessaging\ZabMessaging::class)->send('orders', 'New order #1001', from: 'shop');Private messages, Store
$zab->send('live-42', 'hello everyone', from: 'system'); // everybody subscribed
$zab->send('live-42', 'only for bob', from: 'system', to: ['bob']); // a private message
$zab->send('live-42', 'hearts', from: 'system', isStore: false); // live only: never in history
$zab->history('live-42', limit: 30); // the server side sees every messageErrors
ZabException::$zabCode is one of rejected, unauthorized, timeout, disconnected, invalid, server; $e->status() is the HTTP status (0 when unreachable).
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
Protocol & REST API
All SDKs are thin layers over these three transports. Use them directly to build a client for any language.
Authentication
Optionally identify the end user too: &user_id=alice on the WebSocket URL, auth: {key, user_id} in Socket.IO, or the X-Zab-User-Id header (or ?user_id=) on REST. It appears in the admin console's activity log; see Core concepts.
Send the access key as ?key=zk_…, as Authorization: Bearer zk_…, or (alias) ?token=. A key belongs to exactly one app: every channel is that app's own.
Prefer the Authorization header where the client allows it (REST, Node.js, mobile). Browsers cannot set headers on a WebSocket, so they use ?key=; put the server behind a proxy that does not log query strings.
WebSocket
Connect to wss://host/ws?key=zk_…. Every message is one JSON text frame: the operation in op, the channel in path, the arguments in data.
{"id":"1","op":"msg.join","path":"live-42","data":{"history":true,"limit":30}}
{"id":"2","op":"msg.send","path":"live-42","data":{"text":"hello","isStore":true}}
{"id":"3","op":"msg.send","path":"live-42","data":{"text":"psst","to":["bob"]}}
{"id":"4","op":"msg.history","path":"live-42","data":{"limit":30,"before":120}}
{"id":"5","op":"msg.leave","path":"live-42"}
{"id":"6","op":"ping"}{"id":"2","ok":true,"path":"live-42","data":{"message":{ },"delivered":3}} // send reply
{"id":"9","ok":false,"error":"join the channel first"} // failure
{"event":"msg.message","path":"live-42","ok":true,"data":{ }} // a message pushed to every subscriber- Echo the client-generated
idto match replies to requests. - Live events:
msg.message,msg.updated,msg.deleted,msg.typing,msg.receipt,msg.presence,msg.cleared. Nothing arrives for a channel you have not joined. pingreplies{"id":"6","ok":true}. SDKs send it on an idle connection as a heartbeat: a browser cannot see WebSocket ping frames, and a silent network drop must be noticed in seconds. It is not metered and not written to the activity log.- The server sends WebSocket ping frames every 30 s and drops connections that stay silent for 70 s; any message counts as activity.
- The operations (
msg.join,msg.send,msg.history,msg.edit,msg.delete,msg.typing,msg.seen, ...) and their arguments are listed on the Messaging page.
Socket.IO
Endpoint /socket.io/, Socket.IO v4 over the websocket transport only (set transports: ['websocket']). Authenticate with auth: {key: 'zk_…'} or ?key=. The events are the same msg.* operations, with the arguments in the first argument and an acknowledgement as the reply, for example emit('msg.send', {channel: 'live-42', text: 'hi'}, ack); the live events are pushed under the same names (msg.message, ...).
REST
Base URL https://host/msg/<channel>, header Authorization: Bearer zk_…, JSON bodies up to 1 MB. For backends: a message posted over REST is broadcast to everyone subscribed over WebSocket or Socket.IO at once.
| Method | Meaning | Response |
|---|---|---|
POST /msg/live-42 | Send as the server ({"text","data","from","to","isStore"}) | {"message":{…},"delivered":n} |
GET /msg/live-42?limit=30&before=120 | History (the server side sees every message, private ones too) | {"messages":[…],"hasMore":bool,"lastSeq":n} |
GET /msg | List the app's channels | {"channels":[…]} |
PUT /msg/live-42 | Create a channel on purpose | {"ok":true,"created":bool} |
PATCH /msg/live-42/<id> | Edit a message | {"message":{…}} |
DELETE /msg/live-42/<id> | Delete one message | {"message":{…}} |
DELETE /msg/live-42 | Remove every message of the channel | {"ok":true,"removed":n} |
GET /whoami | Check a key | app, customer, limits, usage and the socket/REST URLs (never the key) |
curl -X POST https://your-server/msg/live-42 \
-H "Authorization: Bearer zk_YOUR_ACCESS_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"The stream starts now","from":"system"}'Errors & connection states
All SDKs expose the same states and the same six error codes.
Connection states
| State | Meaning |
|---|---|
| disconnected | Not connected and not trying (before connect(), after disconnect()). |
| connecting | Opening, or waiting to retry after a network problem. Retries back off from 1 s to 10 s. |
| connected | Live. Your channels are joined and messages arrive. |
| rejected | The server answered but refused the key. The reason is in lastError. A wrong, revoked or deleted key stops retrying; other refusals are retried every 60 s. |
Error codes
| Code | HTTP | When | What to do |
|---|---|---|---|
| unauthorized | 401 | The key is wrong, revoked or deleted. | Stop. Ask the user to sign in again or fetch a new key, then useAccessKey(). |
| rejected | 403 · 429 | Account or app suspended, key disabled, your IP blocked, origin not allowed, rate limited, or locked out after too many wrong keys. | Retried automatically every 60 s. Show lastError. |
| timeout | — | No answer within the request timeout (default 15 s), or the connection did not come up in time. | Retry the call. |
| disconnected | — | The connection dropped or was closed while a call was in flight; or the server is unreachable. | The SDK reconnects by itself; retry the call. |
| invalid | 400 | Bad channel name (empty, over 128 characters or containing /), bad message (empty, over 8,000 bytes of text or 16 KB of data), bad to list, or missing key/URL. | Fix the input. |
| server | 5xx · other | The server refused the operation: not joined to the channel, storage quota exceeded (507), connection limit reached (503), invalid JSON. | Read the message. |
The server counts every wrong key: 10 wrong keys in a minute lock the client's IP out for 5 minutes (HTTP 429). That is why the SDKs stop retrying on unauthorized instead of hammering the server.
Limits
Defaults of a stock server. Operators set the start-up values with flags and can change every rate limit at any time, with no restart, in the admin console under Rate limits (or GET/PUT /api/limits).
| Limit | Value |
|---|---|
| Message / request body size | 1 MB |
| Text per message · data per message | 8,000 bytes · 16 KB of JSON |
| Channel name · channels joined per connection · channels per app | 128 characters · 100 · 5,000 |
| Recipients of one private message | 100 |
| Operations per second per connection | 200 sustained, burst 400 (-ops-per-sec); persistent abusers are disconnected |
| Connections per IP · server-wide | 200 · 10,000 (-max-conns-per-ip, -max-conns) |
| Storage quota (per app) | Set on each app, any number from 1 MB, no upper limit, default 100 MB |
| Connections (per app) | Set on each app, default 1,000 |
| Active keys per app | 20 |
| Apps per customer | 50 |
| New connections per IP | 600 per minute (editable in the console) |
| REST / console requests per IP | 200 per second, burst 400 (editable) |
| Wrong-key lockout | 10 per minute → 5 minutes per IP (editable) |
| Slow clients | A client that stops reading is disconnected and re-syncs on reconnect |
Not available yet: rules that decide which user may join which channel. An app's messages are held in memory (bounded per channel by Keep per channel) and journaled to disk; idle apps are unloaded after 15 minutes.
Security & keys
An access key is a password to one app's data. Treat it like one.
One key per client type
Create a separate key for each platform and for your backend: a Web key, an Android key, a Server key. If one leaks you disable or revoke only that one, and live connections using it are cut immediately.
Keys in apps
- Browser and mobile apps ship their key inside the app: anyone can extract it. That is expected for client SDKs; limit the damage with a dedicated key and the app's IP block list.
- Servers (Next.js server code, Python, Go, PHP, .NET backends) keep the key in an environment variable or secret manager, never in source control and never in a
NEXT_PUBLIC_variable.
Browsers
Browser connections must come from an origin allowed by the server's -origins flag (default *, because every connection still needs a valid key). Lock it down to your domains in production. Native apps send no Origin header and are always allowed.
Transport
Always use https:// / wss:// in production. WebSocket keys travel in the query string, so make sure your reverse proxy does not log query strings (the bundled installer's nginx config does not).
Rotating a key
// 1. generate a new key in the console, 2. give it to the running app, 3. revoke the old one
db.useAccessKey('zk_NEW_KEY'); // listeners are keptReliability & reconnection
Mobile and office networks drop all the time. Every realtime SDK notices, reconnects by itself, and rejoins your channels, with no code on your side.
What happens when the network drops
- Notice. A closed or reset connection is seen at once. A silent drop (a half-open connection) is caught by the heartbeat: the SDK pings an idle connection and, if nothing comes back in time, declares it dead.
- Ask why. It calls
GET /whoami. If the network is down the call fails and the SDK keeps retrying. If the server answers401the key is wrong or revoked: state becomesrejectedand retrying stops. If it answers403or429(suspended, disabled key, blocked IP, lockout) the state isrejectedand it retries every 60 s. - Retry with backoff. About 1 s, 1.7 s, 2.9 s, 4.9 s, 8.4 s, then every 10 s, each with random jitter so thousands of clients do not reconnect at the same instant. Where the platform reports “network is back” (browsers, Android, iOS, .NET) the SDK reconnects immediately instead of waiting.
- Restore. On reconnect every channel you joined is joined again and the messages you missed while offline are delivered through the same listener. Calls you made while offline wait for the connection (up to the request timeout) and then go through.
Detection and recovery by SDK
| SDK | Silent drop noticed | Network back | Tuning |
|---|---|---|---|
| JavaScript, React, Next.js (client) | heartbeat: 25 s + 10 s (max about 35 s) | immediately in browsers (online event, tab visible); else next retry (max 10 s) | heartbeatMs, heartbeatTimeoutMs |
| Flutter | Socket.IO ping: 25 s + 20 s (about 45 s); also a 30 s watchdog and a reconnect on app resume | next retry (max 10 s); reconnect when the app returns to the foreground | built in |
| Android (Kotlin) | WebSocket ping every heartbeatMs (20 s): about 20–40 s | immediately with autoReconnectOnNetwork(context) | ZabOptions.heartbeatMs |
| iOS / macOS (Swift) | heartbeat: 25 s + 10 s | immediately (NWPathMonitor, built in) | ZabOptions.heartbeat, heartbeatTimeout |
| .NET | heartbeat: 25 s + 10 s | immediately (NetworkChange, built in) | HeartbeatInterval, HeartbeatTimeout |
| Python | WebSocket ping: 25 s + 10 s | next retry (max 10 s) | heartbeat, heartbeat_timeout |
| Go | heartbeat: 25 s + 10 s | next retry (max 10 s) | Options.HeartbeatInterval, HeartbeatTimeout |
| Next.js server, PHP, REST clients | no connection to lose: each call is independent | the next call just works | timeout option |
Lower the heartbeat for faster detection (for example 10 s + 5 s) at the cost of a little more traffic. The ping is cheap: it is not metered and does not appear in the activity log.
What your code should do
- Show the connection state (
state,lastError) so users know when they are offline. Do not build your own reconnect loop. - Treat
unauthorizedas final: ask the user to sign in again or fetch a new key, then calluseAccessKey. - Treat
timeoutanddisconnectedfrom a call as retryable. - REST calls (PHP, Next.js server,
ZabRest, GoREST) do not retry for you: wrap them in your own retry for critical writes.
Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
State stays rejected with “unauthorized” | The key is wrong, was revoked or its app was deleted. Check it with GET /whoami or the console's API key tester; give the app a new key. |
rejected with “this access key is disabled” / “suspended” | An admin switched the key, app or customer off. The SDK retries every 60 s and recovers by itself once it is switched on. |
rejected with “your IP address is blocked” | The address is on the app's or the system IP block list (console → IP block list). |
| HTTP 429 / “too many failed attempts” | Ten wrong keys in a minute from one IP. Wait five minutes, fix the key, and avoid retry loops. |
| Browser: connection fails, nothing in the console | Origin not allowed (-origins) or an http:// page connecting to wss:// with a bad certificate. Open the Network tab and look at the /ws request. |
| Flutter on the Android emulator cannot reach localhost | Use http://10.0.2.2:8080, and allow cleartext HTTP for non-TLS development. |
timeout on every call | The connection is not up (check state), or a proxy strips WebSocket upgrades: it must forward Upgrade and Connection headers and allow read timeouts of 120 s or more. |
server error “storage quota exceeded” | The app reached its quota. Delete data or raise the app's storage quota (edit the app in the console). |
join the channel first | You must subscribe (join) before you send, read history or ask for receipts (who is online can be asked for any channel). Connecting with the key alone gives you no channel data. |
| A private message did not arrive | The recipient must be joined to the channel and the to user id must match theirs exactly (ids are labels: check the id the other client really uses). |
| Socket.IO: “Only the websocket transport is supported” | Set transports: ['websocket'] (Flutter: setTransports(['websocket'])). |
Want ZabMessaging for your app?
Tell us your platform and what you want to build, and we will set up your access.
