Loading ZabSys Cloud…

New Business software, email, SMS and AI built for growing companies, with support by a real team

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

Mobile & Desktop

Backend & Desktop

Any 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: join a channel, send messages, get every new message instantly, load history separately, show typing and seen receipts. Whether a join brings the old messages is an app option in the admin console.
  • Subscribe, send, store: join several channels at once, send to everyone in a channel (you included) or to specific users only, keep a message in the channel history or send it live-only with one isStore parameter, and leave one channel or leaveAll.
  • 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

Architecture
  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, monitor

Why each part exists

Why ZabMessaging
PartWhy it is there
Access keyOne 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 → KeyLets 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.
ChannelsA 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 notOne 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 messagesto 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 SDKsPhones 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 RESTWebSocket 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 probeA 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 SDKsThe 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.

  1. Sign in to the admin console at https://your-server/admin.
  2. Create a customer (name and e-mail).
  3. Create an app on the customer page, for example “Mobile app”: pick its platforms and set its storage quota and connection limit.
  4. Generate a key on the app page. It looks like zk_ plus 40 characters. Show key displays it again later.
  5. Test the key with the console's API key tester, or from a shell:
bash
curl -H "Authorization: Bearer zk_YOUR_ACCESS_KEY" https://your-server/whoami

Then 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

Install · npm (from the SDK folder)
npm install ./sdk/web/zab-messaging-js
Install · Browser, 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>
Install · Node.js 18 / 20 (no built-in WebSocket)
npm install ws
Join a channel, send, history, typing, seen
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 message

Full JavaScript documentation →

React SDK

Install · npm (from the SDK folder)
npm install ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-js
Join a channel, send, history, typing, seen
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)} />
  </>);
}

Full React documentation →

Next.js SDK

Install · npm (from the SDK folder)
npm install ./sdk/nextjs/zab-messaging-next ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-js
Install · .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 key
Install · next.config.js (when installed from a local folder)
module.exports = { transpilePackages: ['zab-messaging-next', 'zab-messaging-react', 'zab-messaging'] };
Join a channel, send, history, typing, seen
// 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>);
}

Full Next.js documentation →

Flutter SDK

Install · pubspec.yaml
dependencies:
  zab_messaging:
    path: ../ZabMessaging/sdk/flutter/zab_messaging   # or your git / pub.dev source
Join a channel, send, history, typing, seen
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 message

Full Flutter documentation →

Android (Kotlin) SDK

Install · settings.gradle.kts
include(":zab-messaging")
project(":zab-messaging").projectDir = file("path/to/ZabMessaging/sdk/android/zab-messaging")
Install · app/build.gradle.kts
dependencies { implementation(project(":zab-messaging")) }
// or, after ./gradlew :zab-messaging:publishToMavenLocal:
// implementation("com.zabsys:zab-messaging:1.0.0")
Install · Local server on the emulator
<!-- http://10.0.2.2:8080 needs cleartext traffic; use https in production -->
<application android:usesCleartextTraffic="true" ... />
Join a channel, send, history, typing, seen
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 message

Full Android (Kotlin) documentation →

iOS & macOS (Swift) SDK

Install · Xcode
File → Add Package Dependencies… → Add Local… → choose sdk/ios
Install · Package.swift
dependencies: [ .package(path: "../ZabMessaging/sdk/ios") ],      // or your Git URL once published
targets: [ .target(name: "MyApp", dependencies: [.product(name: "ZabMessaging", package: "ios")]) ]
Join a channel, send, history, typing, seen
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

Full iOS (Swift) documentation →

.NET (C#) SDK

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 feed
Join a channel, send, history, typing, seen
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 message

Full .NET (C#) documentation →

Python SDK

Install · pip (from the SDK folder)
pip install ./sdk/python
Join a channel, send, history, typing, seen
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")

Full Python documentation →

Go SDK

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/go
Join a channel, send, history, typing, seen
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 message

Full Go documentation →

PHP SDK

Install · Composer
composer require zabsys/zab-messaging
# or a path repository pointing at ./sdk/php
Join a channel, send, history, typing, seen
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 first

Full PHP documentation →

Messaging (channels)

  • Connection and presence: 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.
  • Typing and seen: 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:

    Messaging (channels)
    OptionDefaultMeaning
    Clients may create channelsonOn: 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 messagesonAsked 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 joinoffOn: 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 join501 to 1000. Older pages: history({before: seq}) or loadMore().
    Keep per channel10,000The oldest messages beyond this are dropped.
    Typing / receipts / presenceonEach 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

    Messaging (channels)
    FieldMeaning
    id, seqUnique 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).
    fromThe 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, dataUp to 8,000 bytes of text and/or up to 16 KB of any JSON (a gift, a sticker, a vote).
    toPrivate 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, deletedMilliseconds 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)

    bash
    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.

    json
    {"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>"}}
    Messaging (channels)
    OperationArgumentsResult
    msg.joinhistory, limit, afteronline, lastSeq, unread, historyOnJoin, messages?, hasMore?
    msg.sendtext and/or data, replyTo, clientId, isStore, tomessage, delivered (to = private message to those user ids)
    msg.historylimit, before, after, receiptsmessages (oldest first), hasMore, lastSeq
    msg.edit / msg.deleteid (+ text / data)message (author only)
    msg.typing, msg.seen, msg.deliveredtyping / 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

    Core concepts
    CallWhat it does
    sendSends 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).
    isStoreOne 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.
    toA 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.
    historyLoads old messages separately, any time, oldest first, in pages (before / after).
    edit / deleteThe author changes or removes a message; everyone subscribed is told (the message stays as a tombstone so the numbering does not change).
    leave / leaveAllUnsubscribes from one channel or from every channel. Nothing is deleted: leaving only stops the stream.
    A message (to only on a private one)
    { "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 an anon_… 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? setUserId re-identifies the live connection and keeps your channels.

    Customer, app, key

    Core concepts
    LevelMeaning
    CustomerYour client or tenant. Groups apps and can be suspended: that cuts every live connection of every one of its apps.
    AppOne 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 IDOptional label for the end user behind a request, shown in the activity log. Yours, or generated when you send none.
    Access keyzk_ + 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.

    Tested against a live serverv1.0.0zab-messaging

    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)

    bash
    npm install ./sdk/web/zab-messaging-js

    Browser, without a bundler

    html
    <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)

    bash
    npm install ws

    Quick start: subscribe, send, receive

    javascript
    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 message

    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

    JavaScript / Node.js SDK
    OperationCall
    Join a channelconst r = await room.join({ history?: true | false, limit? }) (history: true = load old messages with the join)
    Send a messageawait 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 pageawait room.loadMore(limit)
    Typing indicatorroom.setTyping(true | false)
    Mark seen (receipts)await room.markSeen(upToMessage?)
    Edit / deleteawait room.edit(id, text) · await room.delete(id)
    Members, unread, receipts, channelsawait room.members() · room.unread() · room.receipts(id) · zab.channels() · zab.messagingConfig()
    Connected? joined channels? who is online? statszab.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

    javascript
    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

    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.

    javascript
    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.

    javascript
    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 channel

    Private 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.

    javascript
    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 join

    Connection 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.

    javascript
    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 channels

    Node.js 18 / 20

    Pass the WebSocket class from the ws package.

    javascript
    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.

    Tested against a live serverv1.0.0zab-messaging-react

    Requirements

    • React 18+
    • Depends on zab-messaging (the JavaScript SDK)
    • Works with Vite, CRA, Remix, Expo web

    Install

    npm (from the SDK folder)

    bash
    npm install ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-js

    Quick start: subscribe, send, receive

    jsx
    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

    React SDK
    OperationCall
    Join a channelconst chat = useZabChannel(name, { history, limit, autoSeen }) (joins on mount; history: true loads old messages with the join)
    Send a messageawait 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 pageawait chat.loadMore(limit) · chat.hasMore
    Typing indicatorchat.setTyping(true)
    Mark seen (receipts)await chat.markSeen(upToMessage?) (or autoSeen: true)
    Edit / deleteawait chat.edit(id, text) · await chat.remove(id)
    Members, unread, receipts, channelschat.channel (the underlying channel object for members(), receipts()...)
    Connected? joined channels? who is online? statsconst { 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

    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

    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

    bash
    VITE_ZAB_URL=https://chat.example.com
    VITE_ZAB_KEY=zk_YOUR_ACCESS_KEY

    User 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

    React SDK
    NameDescription
    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

    jsx
    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 history

    Connection banner

    jsx
    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.

    Next.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.

    Tested against a live serverv1.0.0zab-messaging-next

    Requirements

    • Next.js 13.4+ (App Router or Pages Router)
    • React 18+
    • /server entry: Route Handlers, Server Components, Server Actions, middleware
    • /client entry: Client Components

    Install

    npm (from the SDK folder)

    bash
    npm install ./sdk/nextjs/zab-messaging-next ./sdk/react/zab-messaging-react ./sdk/web/zab-messaging-js

    .env.local

    bash
    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 key

    next.config.js (when installed from a local folder)

    javascript
    module.exports = { transpilePackages: ['zab-messaging-next', 'zab-messaging-react', 'zab-messaging'] };

    Quick start: subscribe, send, receive

    jsx
    // 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

    Next.js SDK
    OperationCall
    Join a channel'use client': useZabChannel(name) (joins on mount)
    Send a messageclient: 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 pagechat.loadMore(limit)
    Typing indicatorclient: chat.setTyping(true)
    Mark seen (receipts)client: chat.markSeen()
    Edit / deleteserver: zab.messages.edit(ch, id, text) · delete(ch, id) · clear(ch)
    Members, unread, receipts, channelsserver: zab.messages.channels({ prefix })
    Connected? joined channels? who is online? statsawait 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

    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

    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)

    jsx
    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)

    jsx
    '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)

    javascript
    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

    bash
    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_KEY

    User 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)

    jsx
    // 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

    javascript
    // 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.

    Tested against a live serverv1.0.0zab_messaging

    Requirements

    • Flutter 3.x / Dart 3
    • Android, iOS, web, Windows, macOS, Linux
    • Uses socket_io_client

    Install

    pubspec.yaml

    yaml
    dependencies:
      zab_messaging:
        path: ../ZabMessaging/sdk/flutter/zab_messaging   # or your git / pub.dev source

    Quick start: subscribe, send, receive

    dart
    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 message

    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

    Flutter SDK
    OperationCall
    Join a channelfinal r = await room.join(history: true, limit: n) (true = load old messages with the join, false = none, omitted = the app's setting)
    Send a messageawait 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 pageawait room.loadMore([limit])
    Typing indicatorroom.setTyping(true)
    Mark seen (receipts)await room.markSeen([upTo])
    Edit / deleteawait room.edit(id, text: "…") · await room.delete(id)
    Members, unread, receipts, channelsawait room.members() · room.unread() · room.receiptsOf(id) · db.channels() · db.messagingConfig()
    Connected? joined channels? who is online? statszab.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

    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

    dart
    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 channel

    Connection status

    dart
    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.

    Build & test once before shippingv1.0.0com.zabsys:zab-messaging

    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

    kotlin
    include(":zab-messaging")
    project(":zab-messaging").projectDir = file("path/to/ZabMessaging/sdk/android/zab-messaging")

    app/build.gradle.kts

    kotlin
    dependencies { implementation(project(":zab-messaging")) }
    // or, after ./gradlew :zab-messaging:publishToMavenLocal:
    // implementation("com.zabsys:zab-messaging:1.0.0")

    Local server on the emulator

    xml
    <!-- http://10.0.2.2:8080 needs cleartext traffic; use https in production -->
    <application android:usesCleartextTraffic="true" ... />

    Quick start: subscribe, send, receive

    kotlin
    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 message

    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

    Android (Kotlin) SDK
    OperationCall
    Join a channelval r = room.join(history = true, limit = n) (true = load old messages with the join, false = none, null = the app's setting)
    Send a messageroom.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 pageroom.loadMore(limit)
    Typing indicatorroom.setTyping(true)
    Mark seen (receipts)room.markSeen(upToId?)
    Edit / deleteroom.edit(id, text) · room.delete(id)
    Members, unread, receipts, channelsroom.members() · room.unread() · room.receiptsOf(id) · zab.channels() · zab.messagingConfig()
    Connected? joined channels? who is online? statszab.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

    kotlin
    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

    kotlin
    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

    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

    kotlin
    @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

    kotlin
    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 channel

    Build 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.

    Build & test once before shippingv1.0.0ZabMessaging (Swift Package)

    Requirements

    • iOS 15+, macOS 12+, tvOS 15+, watchOS 8+
    • Swift 5.7+ / Xcode 14+
    • No third-party dependencies

    Install

    Xcode

    text
    File → Add Package Dependencies… → Add Local… → choose sdk/ios

    Package.swift

    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

    swift
    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

    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

    iOS & macOS (Swift) SDK
    OperationCall
    Join a channellet 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 messagetry 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 pagetry await room.loadMore(limit)
    Typing indicatorroom.setTyping(true)
    Mark seen (receipts)try await room.markSeen(upToId)
    Edit / deletetry await room.edit(id, text:) · try await room.delete(id)
    Members, unread, receipts, channelstry await room.members() · room.unread() · room.receipts(of: id) · zab.channels()
    Connected? joined channels? who is online? statszab.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

    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

    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

    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

    swift
    @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

    swift
    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 channel

    Build 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.

    Build & test once before shippingv1.0.0ZabSys.Messaging

    Requirements

    • .NET 8+ or .NET Standard 2.1
    • Unity 2021.2+, MAUI, Xamarin
    • System.Text.Json (no other dependencies)

    Install

    Project reference

    bash
    dotnet add reference ./sdk/dotnet/ZabMessaging/ZabMessaging.csproj
    # or: dotnet pack ./sdk/dotnet/ZabMessaging -c Release   then publish ZabSys.Messaging to your NuGet feed

    Quick start: subscribe, send, receive

    csharp
    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 message

    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

    .NET (C#) SDK
    OperationCall
    Join a channelvar r = await room.JoinAsync(history: true, limit: n) (true = load old messages with the join, false = none, null = the app's setting)
    Send a messageawait 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 pageawait room.LoadMoreAsync(limit)
    Typing indicatorroom.SetTyping(true)
    Mark seen (receipts)await room.MarkSeenAsync(upToId)
    Edit / deleteawait room.EditAsync(id, text) · await room.DeleteAsync(id)
    Members, unread, receipts, channelsawait room.MembersAsync() · UnreadAsync() · ReceiptsAsync(id) · zab.ChannelsAsync()
    Connected? joined channels? who is online? statszab.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)

    csharp
    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 channel

    User 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

    csharp
    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

    csharp
    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 channel

    Build 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.

    Tested against a live serverv1.0.0zab-messaging

    Requirements

    • Python 3.8+
    • ZabMessaging (asyncio) needs websockets
    • ZabRest needs nothing

    Install

    pip (from the SDK folder)

    bash
    pip install ./sdk/python

    Quick start: subscribe, send, receive

    python
    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

    Python SDK
    OperationCall
    Join a channelr = await room.join(history=True, limit=n) (True = load old messages with the join, False = none, None = the app's setting)
    Send a messageawait 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 pageawait room.load_more(limit)
    Typing indicatorroom.set_typing(True)
    Mark seen (receipts)await room.mark_seen(up_to)
    Edit / deleteawait room.edit(id, text) · await room.delete(id)
    Members, unread, receipts, channelsawait 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? statszab.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

    python
    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)

    python
    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.

    python
    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 user

    Blocking REST client

    For scripts, cron jobs and Django / Flask / FastAPI handlers. No dependencies. Everything you send reaches the subscribers of the channel at once.

    python
    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

    python
    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 channel

    Errors

    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.

    Go 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.

    Tested against a live serverv1.0.0github.com/zabsys/zabmessaging-go

    Requirements

    • Go 1.22+
    • gorilla/websocket

    Install

    go get / replace

    bash
    go get github.com/zabsys/zabmessaging-go
    # from the SDK folder:
    go mod edit -replace github.com/zabsys/zabmessaging-go=./sdk/go

    Quick start: subscribe, send, receive

    go
    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 message

    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

    Go SDK
    OperationCall
    Join a channelr, err := room.Join(ctx, JoinOptions{LoadHistory, NoHistory, Limit}) (LoadHistory = old messages come with the join)
    Send a messageroom.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 pageroom.LoadMore(ctx, limit)
    Typing indicatorroom.SetTyping(true)
    Mark seen (receipts)room.MarkSeen(ctx, upToID)
    Edit / deleteroom.Edit(ctx, id, text) · room.Delete(ctx, id)
    Members, unread, receipts, channelsroom.Members(ctx) · Unread(ctx) · Receipts(ctx, id) · client.Channels(ctx, prefix, limit)
    Connected? joined channels? who is online? statsclient.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

    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

    go
    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.

    go
    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 message

    Many channels, private messages, Store

    go
    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 channel

    Errors

    Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.

    PHP 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.

    Tested against a live serverv1.0.0zabsys/zab-messaging

    Requirements

    • PHP 8.0+
    • ext-json
    • REST only: PHP requests are short-lived, so there are no live subscriptions

    Install

    Composer

    bash
    composer require zabsys/zab-messaging
    # or a path repository pointing at ./sdk/php

    Quick start: subscribe, send, receive

    php
    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 first

    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

    PHP SDK
    OperationCall
    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
    <?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

    php
    // 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

    php
    $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 message

    Errors

    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.

    Requests
    {"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"}
    Replies and events
    {"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 id to 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.
    • ping replies {"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.

    Protocol & REST API
    MethodMeaningResponse
    POST /msg/live-42Send as the server ({"text","data","from","to","isStore"}){"message":{…},"delivered":n}
    GET /msg/live-42?limit=30&before=120History (the server side sees every message, private ones too){"messages":[…],"hasMore":bool,"lastSeq":n}
    GET /msgList the app's channels{"channels":[…]}
    PUT /msg/live-42Create 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-42Remove every message of the channel{"ok":true,"removed":n}
    GET /whoamiCheck a keyapp, customer, limits, usage and the socket/REST URLs (never the key)
    Example
    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

    Errors & connection states
    StateMeaning
    disconnectedNot connected and not trying (before connect(), after disconnect()).
    connectingOpening, or waiting to retry after a network problem. Retries back off from 1 s to 10 s.
    connectedLive. Your channels are joined and messages arrive.
    rejectedThe 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

    Errors & connection states
    CodeHTTPWhenWhat to do
    unauthorized401The key is wrong, revoked or deleted.Stop. Ask the user to sign in again or fetch a new key, then useAccessKey().
    rejected403 · 429Account 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.
    invalid400Bad 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.
    server5xx · otherThe 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).

    Limits
    LimitValue
    Message / request body size1 MB
    Text per message · data per message8,000 bytes · 16 KB of JSON
    Channel name · channels joined per connection · channels per app128 characters · 100 · 5,000
    Recipients of one private message100
    Operations per second per connection200 sustained, burst 400 (-ops-per-sec); persistent abusers are disconnected
    Connections per IP · server-wide200 · 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 app20
    Apps per customer50
    New connections per IP600 per minute (editable in the console)
    REST / console requests per IP200 per second, burst 400 (editable)
    Wrong-key lockout10 per minute → 5 minutes per IP (editable)
    Slow clientsA 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

    Rotate without losing listeners
    // 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 kept

    Reliability & 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

    1. 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.
    2. Ask why. It calls GET /whoami. If the network is down the call fails and the SDK keeps retrying. If the server answers 401 the key is wrong or revoked: state becomes rejected and retrying stops. If it answers 403 or 429 (suspended, disabled key, blocked IP, lockout) the state is rejected and it retries every 60 s.
    3. 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.
    4. 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

    Reliability & reconnection
    SDKSilent drop noticedNetwork backTuning
    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
    FlutterSocket.IO ping: 25 s + 20 s (about 45 s); also a 30 s watchdog and a reconnect on app resumenext retry (max 10 s); reconnect when the app returns to the foregroundbuilt in
    Android (Kotlin)WebSocket ping every heartbeatMs (20 s): about 20–40 simmediately with autoReconnectOnNetwork(context)ZabOptions.heartbeatMs
    iOS / macOS (Swift)heartbeat: 25 s + 10 simmediately (NWPathMonitor, built in)ZabOptions.heartbeat, heartbeatTimeout
    .NETheartbeat: 25 s + 10 simmediately (NetworkChange, built in)HeartbeatInterval, HeartbeatTimeout
    PythonWebSocket ping: 25 s + 10 snext retry (max 10 s)heartbeat, heartbeat_timeout
    Goheartbeat: 25 s + 10 snext retry (max 10 s)Options.HeartbeatInterval, HeartbeatTimeout
    Next.js server, PHP, REST clientsno connection to lose: each call is independentthe next call just workstimeout 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 unauthorized as final: ask the user to sign in again or fetch a new key, then call useAccessKey.
    • Treat timeout and disconnected from a call as retryable.
    • REST calls (PHP, Next.js server, ZabRest, Go REST) do not retry for you: wrap them in your own retry for critical writes.

    Troubleshooting

    Troubleshooting
    SymptomLikely 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 consoleOrigin 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 localhostUse http://10.0.2.2:8080, and allow cleartext HTTP for non-TLS development.
    timeout on every callThe 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 firstYou 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 arriveThe 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.