
Sync your app's data with ZabRealtimeKit
A realtime JSON database with live listeners and offline-safe reconnects. One server address and one access key, with SDKs for web, mobile and backends.
ZabRealtimeKit SDKs
A self-hosted realtime JSON database. Connect from any platform with one server URL and one access key: live listeners, chronological push IDs, offline-safe reconnects and a REST fallback.
Customer → App → Access key. Every access key (zk_…) opens exactly one app's private database. Apps never see each other's data.
Choose your platform
Web & JavaScript
Browsers and Node.js. Zero dependencies: uses the platform WebSocket and fetch.
Tested against a live serverA provider and hooks: live values, lists and connection status in components.
Tested against a live serverNNext.jsApp Router and Pages Router: a server-side REST client plus live hooks for Client Components.
Tested against a live serverMobile & Desktop
Android, iOS, web and desktop. One app-wide connection, per-screen subscriptions.
Tested against a live serverCoroutines, StateFlow and Flow over an OkHttp WebSocket. Also runs on the plain JVM.
Build & test once before shippingA Swift Package with async/await and AsyncStream over URLSessionWebSocketTask. No dependencies.
Build & test once before shippingBackend & Desktop
ASP.NET Core, MAUI, WPF, Xamarin and Unity. ClientWebSocket, async/await, System.Text.Json.
Build & test once before shippingAn asyncio realtime client and a dependency-free blocking REST client.
Tested against a live serverGoGoA WebSocket client with listeners and auto-reconnect, plus a stateless REST client.
Tested against a live serverPPHPA dependency-free REST client for Laravel, Symfony, WordPress and plain PHP.
Tested against a live serverAny other language
Everything the SDKs do is plain WebSocket JSON or REST. See the protocol reference to build a client for Ruby, Java, Rust, C++ or anything else in an afternoon.
What every SDK gives you
- Firebase-style calls:
set,update,push(chronological key),get,remove, liveonValue. - Offline-safe: calls wait for the connection and live listeners are restored after every reconnect.
- 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 ZabRealtimeKit server. Build & test once before shipping means the code is complete; build and test it in your own project before you ship.
Why ZabRealtimeKit
Most apps need the same thing: data that several users or devices see change as it happens, without you building and running a realtime backend first.
The problem it solves
A chat, a live order board, a presence indicator or a shared checklist needs a server that holds open connections, authenticates every client, keeps customers' data apart, limits abuse and survives flaky mobile networks. That is weeks of work and a lot to get wrong. ZabRealtimeKit is that backend, ready to run: you install it once on your server and your clients connect with a URL and a key.
How the pieces fit
your apps (Web, React, Next.js, Flutter, Android, iOS, .NET) your backends (Python, Go, PHP, Node, Next.js server)
| WebSocket: live values, writes | REST: writes, reads, jobs
v v
+---------------------------- ZabRealtime server ----------------------------+
| access key -> one APP -> one private JSON tree (customer quotas apply) |
+------------------------------------------------------------------------------+
admin console: customers, apps, keys, IP blocks, activity log, monitorWhy each part exists
| Part | Why it is there |
|---|---|
| Access key | One secret that says which app you are, with no user accounts to build. Each key opens exactly one private database. Revoking or disabling it cuts that client off instantly, without touching anyone else. |
| Customer → App → Key | Lets one server host many customers (or many of your own products). Storage quota and connection limit are set on each app, so every project can have its own; every app is isolated, so a leak in one never exposes another. |
| JSON tree with paths | Simple to reason about and flexible: any shape of data, addressed by users/u1/name. No schema migrations. |
| Live listeners | The client is told when data changes, so you do not poll. A listener sees changes at its path, above it or below it, and always receives the full current value. |
| Push IDs | Auto-generated keys that sort by creation time and never collide between devices, so appending to a list from many clients is safe and ordered without a counter. |
| Offline-safe SDKs | Phones lose signal. The SDKs queue calls until the connection is back, restore every listener after a reconnect and re-deliver the latest value, so a screen never stays stale. |
| WebSocket and REST | WebSocket for clients that watch data live; REST for backends that just write or read. REST writes still reach live listeners. |
| Heartbeat and probe | A connection can die silently (a Wi-Fi router unplugged). The SDK pings, notices within seconds, and asks the server why a connection failed, so it can tell “network down, retry” from “your key was revoked, stop”. See Reliability. |
| Per-platform SDKs | The wire protocol is plain JSON, but reconnection, backoff, listener restore, 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 queries (
orderBy,limit) or per-path security rules inside one app: not available yet. - Your data set is far larger than memory: each app's tree is held in RAM.
- You need multi-server scale-out: one server today.
Quickstart
From zero to a live value in five minutes.
- Sign in to the admin console at
https://your-server/admin. - Create a customer (name and e-mail).
- Create an app on the customer page, for example “Mobile app”: pick its platforms and set its storage quota and connection limit.
- Generate a key on the app page. It looks like
zk_plus 40 characters. Show key displays it again later. - Test the key with the console's API key tester, or from a shell:
curl -H "Authorization: Bearer zk_YOUR_ACCESS_KEY" https://your-server/whoamiThen give your app the server URL (https://your-server; wss://your-server/ws is accepted too) and the access key.
Pick your platform
JavaScript / Node.js SDK
npm install ./sdk/web/zab-realtime-js<script src="zab-realtime-js/dist/zab-realtime.global.js"></script>
<!-- or -->
<script type="module">
import { ZabRealtime } from './zab-realtime-js/dist/zab-realtime.mjs';
</script>npm install wsimport { ZabRealtime } from 'zab-realtime';
const db = new ZabRealtime('https://rtdb.example.com', { accessKey: 'zk_YOUR_ACCESS_KEY' });
await db.connect(); // rejects if the key is refused
await db.set('users/u1', { name: 'Alex' }); // replace
await db.update('users/u1', { city: 'Austin' }); // merge keys
const key = await db.push('orders', { item: 'tea' }); // auto chronological key
console.log(await db.get('users/u1')); // read once (null if empty)
const off = db.onValue('chats/room1', (data) => console.log(data)); // live
// later: off();React SDK
npm install ./sdk/react/zab-realtime-react ./sdk/web/zab-realtime-jsimport { ZabProvider, useZabList, useZabRef, useZabState } from 'zab-realtime-react';
export default function Root() {
return (
<ZabProvider url="https://rtdb.example.com" accessKey="zk_YOUR_ACCESS_KEY">
<Chat room="room1" />
</ZabProvider>
);
}
function Chat({ room }) {
const { items, loading } = useZabList('chats/' + room + '/messages'); // live, oldest first
const messages = useZabRef('chats/' + room + '/messages');
const { state } = useZabState();
if (loading) return <p>Loading…</p>;
return (
<>
<small>{state}</small>
<ul>{items.map(({ key, value }) => <li key={key}>{value.text}</li>)}</ul>
<button onClick={() => messages.push({ text: 'hi' })}>Send</button>
</>
);
}Next.js SDK
npm install ./sdk/nextjs/zab-realtime-next ./sdk/react/zab-realtime-react ./sdk/web/zab-realtime-jsZAB_URL=https://rtdb.example.com
ZAB_ACCESS_KEY=zk_SERVER_KEY # server only: never reaches the browser
NEXT_PUBLIC_ZAB_URL=https://rtdb.example.com
NEXT_PUBLIC_ZAB_ACCESS_KEY=zk_BROWSER_KEY # visible in the browser: use a separate, revocable keymodule.exports = { transpilePackages: ['zab-realtime-next', 'zab-realtime-react', 'zab-realtime'] };// app/users/[id]/page.jsx : a Server Component reads at request time
import { createZabServer } from 'zab-realtime-next/server';
const zab = createZabServer(); // reads ZAB_URL and ZAB_ACCESS_KEY
export const dynamic = 'force-dynamic';
export default async function User({ params }) {
const user = await zab.get('users/' + params.id);
return <h1>{user?.name ?? 'Unknown user'}</h1>;
}
// app/chat/room.jsx : a Client Component is live
'use client';
import { useZabList, useZabRef } from 'zab-realtime-next/client';
export default function Room() {
const { items } = useZabList('chats/room1/messages');
const messages = useZabRef('chats/room1/messages');
return (
<>
<ul>{items.map(({ key, value }) => <li key={key}>{value.text}</li>)}</ul>
<button onClick={() => messages.push({ text: 'hi' })}>Send</button>
</>
);
}Flutter SDK
dependencies:
zab_realtime:
path: ../ZabRealtimeKit/sdk/flutter/zab_realtime # or your git / pub.dev sourceimport 'package:zab_realtime/zab_realtime.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
ZabRealtimeIO.init('https://rtdb.example.com', accessKey: 'zk_YOUR_ACCESS_KEY').open(); // once
runApp(const MyApp());
}
// any screen
final db = ZabRealtimeIO.instance;
await db.set('users/u1', {'name': 'Alex'}); // replace
await db.update('users/u1', {'city': 'Austin'}); // merge keys
final key = await db.push('orders', {'item': 'tea'}); // auto chronological key
final user = await db.fetch('users/u1'); // read once
await db.delete('users/u1');
class _ChatState extends State<Chat> with ZabSubscriptions { // auto-unsubscribes when the screen is left
@override
void initState() {
super.initState();
zabSubscribe('chats/room1', (data) => setState(() => messages = data));
}
}Android (Kotlin) SDK
include(":zab-realtime")
project(":zab-realtime").projectDir = file("path/to/ZabRealtimeKit/sdk/android/zab-realtime")dependencies { implementation(project(":zab-realtime")) }
// or, after ./gradlew :zab-realtime:publishToMavenLocal:
// implementation("com.zabsys:zab-realtime:1.0.0")<!-- http://10.0.2.2:8080 needs cleartext traffic; use https in production -->
<application android:usesCleartextTraffic="true" ... />import com.zabsys.zabrealtime.*
val db = ZabRealtime("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY") // keep ONE instance for the whole app
lifecycleScope.launch {
try {
db.connect() // suspends; throws ZabException if refused
} catch (e: ZabException) {
Log.w("zab", e.code.name + ": " + e.message) // UNAUTHORIZED = wrong/revoked key
return@launch
}
db.set("users/u1", mapOf("name" to "Alex")) // replace
db.update("users/u1", mapOf("city" to "Austin")) // merge keys
val key = db.push("orders", mapOf("item" to "tea")) // auto chronological key
val user = db.get("users/u1") as? JSONObject // read once (null if empty)
db.remove("orders/$key")
db.observe("chats/room1").collect { value -> // live Flow; cancelling unsubscribes
// JSONObject / JSONArray / String / Number / Boolean / null
}
}iOS & macOS (Swift) SDK
File → Add Package Dependencies… → Add Local… → choose sdk/iosdependencies: [ .package(path: "../ZabRealtimeKit/sdk/ios") ], // or your Git URL once published
targets: [ .target(name: "MyApp", dependencies: [.product(name: "ZabRealtime", package: "ios")]) ]import ZabRealtime
let db = try ZabRealtime(url: "https://rtdb.example.com", accessKey: "zk_YOUR_ACCESS_KEY") // ONE instance for the app
do {
try await db.connect() // throws ZabError if the key is refused
} catch let e as ZabError {
print(e.code, e.message) // .unauthorized = wrong/revoked key
}
try await db.set("users/u1", ["name": "Alex"]) // replace
try await db.update("users/u1", ["city": "Austin"]) // merge keys
let key = try await db.push("orders", ["item": "tea"]) // auto chronological key
let user = try await db.get("users/u1") as? [String: Any] // read once (nil if empty)
try await db.remove("orders/\(key)")
for await value in db.values("chats/room1") { // live AsyncStream; leaving the loop unsubscribes
print(value as Any)
}.NET (C#) SDK
dotnet add reference ./sdk/dotnet/ZabRealtime/ZabRealtime.csproj
# or: dotnet pack ./sdk/dotnet/ZabRealtime -c Release then publish ZabSys.Realtime to your NuGet feedusing System.Text.Json.Nodes;
using ZabSys.Realtime;
await using var db = new ZabRealtime("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY"); // ONE instance per app
try { await db.ConnectAsync(); } // throws ZabException if the key is refused
catch (ZabException e) { Console.WriteLine($"{e.Code}: {e.Message}"); return; }
await db.SetAsync("users/u1", new { name = "Alex" }); // replace
await db.UpdateAsync("users/u1", new { city = "Austin" }); // merge keys
string key = await db.PushAsync("orders", new { item = "tea" }); // auto chronological key
JsonNode? user = await db.GetAsync("users/u1"); // read once (null if empty)
await db.RemoveAsync($"orders/{key}");
using var sub = db.OnValue("chats/room1", v => Console.WriteLine(v)); // live; dispose to stop
await foreach (var v in db.WatchAsync("users/u1", cts.Token)) { } // or an async streamPython SDK
pip install ./sdk/pythonimport asyncio
from zab_realtime import ZabRealtime, ZabError
async def main():
db = ZabRealtime("https://rtdb.example.com", access_key="zk_YOUR_ACCESS_KEY")
try:
await db.connect() # raises ZabError if the key is refused
except ZabError as e:
print("refused:", e.code, e) # 'unauthorized' = wrong/revoked key
return
await db.set("users/u1", {"name": "Alex"}) # replace
await db.update("users/u1", {"city": "Austin"}) # merge keys
key = await db.push("orders", {"item": "tea"}) # auto chronological key
print(await db.get("users/u1")) # read once (None if empty)
off = db.on_value("chats/room1", lambda v: print("room1:", v)) # live; sync or async callback
async for value in db.watch("users/u1"): # or an async iterator
print(value)
break
off()
await db.disconnect()
asyncio.run(main())Go SDK
go get github.com/zabsys/zabrealtime-go
# from the SDK folder:
go mod edit -replace github.com/zabsys/zabrealtime-go=./sdk/gopackage main
import (
"context"
"fmt"
"log"
zab "github.com/zabsys/zabrealtime-go"
)
func main() {
ctx := context.Background()
db, err := zab.New("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY")
if err != nil {
log.Fatal(err)
}
if err := db.Connect(ctx); err != nil { // *zab.Error: Code "unauthorized" (wrong/revoked key) or "rejected"
log.Fatal(err)
}
defer db.Close()
db.Set(ctx, "users/u1", map[string]any{"name": "Alex"}) // replace
db.Update(ctx, "users/u1", map[string]any{"city": "Austin"}) // merge keys
key, _ := db.Push(ctx, "orders", map[string]any{"item": "tea"})
var user struct{ Name, City string }
db.GetInto(ctx, "users/u1", &user) // read once into a struct
fmt.Println(key, user)
off := db.OnValue("chats/room1", func(v any) { fmt.Println("room1:", v) }) // live
defer off()
}PHP SDK
composer require zabsys/zab-realtime
# or a path repository pointing at ./sdk/php<?php
use ZabRealtime\ZabRealtime;
use ZabRealtime\ZabException;
$db = new ZabRealtime('https://rtdb.example.com', 'zk_YOUR_ACCESS_KEY');
try {
$db->set('users/u1', ['name' => 'Alex']); // replace
$db->update('users/u1', ['city' => 'Austin']); // merge keys
$key = $db->push('orders', ['item' => 'tea']); // auto chronological key
$user = $db->get('users/u1'); // read once (null if empty)
$db->remove('orders/' . $key);
} catch (ZabException $e) {
error_log($e->zabCode . ': ' . $e->getMessage()); // rejected | unauthorized | timeout | disconnected | invalid | server
}Core concepts
The data model is a single JSON tree per app, addressed by slash-separated paths.
Paths
A path like users/u1/name points into your app's tree. Leading and trailing slashes are ignored. A path may be at most 1,024 characters and 32 levels deep, with no empty segments.
Writing data
| Call | What it does |
|---|---|
| set | Replaces the value at the path (and everything below it). Setting null deletes. |
| update | Merges the given keys into the object at the path. Sibling keys are untouched; a null value deletes that key. |
| push | Appends under a new auto-generated key and returns it. Keys are 20 characters and sort chronologically, so the newest message is the last key. |
| remove / delete | Deletes the path. A node with no children does not exist, so empty parents disappear too (Firebase semantics). |
| get / fetch | Reads the current value once. Returns null when nothing is stored. |
{
"users": { "u1": { "name": "Alex", "city": "Austin" } },
"chats": { "room1": { "messages": { "-Oxk3…": { "text": "hi" } } } }
}Live listeners
A listener receives the current value immediately, then again whenever the value at its path, any ancestor or any descendant changes. The callback always gets the full fresh value at the listener's own path.
- Listeners registered while offline start when the connection is up.
- After a reconnect every listener is restored and re-delivers the latest value, so nothing missed while offline is lost.
- One client may hold up to 1,000 subscriptions.
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). 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.
- Not provided? The SDK generates a random id (
u_+ 8 hex characters) and keeps it for the life of the client (browsers remember it between page loads). Clients that send nothing at all (curl, a bare WebSocket) get ananon_…id from the server: random per realtime connection, and derived from the client's address for stateless REST calls so one client keeps one id. - Backends that act for many end users (a web server, a worker) should pass the end user's id on each call:
zab.as(userId),rest.as_user(id),rest.As(id),$db->as($id). - Signed in later?
setUserIdre-identifies the live connection and keeps your listeners.
Customer, app, key
| Level | Meaning |
|---|---|
| Customer | Your client or tenant. Groups apps and can be suspended: that cuts every live connection of every one of its apps. |
| App | One private database (like a Firebase project) with its own storage quota and connection limit. A customer's “Mobile app” and “Website” never see each other's data and can have different limits. |
| User ID | Optional label for the end user behind a request, shown in the activity log. Yours, or generated when you send none. |
| Access key | zk_ + 40 characters. Opens exactly one app. Can be disabled and enabled again, or revoked permanently. Both cut live connections immediately. |
JavaScript / Node.js SDK
Browsers and Node.js. Zero dependencies: uses the platform WebSocket and fetch.
Why this SDK? Use it for any web page, a Node.js service, a CLI or a bot. It has no dependencies, so it adds almost nothing to your bundle, and it is the base the React and Next.js SDKs are built on. Pick it when you want live data without a framework, or full control over how your UI is updated.
Requirements
- Any modern browser
- Node.js 18+ (22+ has WebSocket built in)
- ES module, CommonJS and <script> builds
- TypeScript types included
Install
npm (from the SDK folder)
npm install ./sdk/web/zab-realtime-jsBrowser, without a bundler
<script src="zab-realtime-js/dist/zab-realtime.global.js"></script>
<!-- or -->
<script type="module">
import { ZabRealtime } from './zab-realtime-js/dist/zab-realtime.mjs';
</script>Node.js 18 / 20 (no built-in WebSocket)
npm install wsQuick start
import { ZabRealtime } from 'zab-realtime';
const db = new ZabRealtime('https://rtdb.example.com', { accessKey: 'zk_YOUR_ACCESS_KEY' });
await db.connect(); // rejects if the key is refused
await db.set('users/u1', { name: 'Alex' }); // replace
await db.update('users/u1', { city: 'Austin' }); // merge keys
const key = await db.push('orders', { item: 'tea' }); // auto chronological key
console.log(await db.get('users/u1')); // read once (null if empty)
const off = db.onValue('chats/room1', (data) => console.log(data)); // live
// later: off();Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
Node.js: index.mjs
import { ZabRealtime, ZabError } from 'zab-realtime';
// Node 22+ has WebSocket built in. On Node 18 / 20: import WebSocket from 'ws'; and pass { accessKey, WebSocket }
const db = new ZabRealtime(process.env.ZAB_URL, { // e.g. https://rtdb.example.com
accessKey: process.env.ZAB_ACCESS_KEY, // zk_... (keep it in an environment variable)
userId: 'alice@example.com', // optional: names this user in the admin log (omit: generated)
});
// 1. Watch the connection. This is how you show "offline" in a UI or write a log line.
db.on('state', (state, reason) => console.log('[zab]', state, reason ?? ''));
db.on('rejected', (reason) => console.error('[zab] the server refused the key:', reason));
// 2. Connect. It resolves when connected, and rejects only if the server refuses the key.
// If the network is down right now it keeps retrying in the background, so give it a deadline.
try {
await Promise.race([
db.connect(),
new Promise((_, no) => setTimeout(() => no(new ZabError('No connection after 10 s', 'timeout')), 10000)),
]);
} catch (e) {
if (e.code === 'unauthorized') { console.error('Wrong or revoked key'); process.exit(1); }
console.warn('Not connected yet (' + e.code + '): continuing, the SDK keeps retrying');
}
// 3. Listen. The callback fires now with the current value, then on every change, and again after a reconnect.
const stop = db.onValue('chats/room1/messages', (messages) => console.log('messages:', messages));
// 4. Write. Calls made while offline wait for the connection instead of failing.
const key = await db.push('chats/room1/messages', { text: 'hello', at: Date.now() });
await db.update('users/u1', { lastSeen: Date.now() });
console.log('pushed', key, '| user:', await db.get('users/u1'));
// 5. Shut down cleanly.
process.on('SIGINT', () => { stop(); db.destroy(); process.exit(0); });Browser: index.html
<!doctype html>
<meta charset="utf-8"><title>ZabRealtime demo</title>
<p id="status">connecting…</p>
<ul id="list"></ul>
<button id="send">Send</button>
<script src="zab-realtime-js/dist/zab-realtime.global.js"></script>
<script>
const db = new ZabRealtime('https://rtdb.example.com', {
accessKey: 'zk_YOUR_BROWSER_KEY',
userId: 'alice@example.com', // optional: names this visitor in the admin log (omit: generated and remembered)
});
const status = document.getElementById('status');
db.on('state', (state, reason) => { status.textContent = state + (reason ? ' - ' + reason : ''); });
db.connect().catch((e) => { status.textContent = 'refused: ' + e.message; }); // 'unauthorized' = wrong/revoked key
db.onValue('chats/room1/messages', (data) => {
const list = document.getElementById('list');
list.innerHTML = '';
Object.keys(data || {}).sort().forEach((k) => { // push keys sort chronologically
const li = document.createElement('li');
li.textContent = data[k].text; // textContent, never innerHTML, for user data
list.appendChild(li);
});
});
document.getElementById('send').onclick = () => db.push('chats/room1/messages', { text: 'hi', at: Date.now() });
// The browser reconnects by itself when the network comes back (it listens for the "online" event).
</script>API at a glance
| Operation | Call |
|---|---|
| Connect | await db.connect() |
| User ID (optional) | new ZabRealtime(url, { accessKey, userId }) · db.userId · db.setUserId(id) |
| Read once | await db.get(path) |
| Replace | await db.set(path, value) |
| Merge | await db.update(path, { key: value }) |
| Push | const key = await db.push(path, value) |
| Delete | await db.remove(path) |
| Live listener | const off = db.onValue(path, cb) |
| Connection state | db.state, db.lastError, db.on("state", cb) |
| Disconnect | db.disconnect() / db.destroy() |
User ID
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.
const db = new ZabRealtime(url, { accessKey, userId: 'alice@example.com' });
console.log(db.userId); // alice@example.com (or the generated id)
// the user signs in later: re-identify the live connection, listeners are kept
db.setUserId('bob@example.com');Refs
A ZabRef points at a location and carries the same calls, Firebase style.
const room = db.ref('chats/room1');
await room.child('messages').push({ text: 'hi' });
room.onValue((data) => render(data));
console.log(room.key, room.parent.path); // "room1", "chats"Connection state and errors
The SDK reconnects by itself. When the server refuses the key it stops: a wrong, revoked or deleted key ends in rejected (and connect() throws unauthorized); a disabled key, suspended app, blocked IP or full connection limit is retried every 60 s.
db.on('state', (state, reason) => console.log(state, reason)); // disconnected | connecting | connected | rejected
try {
await db.connect();
} catch (e) {
if (e.code === 'unauthorized') showLogin(); // wrong / revoked key
else console.warn(e.code, e.message); // rejected | timeout | disconnected | invalid | server
}
db.useAccessKey('zk_NEW_KEY'); // swap keys without losing listenersNode.js 18 / 20
Pass the WebSocket class from the ws package.
import WebSocket from 'ws';
const db = new ZabRealtime(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 a database delivers changes from outside React. The hooks bridge the two: useZabValue and useZabList subscribe when a component mounts, unsubscribe when it unmounts, and re-render on every change. You never write subscribe/unsubscribe code or worry about leaks, and one provider shares a single connection across the whole app.
Requirements
- React 18+
- Depends on zab-realtime (the JavaScript SDK)
- Works with Vite, CRA, Remix, Expo web
Install
npm (from the SDK folder)
npm install ./sdk/react/zab-realtime-react ./sdk/web/zab-realtime-jsQuick start
import { ZabProvider, useZabList, useZabRef, useZabState } from 'zab-realtime-react';
export default function Root() {
return (
<ZabProvider url="https://rtdb.example.com" accessKey="zk_YOUR_ACCESS_KEY">
<Chat room="room1" />
</ZabProvider>
);
}
function Chat({ room }) {
const { items, loading } = useZabList('chats/' + room + '/messages'); // live, oldest first
const messages = useZabRef('chats/' + room + '/messages');
const { state } = useZabState();
if (loading) return <p>Loading…</p>;
return (
<>
<small>{state}</small>
<ul>{items.map(({ key, value }) => <li key={key}>{value.text}</li>)}</ul>
<button onClick={() => messages.push({ text: 'hi' })}>Send</button>
</>
);
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
src/main.jsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { ZabProvider } from 'zab-realtime-react';
import App from './App';
createRoot(document.getElementById('root')).render(
<React.StrictMode>
{/* ONE provider = ONE connection for the whole app. It connects on mount and disconnects on unmount. */}
<ZabProvider url={import.meta.env.VITE_ZAB_URL} accessKey={import.meta.env.VITE_ZAB_ACCESS_KEY} userId={currentUser?.id}>
<App />
</ZabProvider>
</React.StrictMode>,
);src/App.jsx
import { useState } from 'react';
import { useZabState, useZabList, useZabValue, useZabRef } from 'zab-realtime-react';
function ConnectionBanner() {
const { state, lastError } = useZabState(); // disconnected | connecting | connected | rejected
if (state === 'connected') return null;
return (
<div role="status" style={{ background: '#fde8e8', padding: 8 }}>
{state === 'rejected' ? 'Access refused: ' + lastError : 'You are offline. Reconnecting automatically…'}
</div>
);
}
function Chat({ room }) {
const path = 'chats/' + room + '/messages';
const { items, loading } = useZabList(path); // live, oldest first; re-subscribes if room changes
const { data: title } = useZabValue('chats/' + room + '/title');
const messages = useZabRef(path); // set / update / push / get / remove / child
const [text, setText] = useState('');
const send = async (e) => {
e.preventDefault();
if (!text.trim()) return;
await messages.push({ text, at: Date.now() }); // waits for the connection if you are offline
setText('');
};
if (loading) return <p>Loading…</p>;
return (
<section>
<h2>{title ?? room}</h2>
<ul>{items.map(({ key, value }) => <li key={key}>{value.text}</li>)}</ul>
<form onSubmit={send}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="Message" />
<button>Send</button>
</form>
</section>
);
}
export default function App() {
return (<><ConnectionBanner /><Chat room="room1" /></>);
}.env
VITE_ZAB_URL=https://rtdb.example.com
VITE_ZAB_ACCESS_KEY=zk_YOUR_BROWSER_KEY # visible to anyone who opens your site: use a dedicated, revocable keyAPI at a glance
| Operation | Call |
|---|---|
| Connect | <ZabProvider url accessKey> (connects on mount) |
| User ID (optional) | <ZabProvider userId={user.id} …> · useZab().userId |
| Read once | await useZabRef(path).get() |
| Replace | useZabRef(path).set(value) |
| Merge | useZabRef(path).update({ key: value }) |
| Push | useZabRef(path).push(value) |
| Delete | useZabRef(path).remove() |
| Live listener | const { data, loading } = useZabValue(path) |
| Connection state | const { state, isConnected, lastError } = useZabState() |
| Disconnect | unmounting <ZabProvider> disconnects |
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 listeners. Omit it for a generated id.
<ZabProvider url={url} accessKey={key} userId={user?.id}>
<App />
</ZabProvider>Hooks
| Name | Description |
|---|---|
<ZabProvider url accessKey options? client?> | One connection for the tree below. Opens on mount, closes on unmount. |
useZab() | The underlying ZabRealtime client. |
useZabState() | { state, isConnected, lastError } |
useZabValue(path) | { data, loading }, live. A null path switches it off. |
useZabList(path, { newestFirst }) | { items: [{ key, value }], loading }, children sorted by key (push keys sort by time). |
useZabRef(path) | A stable ref: set, update, push, get, remove, child. |
A single value
Changing path resubscribes; the previous path's data is never shown for the new one.
function Profile({ uid }) {
const { data: user, loading } = useZabValue('users/' + uid);
if (loading) return <Spinner />;
return <h1>{user?.name ?? 'Unknown'}</h1>;
}Connection banner
function Banner() {
const { state, lastError } = useZabState();
if (state === 'connected') return null;
return <div role="status">{state === 'rejected' ? 'Access refused: ' + lastError : 'Reconnecting…'}</div>;
}Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
NNext.js SDK
App Router and Pages Router: a server-side REST client plus live hooks for Client Components.
Why this SDK? Next.js runs code in two places. Server code (Server Components, Route Handlers, Server Actions) is short-lived and keeps secrets, so it uses stateless REST with a server-only key. Browser code (Client Components) wants live updates, so it uses the WebSocket hooks with a separate, revocable browser key. This SDK gives each side the right tool and keeps the two keys apart.
Requirements
- Next.js 13.4+ (App Router or Pages Router)
- React 18+
/serverentry: Route Handlers, Server Components, Server Actions, middleware/cliententry: Client Components
Install
npm (from the SDK folder)
npm install ./sdk/nextjs/zab-realtime-next ./sdk/react/zab-realtime-react ./sdk/web/zab-realtime-js.env.local
ZAB_URL=https://rtdb.example.com
ZAB_ACCESS_KEY=zk_SERVER_KEY # server only: never reaches the browser
NEXT_PUBLIC_ZAB_URL=https://rtdb.example.com
NEXT_PUBLIC_ZAB_ACCESS_KEY=zk_BROWSER_KEY # visible in the browser: use a separate, revocable keynext.config.js (when installed from a local folder)
module.exports = { transpilePackages: ['zab-realtime-next', 'zab-realtime-react', 'zab-realtime'] };Quick start
// app/users/[id]/page.jsx : a Server Component reads at request time
import { createZabServer } from 'zab-realtime-next/server';
const zab = createZabServer(); // reads ZAB_URL and ZAB_ACCESS_KEY
export const dynamic = 'force-dynamic';
export default async function User({ params }) {
const user = await zab.get('users/' + params.id);
return <h1>{user?.name ?? 'Unknown user'}</h1>;
}
// app/chat/room.jsx : a Client Component is live
'use client';
import { useZabList, useZabRef } from 'zab-realtime-next/client';
export default function Room() {
const { items } = useZabList('chats/room1/messages');
const messages = useZabRef('chats/room1/messages');
return (
<>
<ul>{items.map(({ key, value }) => <li key={key}>{value.text}</li>)}</ul>
<button onClick={() => messages.push({ text: 'hi' })}>Send</button>
</>
);
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
app/providers.jsx
'use client';
// Reads NEXT_PUBLIC_ZAB_URL and NEXT_PUBLIC_ZAB_ACCESS_KEY. One connection for every Client Component below it.
export { ZabProvider as default } from 'zab-realtime-next/client';app/layout.jsx
import Providers from './providers';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body><Providers>{children}</Providers></body>
</html>
);
}app/chat/page.jsx (Server Component: first paint from the server)
import { createZabServer } from 'zab-realtime-next/server';
import Live from './live';
const zab = createZabServer(); // ZAB_URL + ZAB_ACCESS_KEY (server-only variables)
export const dynamic = 'force-dynamic'; // never cache database reads
export default async function ChatPage() {
const initial = await zab.get('chats/room1/messages'); // REST, stateless, no connection to manage
return <Live initial={initial} />;
}app/chat/live.jsx (Client Component: live after that)
'use client';
import { useZabList, useZabRef, useZabState } from 'zab-realtime-next/client';
export default function Live({ initial }) {
const { items, loading } = useZabList('chats/room1/messages');
const messages = useZabRef('chats/room1/messages');
const { state } = useZabState();
// Until the live data arrives, show what the server rendered.
const rows = loading
? Object.keys(initial || {}).sort().map((key) => ({ key, value: initial[key] }))
: items;
return (
<>
<small>{state}</small>
<ul>{rows.map(({ key, value }) => <li key={key}>{value.text}</li>)}</ul>
<button onClick={() => messages.push({ text: 'hi', at: Date.now() })}>Send</button>
</>
);
}app/api/send/route.js (Route Handler: write from the server)
import { NextResponse } from 'next/server';
import { createZabServer, ZabServerError } from 'zab-realtime-next/server';
const zab = createZabServer();
export async function POST(req) {
try {
const { text } = await req.json();
const id = await zab.push('chats/room1/messages', { text: String(text).slice(0, 500), at: Date.now() });
return NextResponse.json({ id });
} catch (e) {
const status = e instanceof ZabServerError && e.status ? e.status : 500;
return NextResponse.json({ error: e.message }, { status });
}
}.env.local
ZAB_URL=https://rtdb.example.com
ZAB_ACCESS_KEY=zk_SERVER_KEY # server only
NEXT_PUBLIC_ZAB_URL=https://rtdb.example.com
NEXT_PUBLIC_ZAB_ACCESS_KEY=zk_BROWSER_KEY # public: separate, revocable keyAPI at a glance
| Operation | Call |
|---|---|
| Connect | <ZabProvider/> (client) · createZabServer() (server) |
| User ID (optional) | createZabServer({ userId }) · zab.as(userId) · <ZabProvider userId> |
| Read once | await zab.get(path) · useZabRef(path).get() |
| Replace | await zab.set(path, value) |
| Merge | await zab.update(path, { key: value }) |
| Push | const key = await zab.push(path, value) |
| Delete | await zab.remove(path) |
| Live listener | useZabValue(path) · useZabList(path) (client only) |
| Connection state | useZabState() (client only) |
| Disconnect | server: nothing to close (stateless REST) |
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 user. In Client Components pass userId to the provider.
const zab = createZabServer();
export async function POST(req) {
const session = await getSession(req); // your own auth
await zab.as(session.user.id).push('orders', await req.json());
return Response.json({ ok: true });
}Provider (App Router)
// app/providers.jsx
'use client';
export { ZabProvider as default } from 'zab-realtime-next/client'; // reads the NEXT_PUBLIC_ env vars
// app/layout.jsx
import Providers from './providers';
export default function Layout({ children }) {
return <html><body><Providers>{children}</Providers></body></html>;
}Route Handler / Server Action
// app/api/orders/route.js
import { NextResponse } from 'next/server';
import { createZabServer } from 'zab-realtime-next/server';
const zab = createZabServer();
export async function POST(req) {
const order = await req.json();
const id = await zab.push('orders', { ...order, createdAt: Date.now() });
return NextResponse.json({ id });
}Server errors
Server calls throw ZabServerError with an HTTP status: 401 wrong or revoked key, 403 suspended or blocked, 429 rate limited, 507 storage quota exceeded, 0 server unreachable.
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, pauses screen subscriptions while another screen covers them, and removes them when a screen closes, so a chat screen stops receiving data the moment the user leaves it. It also reconnects when the app returns to the foreground after the OS froze its timers.
Requirements
- Flutter 3.x / Dart 3
- Android, iOS, web, Windows, macOS, Linux
- Uses socket_io_client
Install
pubspec.yaml
dependencies:
zab_realtime:
path: ../ZabRealtimeKit/sdk/flutter/zab_realtime # or your git / pub.dev sourceQuick start
import 'package:zab_realtime/zab_realtime.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
ZabRealtimeIO.init('https://rtdb.example.com', accessKey: 'zk_YOUR_ACCESS_KEY').open(); // once
runApp(const MyApp());
}
// any screen
final db = ZabRealtimeIO.instance;
await db.set('users/u1', {'name': 'Alex'}); // replace
await db.update('users/u1', {'city': 'Austin'}); // merge keys
final key = await db.push('orders', {'item': 'tea'}); // auto chronological key
final user = await db.fetch('users/u1'); // read once
await db.delete('users/u1');
class _ChatState extends State<Chat> with ZabSubscriptions { // auto-unsubscribes when the screen is left
@override
void initState() {
super.initState();
zabSubscribe('chats/room1', (data) => setState(() => messages = data));
}
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
lib/main.dart
import 'package:flutter/material.dart';
import 'package:zab_realtime/zab_realtime.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// ONE connection for the whole app. Android emulator + local server: http://10.0.2.2:8080
ZabRealtimeIO.init('https://rtdb.example.com', accessKey: 'zk_YOUR_ACCESS_KEY', userId: 'alice@example.com').open(); // userId optional
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
navigatorObservers: [zabRouteObserver], // lets screens pause their subscriptions while covered
home: const ChatScreen(),
);
}
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> with ZabSubscriptions {
Map<String, dynamic> messages = {};
final controller = TextEditingController();
@override
void initState() {
super.initState();
// Removed automatically when this screen is left; restored after every reconnect.
zabSubscribe('chats/room1/messages', (data) {
setState(() => messages = data is Map ? Map<String, dynamic>.from(data) : {});
});
}
Future<void> send() async {
final text = controller.text.trim();
if (text.isEmpty) return;
try {
await db.push('chats/room1/messages', {'text': text, 'at': DateTime.now().millisecondsSinceEpoch});
controller.clear();
} on ZabIOException catch (e) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Not sent: ' + (e.message ?? 'unknown error'))));
}
}
@override
Widget build(BuildContext context) {
final keys = messages.keys.toList()..sort(); // push keys sort chronologically
return Scaffold(
appBar: AppBar(
title: const Text('Room 1'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(24),
child: ValueListenableBuilder<ZabConnectionState>(
valueListenable: db.state,
builder: (_, state, __) => Text(state == ZabConnectionState.rejected ? 'Refused: ' + (db.lastError.value ?? '') : state.name),
),
),
),
body: Column(children: [
Expanded(child: ListView(children: [for (final k in keys) ListTile(title: Text(messages[k]['text'].toString()))])),
Row(children: [
Expanded(child: TextField(controller: controller)),
IconButton(onPressed: send, icon: const Icon(Icons.send)),
]),
]),
);
}
}API at a glance
| Operation | Call |
|---|---|
| Connect | ZabRealtimeIO.init(url, accessKey: key).open() |
| User ID (optional) | ZabRealtimeIO.init(url, accessKey: key, userId: id) · db.userId · db.setUserId(id) |
| Read once | await db.fetch(path) |
| Replace | await db.set(path, value) |
| Merge | await db.update(path, {key: value}) |
| Push | final key = await db.push(path, value) |
| Delete | await db.delete(path) |
| Live listener | db.subscribe(path, cb) · db.onValue(path) (Stream) · ZabSubscriptions mixin |
| Connection state | db.state (ValueNotifier), db.lastError |
| Disconnect | db.close() · db.destroy() |
User ID
Pass any id for the end user. Without one a random id is generated. setUserId re-identifies the live connection after sign-in; subscriptions are kept.
ZabRealtimeIO.init(url, accessKey: key, userId: 'alice@example.com').open();
// after the user signs in
ZabRealtimeIO.instance.setUserId(auth.currentUser!.uid);Connection status
ValueListenableBuilder<ZabConnectionState>(
valueListenable: ZabRealtimeIO.instance.state,
builder: (context, state, _) => Text(state.name), // disconnected | connecting | connected | rejected
);
ZabRealtimeIO.instance.lastError.value; // why the server said no, if it didStreamBuilder
Create the stream once (in initState), not inside build().
late final Stream<dynamic> room = ZabRealtimeIO.instance.onValue('chats/room1');
// StreamBuilder(stream: room, builder: (context, snap) => ...)Android emulator
Use http://10.0.2.2:8080 for a server on your machine. Pass https:// (not wss://): Socket.IO upgrades to WebSocket by itself.
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 live data as Flow, so it fits ViewModels and Compose directly, uses coroutines instead of callbacks, and reconnects as soon as Android reports a network again.
Requirements
- Android 5.0+ (API 21), compileSdk 34
- Kotlin 1.9+, Java 8 target
- OkHttp 4 and kotlinx-coroutines (pulled in automatically)
Install
settings.gradle.kts
include(":zab-realtime")
project(":zab-realtime").projectDir = file("path/to/ZabRealtimeKit/sdk/android/zab-realtime")app/build.gradle.kts
dependencies { implementation(project(":zab-realtime")) }
// or, after ./gradlew :zab-realtime:publishToMavenLocal:
// implementation("com.zabsys:zab-realtime:1.0.0")Local server on the emulator
<!-- http://10.0.2.2:8080 needs cleartext traffic; use https in production -->
<application android:usesCleartextTraffic="true" ... />Quick start
import com.zabsys.zabrealtime.*
val db = ZabRealtime("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY") // keep ONE instance for the whole app
lifecycleScope.launch {
try {
db.connect() // suspends; throws ZabException if refused
} catch (e: ZabException) {
Log.w("zab", e.code.name + ": " + e.message) // UNAUTHORIZED = wrong/revoked key
return@launch
}
db.set("users/u1", mapOf("name" to "Alex")) // replace
db.update("users/u1", mapOf("city" to "Austin")) // merge keys
val key = db.push("orders", mapOf("item" to "tea")) // auto chronological key
val user = db.get("users/u1") as? JSONObject // read once (null if empty)
db.remove("orders/$key")
db.observe("chats/room1").collect { value -> // live Flow; cancelling unsubscribes
// JSONObject / JSONArray / String / Number / Boolean / null
}
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
App.kt
import android.app.Application
import com.zabsys.zabrealtime.*
class App : Application() {
// ONE client for the whole app process.
lateinit var zab: ZabRealtime
private var networkWatcher: AutoCloseable? = null
override fun onCreate() {
super.onCreate()
zab = ZabRealtime("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY", ZabOptions(userId = "alice@example.com")) // userId optional: names this user in the admin log
// Reconnect the moment Android reports a network again (Wi-Fi back, tunnel exit, airplane mode off).
networkWatcher = zab.autoReconnectOnNetwork(this)
}
}ChatViewModel.kt
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zabsys.zabrealtime.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import org.json.JSONObject
class ChatViewModel(private val zab: ZabRealtime) : ViewModel() {
val connection: StateFlow<ZabState> = zab.state // DISCONNECTED, CONNECTING, CONNECTED, REJECTED
val refusedBecause: StateFlow<String?> = zab.lastError
val messages: StateFlow<List<String>> = zab.observe("chats/room1/messages") // live; restored after reconnects
.map { v -> (v as? JSONObject)?.let { o -> o.keys().asSequence().sorted().map { o.getJSONObject(it).getString("text") }.toList() } ?: emptyList() }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
init {
viewModelScope.launch {
try {
zab.connect() // suspends until connected
} catch (e: ZabException) {
// UNAUTHORIZED = wrong or revoked key: ask the user to sign in again. Others are retried automatically.
}
}
}
fun send(text: String) = viewModelScope.launch {
try { zab.push("chats/room1/messages", mapOf("text" to text, "at" to System.currentTimeMillis())) }
catch (e: ZabException) { /* show e.message */ }
}
override fun onCleared() { /* keep the app-wide client open; call zab.disconnect() on logout */ }
}MainActivity.kt (Compose)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val vm = ChatViewModel((application as App).zab)
setContent {
val state by vm.connection.collectAsState()
val messages by vm.messages.collectAsState()
Column {
if (state != ZabState.CONNECTED) Text("Offline: reconnecting…")
LazyColumn { items(messages) { Text(it) } }
Button(onClick = { vm.send("hi") }) { Text("Send") }
}
}
}
}AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- INTERNET and ACCESS_NETWORK_STATE come from the library's manifest -->
<application android:name=".App" ...>
<activity android:name=".MainActivity" android:exported="true">...</activity>
</application>
</manifest>API at a glance
| Operation | Call |
|---|---|
| Connect | db.connect() (suspend) |
| User ID (optional) | ZabOptions(userId = id) · db.userId · db.setUserId(id) |
| Read once | db.get(path) (suspend) |
| Replace | db.set(path, value) (suspend) |
| Merge | db.update(path, mapOf("key" to value)) |
| Push | val key = db.push(path, value) |
| Delete | db.remove(path) |
| Live listener | db.observe(path): Flow · db.onValue(path) { }: ZabSubscription |
| Connection state | db.state: StateFlow<ZabState>, db.lastError: StateFlow<String?> |
| Disconnect | db.disconnect() · db.destroy() |
User ID
Pass any id for the end user in ZabOptions. Without one a random id is generated. setUserId re-identifies the connection after sign-in.
val db = ZabRealtime(url, key, ZabOptions(userId = "alice@example.com"))
Log.d("zab", db.userId)
// after the user signs in
viewModelScope.launch { db.setUserId(auth.uid) }Compose
@Composable
fun Room(db: ZabRealtime) {
val value by remember { db.observe("chats/room1") }.collectAsState(initial = null)
val state by db.state.collectAsState()
Text(state.name)
Text(value?.toString() ?: "empty")
}Values
Values are org.json types. set, update and push accept Map, List, String, numbers, Boolean, JSONObject, JSONArray or null.
Build check
This module was written without an Android toolchain in the repository environment. Run ./gradlew :zab-realtime:assembleRelease :zab-realtime:testDebugUnitTest 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 realtime channel. This package is built on URLSessionWebSocketTask and Swift concurrency: async/await for calls, AsyncStream for live values (they drop straight into SwiftUI), and automatic reconnection when the system reports a usable network.
Requirements
- iOS 15+, macOS 12+, tvOS 15+, watchOS 8+
- Swift 5.7+ / Xcode 14+
- No third-party dependencies
Install
Xcode
File → Add Package Dependencies… → Add Local… → choose sdk/iosPackage.swift
dependencies: [ .package(path: "../ZabRealtimeKit/sdk/ios") ], // or your Git URL once published
targets: [ .target(name: "MyApp", dependencies: [.product(name: "ZabRealtime", package: "ios")]) ]Quick start
import ZabRealtime
let db = try ZabRealtime(url: "https://rtdb.example.com", accessKey: "zk_YOUR_ACCESS_KEY") // ONE instance for the app
do {
try await db.connect() // throws ZabError if the key is refused
} catch let e as ZabError {
print(e.code, e.message) // .unauthorized = wrong/revoked key
}
try await db.set("users/u1", ["name": "Alex"]) // replace
try await db.update("users/u1", ["city": "Austin"]) // merge keys
let key = try await db.push("orders", ["item": "tea"]) // auto chronological key
let user = try await db.get("users/u1") as? [String: Any] // read once (nil if empty)
try await db.remove("orders/\(key)")
for await value in db.values("chats/room1") { // live AsyncStream; leaving the loop unsubscribes
print(value as Any)
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
MyApp.swift
import SwiftUI
import ZabRealtime
@main
struct MyApp: App {
// ONE client for the whole app.
@StateObject private var chat = ChatModel()
var body: some Scene {
WindowGroup { ChatView().environmentObject(chat) }
}
}ChatModel.swift
import Foundation
import ZabRealtime
@MainActor
final class ChatModel: ObservableObject {
@Published var messages: [(key: String, text: String)] = []
@Published var state: ZabState = .disconnected
@Published var problem: String?
private let db: ZabRealtime
private var tasks: [Task<Void, Never>] = []
init() {
// try! is acceptable here: it only throws for an empty URL or key, which is a programming error.
var options = ZabOptions()
options.userId = "alice@example.com" // optional: names this user in the admin log (omit: generated)
db = try! ZabRealtime(url: "https://rtdb.example.com", accessKey: "zk_YOUR_ACCESS_KEY", options: options)
start()
}
private func start() {
// 1. Connection state (reconnects automatically; also when the system reports a network again).
tasks.append(Task { [weak self] in
guard let self else { return }
for await s in self.db.stateStream() { self.state = s; self.problem = self.db.lastError }
})
// 2. Connect.
tasks.append(Task { [weak self] in
do { try await self?.db.connect() }
catch let e as ZabError where e.code == .unauthorized { self?.problem = "Wrong or revoked key" }
catch { /* other errors are retried automatically */ }
})
// 3. Live values: restored after every reconnect.
tasks.append(Task { [weak self] in
guard let self else { return }
for await value in self.db.values("chats/room1/messages") {
let dict = value as? [String: Any] ?? [:]
self.messages = dict.keys.sorted().map { ($0, (dict[$0] as? [String: Any])?["text"] as? String ?? "") }
}
})
}
func send(_ text: String) {
Task {
do { _ = try await db.push("chats/room1/messages", ["text": text, "at": Int(Date().timeIntervalSince1970 * 1000)]) }
catch let e as ZabError { problem = e.message }
}
}
deinit { tasks.forEach { $0.cancel() }; db.disconnect() }
}ChatView.swift
import SwiftUI
import ZabRealtime
struct ChatView: View {
@EnvironmentObject var chat: ChatModel
@State private var text = ""
var body: some View {
VStack {
if chat.state != .connected { Text(chat.problem ?? "Offline: reconnecting…").font(.footnote) }
List(chat.messages, id: \.key) { Text($0.text) }
HStack {
TextField("Message", text: $text)
Button("Send") { chat.send(text); text = "" }
}
}
.padding()
}
}API at a glance
| Operation | Call |
|---|---|
| Connect | try await db.connect() |
| User ID (optional) | var o = ZabOptions(); o.userId = id · db.userId · try await db.setUserId(id) |
| Read once | try await db.get(path) |
| Replace | try await db.set(path, value) |
| Merge | try await db.update(path, ["key": value]) |
| Push | let key = try await db.push(path, value) |
| Delete | try await db.remove(path) |
| Live listener | db.values(path): AsyncStream · try db.onValue(path) { } |
| Connection state | db.state, db.lastError, db.onStateChange { }, db.stateStream() |
| Disconnect | db.disconnect() |
User ID
Set userId in ZabOptions. Without one a random id is generated. setUserId re-identifies the connection after sign-in.
var options = ZabOptions()
options.userId = "alice@example.com"
let db = try ZabRealtime(url: url, accessKey: key, options: options)
print(db.userId)
// after the user signs in
try await db.setUserId(user.id)Codable models
struct User: Codable { var name: String; var city: String? }
try await db.set("users/u1", encoding: User(name: "Alex", city: "Austin"))
let user = try await db.get("users/u1", as: User.self)
let id = try await db.push("msgs", encoding: Message(text: "hi"))SwiftUI
@MainActor final class Room: ObservableObject {
@Published var messages: [String: Any] = [:]
private var task: Task<Void, Never>?
func start(_ db: ZabRealtime) {
task = Task { for await v in db.values("chats/room1") { messages = (v as? [String: Any]) ?? [:] } }
}
deinit { task?.cancel() }
}Build check
This package was written without a Swift toolchain in the repository environment. Run swift build and swift test on a Mac 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 streams, IAsyncDisposable for clean shutdown, and it fits dependency injection as a singleton.
Requirements
- .NET 8+ or .NET Standard 2.1
- Unity 2021.2+, MAUI, Xamarin
- System.Text.Json (no other dependencies)
Install
Project reference
dotnet add reference ./sdk/dotnet/ZabRealtime/ZabRealtime.csproj
# or: dotnet pack ./sdk/dotnet/ZabRealtime -c Release then publish ZabSys.Realtime to your NuGet feedQuick start
using System.Text.Json.Nodes;
using ZabSys.Realtime;
await using var db = new ZabRealtime("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY"); // ONE instance per app
try { await db.ConnectAsync(); } // throws ZabException if the key is refused
catch (ZabException e) { Console.WriteLine($"{e.Code}: {e.Message}"); return; }
await db.SetAsync("users/u1", new { name = "Alex" }); // replace
await db.UpdateAsync("users/u1", new { city = "Austin" }); // merge keys
string key = await db.PushAsync("orders", new { item = "tea" }); // auto chronological key
JsonNode? user = await db.GetAsync("users/u1"); // read once (null if empty)
await db.RemoveAsync($"orders/{key}");
using var sub = db.OnValue("chats/room1", v => Console.WriteLine(v)); // live; dispose to stop
await foreach (var v in db.WatchAsync("users/u1", cts.Token)) { } // or an async streamComplete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
Program.cs (console or worker service)
using System.Text.Json.Nodes;
using ZabSys.Realtime;
var url = Environment.GetEnvironmentVariable("ZAB_URL")!; // https://rtdb.example.com
var key = Environment.GetEnvironmentVariable("ZAB_ACCESS_KEY")!; // zk_...
await using var db = new ZabRealtime(url, key, new ZabOptions { RequestTimeout = TimeSpan.FromSeconds(15), UserId = "alice@example.com" }); // UserId optional
// 1. Watch the connection (raised on a background thread).
db.StateChanged += (state, reason) => Console.WriteLine($"[zab] {state} {reason}");
// 2. Connect. Throws only when the server refuses the key; a network that is down right now is retried in the background.
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
await db.ConnectAsync(cts.Token);
}
catch (ZabException e) when (e.Code == ZabErrorCode.Unauthorized)
{
Console.Error.WriteLine("Wrong or revoked key");
return 1;
}
catch (OperationCanceledException)
{
Console.WriteLine("Not connected yet: the SDK keeps retrying and reconnects when the network is back");
}
// 3. Listen: the callback gets the current value, every change, and the latest value again after a reconnect.
using var sub = db.OnValue("chats/room1/messages", v => Console.WriteLine("messages: " + v?.ToJsonString()));
// 4. Write: calls made while offline wait for the connection.
string id = await db.PushAsync("chats/room1/messages", new { text = "hello", at = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
await db.UpdateAsync("users/u1", new { lastSeen = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
JsonNode? user = await db.GetAsync("users/u1");
Console.WriteLine($"pushed {id}; user = {user}");
Console.ReadLine(); // keep running; Dispose (await using) disconnects cleanly
return 0;ASP.NET Core: register once
// Program.cs
builder.Services.AddSingleton(sp => new ZabRealtime(cfg["Zab:Url"]!, cfg["Zab:AccessKey"]!));
builder.Services.AddHostedService<ZabConnectService>();
// ZabConnectService.cs
public sealed class ZabConnectService(ZabRealtime db, ILogger<ZabConnectService> log) : IHostedService
{
public Task StartAsync(CancellationToken ct)
{
db.StateChanged += (s, why) => log.LogInformation("ZabRealtime {State} {Why}", s, why);
_ = db.ConnectAsync(CancellationToken.None).ContinueWith(
t => log.LogError(t.Exception, "ZabRealtime refused the key"), TaskContinuationOptions.OnlyOnFaulted);
return Task.CompletedTask; // do not block startup on the network
}
public Task StopAsync(CancellationToken ct) => db.DisconnectAsync();
}API at a glance
| Operation | Call |
|---|---|
| Connect | await db.ConnectAsync() |
| User ID (optional) | new ZabOptions { UserId = id } · db.UserId · await db.SetUserIdAsync(id) |
| Read once | await db.GetAsync(path) · GetAsync<T>(path) |
| Replace | await db.SetAsync(path, value) |
| Merge | await db.UpdateAsync(path, new { key = value }) |
| Push | string key = await db.PushAsync(path, value) |
| Delete | await db.RemoveAsync(path) |
| Live listener | db.OnValue(path, cb): IDisposable · db.WatchAsync(path): IAsyncEnumerable |
| Connection state | db.State, db.LastError, db.StateChanged event |
| Disconnect | await db.DisconnectAsync() · await using |
User ID
Set UserId in ZabOptions. Without one a random id is generated. SetUserIdAsync re-identifies the connection after sign-in.
var db = new ZabRealtime(url, key, new ZabOptions { UserId = "alice@example.com" });
Console.WriteLine(db.UserId);
// after the user signs in
await db.SetUserIdAsync(user.Id);ASP.NET Core
builder.Services.AddSingleton(sp => new ZabRealtime(cfg["Zab:Url"]!, cfg["Zab:AccessKey"]!));
builder.Services.AddHostedService<ZabConnectService>(); // ConnectAsync in StartAsync, DisconnectAsync in StopAsyncTyped reads
Property names are camelCase on the wire.
record User(string Name, string? City);
User? u = await db.GetAsync<User>("users/u1");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, data pipelines and FastAPI services that need live updates. Use the blocking REST client for scripts, cron jobs and Django or Flask views, where you only need to read or write a value and move on.
Requirements
- Python 3.8+
ZabRealtime(asyncio) needswebsocketsZabRestneeds nothing
Install
pip (from the SDK folder)
pip install ./sdk/pythonQuick start
import asyncio
from zab_realtime import ZabRealtime, ZabError
async def main():
db = ZabRealtime("https://rtdb.example.com", access_key="zk_YOUR_ACCESS_KEY")
try:
await db.connect() # raises ZabError if the key is refused
except ZabError as e:
print("refused:", e.code, e) # 'unauthorized' = wrong/revoked key
return
await db.set("users/u1", {"name": "Alex"}) # replace
await db.update("users/u1", {"city": "Austin"}) # merge keys
key = await db.push("orders", {"item": "tea"}) # auto chronological key
print(await db.get("users/u1")) # read once (None if empty)
off = db.on_value("chats/room1", lambda v: print("room1:", v)) # live; sync or async callback
async for value in db.watch("users/u1"): # or an async iterator
print(value)
break
off()
await db.disconnect()
asyncio.run(main())Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
app.py
import asyncio
import os
import time
from zab_realtime import ZabRealtime, ZabError
URL = os.environ["ZAB_URL"] # https://rtdb.example.com
KEY = os.environ["ZAB_ACCESS_KEY"] # zk_...
async def main() -> None:
db = ZabRealtime(URL, access_key=KEY, user_id="alice@example.com") # user_id optional: names this user in the admin log
# 1. Watch the connection (sync or async callbacks).
db.on_state(lambda state, reason: print("[zab]", state, reason or ""))
# 2. Connect. Raises ZabError only when the server refuses the key. If the network is down right now it keeps
# retrying in the background, so give it a deadline.
try:
await asyncio.wait_for(db.connect(), timeout=10)
except ZabError as e:
if e.code == "unauthorized":
raise SystemExit("Wrong or revoked key")
print("refused for now:", e.code, e) # 'rejected': retried automatically every 60 s
except asyncio.TimeoutError:
print("Not connected yet: the SDK keeps retrying and reconnects when the network is back")
# 3. Listen: current value now, every change, and again after a reconnect.
off = db.on_value("chats/room1/messages", lambda v: print("messages:", v))
# 4. Write: calls made while offline wait for the connection.
key = await db.push("chats/room1/messages", {"text": "hello", "at": int(time.time() * 1000)})
await db.update("users/u1", {"lastSeen": int(time.time() * 1000)})
print("pushed", key, "| user:", await db.get("users/u1"))
try:
await asyncio.Event().wait() # run until Ctrl+C
finally:
off()
await db.disconnect() # 5. clean shutdown
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
passREST in a web handler (FastAPI / Flask / Django)
import os
from zab_realtime import ZabRest, ZabError
zab = ZabRest(os.environ["ZAB_URL"], access_key=os.environ["ZAB_ACCESS_KEY"], timeout=10)
def create_order(item: str) -> str:
try:
return zab.push("orders", {"item": item})
except ZabError as e: # e.code, e.status
raise RuntimeError("database unavailable: " + str(e)) from eAPI at a glance
| Operation | Call |
|---|---|
| Connect | await db.connect() |
| User ID (optional) | ZabRealtime(url, key, user_id=id) · db.user_id · await db.set_user_id(id) · ZabRest(..., user_id=id).as_user(id) |
| Read once | await db.get(path) |
| Replace | await db.set(path, value) |
| Merge | await db.update(path, {"key": value}) |
| Push | key = await db.push(path, value) |
| Delete | await db.remove(path) |
| Live listener | off = db.on_value(path, cb) · async for v in db.watch(path) |
| Connection state | db.state, db.last_error, db.on_state(cb) |
| Disconnect | await db.disconnect() · async with |
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: use as_user() to act for the end user behind each request.
db = ZabRealtime(url, access_key=key, user_id="alice@example.com")
print(db.user_id)
await db.set_user_id("bob@example.com") # re-identify the live connection
rest = ZabRest(url, access_key=key)
rest.as_user(request.user.id).push("orders", {"item": "tea"}) # logged under that userBlocking REST client
For scripts, cron jobs and Django / Flask / FastAPI handlers. No dependencies.
from zab_realtime import ZabRest
db = ZabRest("https://rtdb.example.com", access_key="zk_YOUR_ACCESS_KEY")
db.set("users/u1", {"name": "Alex"})
db.update("users/u1", {"city": "Austin"})
key = db.push("orders", {"item": "tea"})
print(db.get("users/u1"), db.whoami()["app"]["name"])
db.remove("users/u1")Context manager
async with ZabRealtime(url, access_key=key) as db: # connects, disconnects on exit
await db.set("ping", 1)Errors
Every call raises ZabError with code (rejected, unauthorized, timeout, disconnected, invalid, server) and status (HTTP status, 0 when unreachable).
Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
GoGo SDK
A WebSocket client with listeners 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 listeners and automatic reconnection; the REST type makes stateless calls from HTTP handlers. Callbacks run on their own goroutine, so they may safely call back into the client.
Requirements
- Go 1.22+
- gorilla/websocket
Install
go get / replace
go get github.com/zabsys/zabrealtime-go
# from the SDK folder:
go mod edit -replace github.com/zabsys/zabrealtime-go=./sdk/goQuick start
package main
import (
"context"
"fmt"
"log"
zab "github.com/zabsys/zabrealtime-go"
)
func main() {
ctx := context.Background()
db, err := zab.New("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY")
if err != nil {
log.Fatal(err)
}
if err := db.Connect(ctx); err != nil { // *zab.Error: Code "unauthorized" (wrong/revoked key) or "rejected"
log.Fatal(err)
}
defer db.Close()
db.Set(ctx, "users/u1", map[string]any{"name": "Alex"}) // replace
db.Update(ctx, "users/u1", map[string]any{"city": "Austin"}) // merge keys
key, _ := db.Push(ctx, "orders", map[string]any{"item": "tea"})
var user struct{ Name, City string }
db.GetInto(ctx, "users/u1", &user) // read once into a struct
fmt.Println(key, user)
off := db.OnValue("chats/room1", func(v any) { fmt.Println("room1:", v) }) // live
defer off()
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
main.go
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"time"
zab "github.com/zabsys/zabrealtime-go"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
db, err := zab.New(os.Getenv("ZAB_URL"), os.Getenv("ZAB_ACCESS_KEY"), zab.Options{UserID: "alice@example.com"}) // UserID optional
if err != nil {
log.Fatal(err)
}
defer db.Close()
// 1. Watch the connection (callbacks run on their own goroutine, so they may call the client).
db.OnState(func(s zab.State, reason string) { log.Printf("[zab] %s %s", s, reason) })
// 2. Connect. Returns an error only when the server refuses the key; a network that is down right now keeps
// retrying in the background, so give Connect a deadline.
cctx, cancel := context.WithTimeout(ctx, 10*time.Second)
err = db.Connect(cctx)
cancel()
var ze *zab.Error
switch {
case errors.As(err, &ze) && ze.Code == zab.CodeUnauthorized:
log.Fatal("wrong or revoked key")
case err != nil:
log.Println("not connected yet, the SDK keeps retrying:", err)
}
// 3. Listen: current value now, every change, and again after a reconnect.
off := db.OnValue("chats/room1/messages", func(v any) { fmt.Println("messages:", v) })
defer off()
// 4. Write: calls made while offline wait for the connection (up to the request timeout).
key, err := db.Push(ctx, "chats/room1/messages", map[string]any{"text": "hello", "at": time.Now().UnixMilli()})
if err != nil {
log.Println("push failed:", err)
}
_ = db.Update(ctx, "users/u1", map[string]any{"lastSeen": time.Now().UnixMilli()})
var user struct{ Name, City string }
_ = db.GetInto(ctx, "users/u1", &user)
fmt.Println("pushed", key, "| user:", user)
<-ctx.Done() // run until Ctrl+C; the deferred Close disconnects cleanly
}REST in an HTTP handler
var zdb, _ = zab.NewREST(os.Getenv("ZAB_URL"), os.Getenv("ZAB_ACCESS_KEY"))
func createOrder(w http.ResponseWriter, r *http.Request) {
id, err := zdb.Push(r.Context(), "orders", map[string]any{"item": r.FormValue("item")})
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
fmt.Fprint(w, id)
}API at a glance
| Operation | Call |
|---|---|
| Connect | err := db.Connect(ctx) |
| User ID (optional) | zab.Options{UserID: id} · db.UserID() · db.SetUserID(ctx, id) · rest.As(id) |
| Read once | v, err := db.Get(ctx, path) · db.GetInto(ctx, path, &out) |
| Replace | err := db.Set(ctx, path, value) |
| Merge | err := db.Update(ctx, path, map[string]any{...}) |
| Push | key, err := db.Push(ctx, path, value) |
| Delete | err := db.Remove(ctx, path) |
| Live listener | off := db.OnValue(path, cb) · ch := db.Watch(ctx, path) |
| Connection state | db.State(), db.LastError(), db.OnState(cb) |
| Disconnect | db.Close() |
User ID
Set Options.UserID (a random id is generated when empty). A REST client has no id of its own: use As() to act for the end user behind each request.
db, _ := zab.New(url, key, zab.Options{UserID: "alice@example.com"})
fmt.Println(db.UserID())
_ = db.SetUserID(ctx, "bob@example.com") // re-identify the live connection
rest, _ := zab.NewREST(url, key)
rest.As(userID).Push(ctx, "orders", map[string]any{"item": "tea"}) // logged under that userStateless REST
For HTTP handlers and jobs: no connection to manage.
db, _ := zab.NewREST("https://rtdb.example.com", "zk_YOUR_ACCESS_KEY")
id, err := db.Push(ctx, "orders", map[string]any{"item": "tea"})Watch as a channel
for v := range db.Watch(ctx, "users/u1") { // cancel ctx to stop; the channel is then closed
fmt.Println(v)
}Errors
Every SDK reports the same six error codes: unauthorized, rejected, timeout, disconnected, invalid, server. See Errors & connection states.
PPHP SDK
A dependency-free REST client for Laravel, Symfony, WordPress and plain PHP.
Why this SDK? PHP requests start and end within a page load, so keeping a WebSocket open makes no sense there. This client does the one thing PHP needs: write and read data over REST from Laravel, Symfony, WordPress or plain scripts, while your web and mobile apps receive the changes live through the other SDKs.
Requirements
- PHP 8.0+
- ext-json
- REST only: PHP requests are short-lived, so there are no live listeners
Install
Composer
composer require zabsys/zab-realtime
# or a path repository pointing at ./sdk/phpQuick start
<?php
use ZabRealtime\ZabRealtime;
use ZabRealtime\ZabException;
$db = new ZabRealtime('https://rtdb.example.com', 'zk_YOUR_ACCESS_KEY');
try {
$db->set('users/u1', ['name' => 'Alex']); // replace
$db->update('users/u1', ['city' => 'Austin']); // merge keys
$key = $db->push('orders', ['item' => 'tea']); // auto chronological key
$user = $db->get('users/u1'); // read once (null if empty)
$db->remove('orders/' . $key);
} catch (ZabException $e) {
error_log($e->zabCode . ': ' . $e->getMessage()); // rejected | unauthorized | timeout | disconnected | invalid | server
}Complete connection example
A full, copy-paste setup: configuration, connecting with error handling, watching the connection, a live listener, writes, and a clean shutdown. It reconnects by itself if the network drops (see Reliability & reconnection).
order.php
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use ZabRealtime\ZabRealtime;
use ZabRealtime\ZabException;
$db = new ZabRealtime(getenv('ZAB_URL'), getenv('ZAB_ACCESS_KEY'), 10.0); // https://rtdb.example.com, zk_..., timeout (s)
try {
// Check the key and the connection first (also useful as a health check).
$who = $db->whoami();
error_log('ZabRealtime app: ' . $who['app']['name']);
// Write and read.
// Log the call under the end user who made it (optional: without it the server generates an id).
$key = $db->as($currentUserId)->push('orders', ['item' => $_POST['item'] ?? 'tea', 'at' => (int) (microtime(true) * 1000)]);
$db->update('stats', ['lastOrder' => $key]);
$order = $db->get('orders/' . $key);
header('Content-Type: application/json');
echo json_encode(['id' => $key, 'order' => $order]);
} catch (ZabException $e) {
// unauthorized = wrong/revoked key; disconnected = the server is unreachable (retry later); rejected = suspended/blocked
http_response_code($e->zabCode === 'unauthorized' ? 500 : 502);
error_log('ZabRealtime ' . $e->zabCode . ' (' . $e->status() . '): ' . $e->getMessage());
echo json_encode(['error' => 'database unavailable']);
}API at a glance
| Operation | Call |
|---|---|
| Connect | new ZabRealtime($url, $key) (stateless) |
| User ID (optional) | new ZabRealtime($url, $key, 15.0, $userId) · $db->as($userId) |
| Read once | $db->get($path) |
| Replace | $db->set($path, $value) |
| Merge | $db->update($path, ['key' => $value]) |
| Push | $key = $db->push($path, $value) |
| Delete | $db->remove($path) |
| Live listener | not available (REST only) |
| Connection state | $db->whoami() (app, limits, usage) |
| Disconnect | nothing to close |
User ID
Pass a user id as the fourth constructor argument, or use as() to act for the end user behind each request. Without one the server generates an id from the client's address.
$db = new ZabRealtime($url, $key);
$db->as($currentUser->id)->push('orders', ['item' => 'tea']); // logged under that user
$db2 = new ZabRealtime($url, $key, 15.0, 'cron-job');Laravel
// app/Providers/AppServiceProvider.php
$this->app->singleton(ZabRealtime::class, fn () => new ZabRealtime(config('services.zab.url'), config('services.zab.key')));
// anywhere
public function store(Request $r, ZabRealtime $zab) {
return ['id' => $zab->push('orders', $r->validate(['item' => 'required|string']))];
}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 path is relative to that app's private tree.
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.
{"id":"1","op":"set","path":"users/u1","data":{"name":"Alex"}}
{"id":"2","op":"update","path":"users/u1","data":{"city":"Austin"}}
{"id":"3","op":"push","path":"chats/room1/messages","data":{"text":"hi"}}
{"id":"4","op":"get","path":"users/u1"}
{"id":"5","op":"delete","path":"users/u1"}
{"id":"6","op":"subscribe","path":"chats/room1"}
{"id":"7","op":"unsubscribe","path":"chats/room1"}
{"id":"8","op":"ping"}{"id":"3","ok":true,"path":"chats/room1/messages/-Oxk3…","key":"-Oxk3…"} // push reply
{"id":"4","ok":true,"path":"users/u1","data":{"name":"Alex"}} // get reply
{"id":"9","ok":false,"error":"storage quota exceeded"} // failure
{"event":"value","path":"chats/room1","ok":true,"data":{ }} // subscription push- Echo the client-generated
idto match replies to requests. subscribereplies with the current value (event: "value") and keeps pushingvalueevents.pingreplies{"id":"8","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. Older servers answerunknown op, which also proves the connection is alive.- The server sends WebSocket ping frames every 30 s and drops connections that stay silent for 70 s; any message you send resets that timer.
- A frame larger than 1 MB closes the connection; a malformed frame gets
{"ok":false,"error":"invalid message"}and the connection stays open.
Socket.IO
Endpoint /socket.io/, Socket.IO v4 over the websocket transport only (set transports: ['websocket']). Authenticate with auth: {key: 'zk_…'} or ?key=.
| Event | Argument | Ack |
|---|---|---|
| get / fetch | {path} | {ok, path, data} |
| set | {path, data} | {ok, path} |
| update | {path, data} | {ok, path} |
| push | {path, data} | {ok, path, key} |
| delete / remove | {path} | {ok, path} |
| subscribe | {path} | {ok, path, data} |
| unsubscribe | {path} | {ok, path} |
| value (server → client) | {path, data} | — |
REST
Base URL https://host/db/<path>, header Authorization: Bearer zk_…, JSON bodies up to 1 MB. REST writes also trigger WebSocket broadcasts.
| Method | Meaning | Response |
|---|---|---|
GET /db/users/u1 | Read | the JSON value (null when empty) |
PUT /db/users/u1 | Set (replace) | {"ok":true} |
PATCH /db/users/u1 | Update (merge) | {"ok":true} |
POST /db/messages | Push | {"name":"<key>","path":"…"} |
DELETE /db/users/u1 | Remove | {"ok":true} |
GET /whoami | Check a key | app, customer, limits, usage and the socket/REST URLs (never the key) |
curl -X PUT https://your-server/db/users/u1 \
-H "Authorization: Bearer zk_YOUR_ACCESS_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"Alex"}'Errors & connection states
All SDKs expose the same states and the same six error codes.
Connection states
| State | Meaning |
|---|---|
| disconnected | Not connected and not trying (before connect(), after disconnect()). |
| connecting | Opening, or waiting to retry after a network problem. Retries back off from 1 s to 10 s. |
| connected | Live. Listeners are active. |
| rejected | The server answered but refused the key. The reason is in lastError. A wrong, revoked or deleted key stops retrying; other refusals are retried every 60 s. |
Error codes
| Code | HTTP | When | What to do |
|---|---|---|---|
| unauthorized | 401 | The key is wrong, revoked or deleted. | Stop. Ask the user to sign in again or fetch a new key, then useAccessKey(). |
| rejected | 403 · 429 | Account or app suspended, key disabled, your IP blocked, origin not allowed, rate limited, or locked out after too many wrong keys. | Retried automatically every 60 s. Show lastError. |
| timeout | — | No answer within the request timeout (default 15 s), or the connection did not come up in time. | Retry the call. |
| disconnected | — | The connection dropped or was closed while a call was in flight; or the server is unreachable. | The SDK reconnects by itself; retry the call. |
| invalid | 400 | Bad path (empty segment, over 1,024 characters or 32 levels), bad value, or missing key/URL. | Fix the input. |
| server | 5xx · other | The server refused the operation: storage quota exceeded (507), connection limit reached (503), invalid JSON. | Read the message. |
The server counts every wrong key: 10 wrong keys in a minute lock the client's IP out for 5 minutes (HTTP 429). That is why the SDKs stop retrying on unauthorized instead of hammering the server.
Limits
Defaults of a stock server. Operators set the start-up values with flags and can change every rate limit at any time, with no restart, in the admin console under Rate limits (or GET/PUT /api/limits).
| Limit | Value |
|---|---|
| Message / request body size | 1 MB |
| Path length · depth | 1,024 characters · 32 levels |
| Subscriptions per connection | 1,000 |
| Operations per second per connection | 200 sustained, burst 400 (-ops-per-sec); persistent abusers are disconnected |
| Connections per IP · server-wide | 200 · 10,000 (-max-conns-per-ip, -max-conns) |
| Storage quota (per app) | Set on each app, any number from 1 MB, no upper limit, default 100 MB |
| Connections (per app) | Set on each app, default 1,000 |
| Active keys per app | 20 |
| Apps per customer | 50 |
| New connections per IP | 600 per minute (editable in the console) |
| REST / console requests per IP | 200 per second, burst 400 (editable) |
| Wrong-key lockout | 10 per minute → 5 minutes per IP (editable) |
| Slow clients | A client that stops reading is disconnected and re-syncs on reconnect |
Not available yet: queries (orderBy, limit) and per-path security rules inside an app. Each app's tree is held in memory, with idle apps unloaded after 15 minutes.
Security & keys
An access key is a password to one app's data. Treat it like one.
One key per client type
Create a separate key for each platform and for your backend: a Web key, an Android key, a Server key. If one leaks you disable or revoke only that one, and live connections using it are cut immediately.
Keys in apps
- Browser and mobile apps ship their key inside the app: anyone can extract it. That is expected for client SDKs; limit the damage with a dedicated key and the app's IP block list.
- Servers (Next.js server code, Python, Go, PHP, .NET backends) keep the key in an environment variable or secret manager, never in source control and never in a
NEXT_PUBLIC_variable.
Browsers
Browser connections must come from an origin allowed by the server's -origins flag (default *, because every connection still needs a valid key). Lock it down to your domains in production. Native apps send no Origin header and are always allowed.
Transport
Always use https:// / wss:// in production. WebSocket keys travel in the query string, so make sure your reverse proxy does not log query strings (the bundled installer's nginx config does not).
Rotating a key
// 1. generate a new key in the console, 2. give it to the running app, 3. revoke the old one
db.useAccessKey('zk_NEW_KEY'); // listeners are keptReliability & reconnection
Mobile and office networks drop all the time. Every realtime SDK notices, reconnects by itself, and restores your listeners, with no code on your side.
What happens when the network drops
- Notice. A closed or reset connection is seen at once. A silent drop (a half-open connection) is caught by the heartbeat: the SDK pings an idle connection and, if nothing comes back in time, declares it dead.
- Ask why. It calls
GET /whoami. If the network is down the call fails and the SDK keeps retrying. If the server answers401the key is wrong or revoked: state becomesrejectedand retrying stops. If it answers403or429(suspended, disabled key, blocked IP, lockout) the state isrejectedand it retries every 60 s. - Retry with backoff. About 1 s, 1.7 s, 2.9 s, 4.9 s, 8.4 s, then every 10 s, each with random jitter so thousands of clients do not reconnect at the same instant. Where the platform reports “network is back” (browsers, Android, iOS, .NET) the SDK reconnects immediately instead of waiting.
- Restore. On reconnect every live listener is re-subscribed and receives the latest value, so changes that happened while offline appear. Writes you made while offline wait for the connection (up to the request timeout) and then go through.
Detection and recovery by SDK
| SDK | Silent drop noticed | Network back | Tuning |
|---|---|---|---|
| JavaScript, React, Next.js (client) | heartbeat: 25 s + 10 s (max about 35 s) | immediately in browsers (online event, tab visible); else next retry (max 10 s) | heartbeatMs, heartbeatTimeoutMs |
| Flutter | Socket.IO ping: 25 s + 20 s (about 45 s); also a 30 s watchdog and a reconnect on app resume | next retry (max 10 s); reconnect when the app returns to the foreground | built in |
| Android (Kotlin) | WebSocket ping every heartbeatMs (20 s): about 20–40 s | immediately with autoReconnectOnNetwork(context) | ZabOptions.heartbeatMs |
| iOS / macOS (Swift) | heartbeat: 25 s + 10 s | immediately (NWPathMonitor, built in) | ZabOptions.heartbeat, heartbeatTimeout |
| .NET | heartbeat: 25 s + 10 s | immediately (NetworkChange, built in) | HeartbeatInterval, HeartbeatTimeout |
| Python | WebSocket ping: 25 s + 10 s | next retry (max 10 s) | heartbeat, heartbeat_timeout |
| Go | heartbeat: 25 s + 10 s | next retry (max 10 s) | Options.HeartbeatInterval, HeartbeatTimeout |
| Next.js server, PHP, REST clients | no connection to lose: each call is independent | the next call just works | timeout option |
Lower the heartbeat for faster detection (for example 10 s + 5 s) at the cost of a little more traffic. The ping is cheap: it is not metered and does not appear in the activity log.
What your code should do
- Show the connection state (
state,lastError) so users know when they are offline. Do not build your own reconnect loop. - Treat
unauthorizedas final: ask the user to sign in again or fetch a new key, then calluseAccessKey. - Treat
timeoutanddisconnectedfrom a call as retryable. - REST calls (PHP, Next.js server,
ZabRest, GoREST) do not retry for you: wrap them in your own retry for critical writes.
Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
State stays rejected with “unauthorized” | The key is wrong, was revoked or its app was deleted. Check it with GET /whoami or the console's API key tester; give the app a new key. |
rejected with “this access key is disabled” / “suspended” | An admin switched the key, app or customer off. The SDK retries every 60 s and recovers by itself once it is switched on. |
rejected with “your IP address is blocked” | The address is on the app's or the system IP block list (console → IP block list). |
| HTTP 429 / “too many failed attempts” | Ten wrong keys in a minute from one IP. Wait five minutes, fix the key, and avoid retry loops. |
| Browser: connection fails, nothing in the console | Origin not allowed (-origins) or an http:// page connecting to wss:// with a bad certificate. Open the Network tab and look at the /ws request. |
| Flutter on the Android emulator cannot reach localhost | Use http://10.0.2.2:8080, and allow cleartext HTTP for non-TLS development. |
timeout on every call | The connection is not up (check state), or a proxy strips WebSocket upgrades: it must forward Upgrade and Connection headers and allow read timeouts of 120 s or more. |
server error “storage quota exceeded” | The app reached its quota. Delete data or raise the app's storage quota (edit the app in the console). |
Listener fires with null first | That is the current value of an empty path. Treat null as “no data yet”. |
| Socket.IO: “Only the websocket transport is supported” | Set transports: ['websocket'] (Flutter: setTransports(['websocket'])). |
Want ZabRealtimeKit for your app?
Tell us your platform and what you want to build, and we will set up your access.
