
Add realtime push with ZabPush
Pick your platform, copy the code, and send your first push from your server. ZabPush is in beta.
Getting started Core concepts JavaScript Flutter Background delivery Product details
Getting started
Add realtime push to any web, mobile or backend project. Pick your platform, copy the code, and your first push arrives in minutes.
How ZabPush works
Client SDKs run inside your apps. Server SDKs run on your backend. Several platforms offer both (JavaScript, Python, .NET, Go, Java); PHP and Node.js are used on the server side only.
1 · Create an app and get your keys
- Get your keysAsk us for access through the contact page or at cloud@zabsys.com. You receive an access key (
zpk_…) and a secret key (zps_…, shown once), and your service address, writtenYOUR_SERVERon these pages. - Open your customer panelWe send you a link to
https://YOUR_SERVER/panel/. It works once and for a short time, so open it when you receive it. - Add an appUnder Apps, create an app, name it and choose its platforms.
- Copy the credentialsEach app has a public app key and an app id for your code, and an app secret for your server only.
| Credential | Where it goes | Public? |
|---|---|---|
| App key | Inside your web, mobile and desktop apps (client SDKs) | Yes, safe to ship |
| App id | Your backend (part of the publish URL) | Not secret |
| App secret | Your backend only: publishing and signing private channels | Never in an app or website |
Secret key (zps_…) | Your backend only: managing your apps and reading messages by REST API | Never in an app or website |
Access token (zpt_…) | Your backend, as an alternative to the secret for publishing | Never in an app or website |
Anyone holding the app secret or an access token can send pushes as you. If one leaks, rotate the app secret in your customer panel, or tell us at once so we can replace the key.
2 · Choose your SDK
The SDKs are not on public package registries yet. Ask us for the SDK package: paths such as sdk/js on these pages are inside it. In a web page, the JavaScript client can be loaded straight from https://YOUR_SERVER/sdk/zabpush.js.
Browsers, Node.js 22+, Deno, Bun. One file, no dependencies.
Hooks, AsyncStorage, reconnect on foreground and network change.
Android, iOS, web and desktop from one codebase.
OkHttp-based library with main-thread callbacks.
Swift Package, no third-party dependencies.
NNode.js (server)Send pushes and sign private channels from your backend.
asyncio client plus a standard-library server SDK.
ASP.NET, MAUI, workers, Unity (netstandard2.1).
GoGoClient and publisher in one module.
JJavaSpring, Jakarta, plain Java 11+. JDK HTTP and WebSocket.
PPHPLaravel, Symfony, WordPress: send pushes from PHP.
{}HTTP & WebSocket APIAny other language: curl, Ruby, Rust, shell, IoT.
3 · Send your first push
Before writing code, prove the server works. Open the built-in demo client in a browser and send it a push with curl.
- Open the demo clientVisit
https://YOUR_SERVER/demo?key=APP_KEY&channel=test. The status should show connected. - Send a push
BASH / POWERSHELL (curl.exe)
curl -X POST https://YOUR_SERVER/api/v1/apps/APP_ID/events \ -H "Authorization: Bearer APP_SECRET" \ -d '{"channel":"test","event":"hello","data":{"title":"It works","body":"My first push"}}' - See it arriveThe message appears in the demo page immediately, and your customer panel's Messages tab lists it with its delivery receipts.
Your customer panel can send a test push to your apps, and shows who received it.
4 · Integrate
Open your platform in the sidebar. Each page follows the same order, so the steps are familiar everywhere:
- Requirements and installation
- Quick start (connect and receive in a few lines)
- Configuration options
- Private channels, receipts and the inbox
- Background delivery and the connection lifecycle
- API reference, error handling, testing and a go-live checklist
Core concepts
The few ideas every SDK shares. Learn them once and every platform page reads the same.
Keys and user id
A client connects with the public app key and a user id. The user id is yours: your account id, a device id, any stable string up to 64 characters of letters, digits and . _ @ : -.
- Receipts, the inbox and missed-message replay are all kept per user id.
- Your customer panel shows the user id next to delivered / read / clicked.
- If you omit it, the SDK generates one. Browsers and React Native remember it; other SDKs generate a new one each run unless you persist it.
Anyone who knows another user's id and the (public) app key can connect as them. Put sensitive data on private channels, not public ones.
Channels and events
A channel is a named stream (news, orders, user-42). A message has an event name (promo, order.shipped) and a JSON data payload. Clients subscribe to channels and bind handlers to events (or * for all).
| Rule | Limit |
|---|---|
| Characters in channel and event names | letters, digits and _ - = @ , . ; : # / |
| Name length | 190 characters |
| Channels per publish | up to 100 |
| Channels per connection | up to 100 |
| Request body | 64 KB |
Private channels
Channels whose name starts with private- need a signature to subscribe, so you decide who may listen. The signature is hex(HMAC-SHA256(app_secret, socket_id + ":" + channel)) and only your backend can create it.
private-user-42.authorize callback with the connection's socketId and the channel name.The socket id changes on every reconnect, so never cache a signature. The SDKs call authorize again whenever they resubscribe.
Receipts, inbox and replay
| Feature | What it does |
|---|---|
| Delivered | Sent automatically for every stored message. Turn off with autoAck: false at very high volume. |
| Read / clicked | You call read(id) / clicked(id) / markAllRead(channel). Each status implies the earlier ones. |
| Replay | The server remembers what each user id acknowledged. After any reconnect (even an app restart) unacknowledged messages are delivered again, so nothing is lost while offline. |
| Inbox | inbox(channel) returns the stored history with a read flag and an unread count, perfect for notification screens and badges. |
| TTL | A publish may carry ttl seconds; after that the message is no longer replayed or shown in the inbox. |
| Retention | Messages are kept for the server's retention period (7 days by default). |
Receipts show up in your customer panel's Messages tab, including which user ids clicked each message.
Live-only messages
If the server's database is temporarily unavailable, pushes are still delivered to connected users but marked id = 0 and live = true. They are not stored, cannot be replayed, and cannot be acknowledged. SDKs skip the receipt for them automatically. When you publish, the response says "stored": false.
Rate limits
The server protects itself with limits (set on the service). Your code should treat 429 as "slow down and retry".
| Limit | Default |
|---|---|
| Publish requests per app | 10,000 per second |
| Connections per IP address | 1,000 (and 200 new connections per second) |
| Control messages per connection (subscribe, inbox …) | 50 per second |
| Receipts per connection | 1,000 per second |
Background delivery
How a push reaches a phone when your app is open, in the background or closed: what each platform allows, what ZabPush does about it, and what you set up.
Three app states
A realtime connection only exists while the operating system lets your app run. So what happens to a push depends on the state of the app, and the two mobile systems behave very differently.
| App state | Android | iOS |
|---|---|---|
| Open (foreground) | Live over the WebSocket, instant. | Live over the WebSocket, instant. |
| Background (user switched away) | Stays connected if you start the foreground service. Without it Android pauses the app after a while. | The app is suspended after a few seconds and the connection closes. This cannot be changed. |
| Closed (swiped away, or killed by the system) | The server sends a notification through Firebase Cloud Messaging. | The server sends a notification through Firebase, which hands it to Apple's push service (APNs). |
Whichever route carried the push, the message is stored on the server with a per-user cursor. A user who was offline for a day still gets everything on the next connect, in order, once.
Android
Android lets a background app run only for a short while. After that it is stopped, and the socket closes. To stay connected you run a foreground service: Android requires it to show a small ongoing notification, and in return keeps your process alive. The SDK ships one, ZabPushForeground. Your ZabPush client stays in your Application class; the service only keeps the process running.
- Declare the permissionsThe library declares the service itself; you add
FOREGROUND_SERVICE,FOREGROUND_SERVICE_SPECIAL_USEand, for Android 13+,POST_NOTIFICATIONS. The example manifest has them. - Start it while the app is visibleAndroid 12+ refuses to start a foreground service from the background. A good moment is after login, or when the user turns on "live updates".
- Stop it when it is no longer neededFor example on logout.
- Subscribe in your Application classIf Android kills the process it restarts the service and your
Application, but there is no Activity. Create the client and its subscriptions inApplication.onCreate, and let the visible screen listen. Subscriptions made only in an Activity are lost after a kill.
ZabPushForeground.start(this, title = "Connected", text = "Receiving live updates")
ZabPushForeground.stop(this) // on logout, or when the user turns it off
// optional, once, after explaining why: stop manufacturers from killing the app
ZabPushForeground.requestBatteryOptimizationExemption(this)What the user sees and what it costs
- One quiet notification (lowest importance: no sound, no status-bar icon). Android requires it and it cannot be hidden. Users can switch it off in system settings.
- Some battery, because the radio stays awake for the heartbeat. Offer it as a setting, not for everyone.
- Doze: Android's deep sleep for a still phone with the screen off. On an Android 16 emulator in forced Doze the app still received a push within seconds, but real phones and manufacturers differ. For pushes that must arrive, also register the device (see Push when the app is closed): the notification is the reliable route.
- Wake lock: the service holds a partial wake lock and a Wi-Fi lock so the connection's heartbeat keeps firing with the screen off. Without them the CPU sleeps, the server drops the silent connection after 40 seconds and the app reconnects over and over. This is part of the battery cost.
- Some manufacturers (Xiaomi, Huawei, OnePlus and others) add their own battery managers that stop background apps even with a foreground service. The battery-exemption prompt helps; users can also allow auto-start in the phone's settings.
- Google Play: the service uses the
specialUsetype becausedataSyncis stopped after 6 hours on Android 15. The Play Console asks you to explain it: "Keeps a WebSocket open to receive live messages the user asked for."
iOS
iOS does not let an ordinary app hold a connection in the background. A few seconds after the user leaves the app, the system suspends it and the socket is closed. There is no setting for this, and the usual tricks (playing silent audio, fake location updates, VoIP mode) are against App Review rules and get apps rejected. So on iOS the design is different: let the connection end cleanly, and use Apple's push service to reach the user.
1. A clean hand-over (the SDK)
ZabPushLifecycle asks iOS for its short grace period (about 30 seconds) when the app goes to the background, so receipts and in-flight messages finish. When the app returns, it reconnects at once and the server replays what was missed.
let zp = ZabPush(appKey: "APP_KEY", options: ...)
let lifecycle = ZabPushLifecycle(client: zp) // create once and keep a reference2. A notification while suspended (Apple's push service)
When the user has no live socket, or the socket does not confirm the message (see When ZabPush sends a notification), ZabPush sends it through Firebase, which delivers it with APNs. The notification appears on the lock screen like any other. Each one is marked high priority, with a sound and content-available.
3. A short wake-up to sync
With the Remote notifications Background Mode enabled, content-available lets iOS wake the app for a few seconds. The example AppDelegate reconnects in that window, so the server replays everything missed before the user opens the app.
- Xcode capabilitiesSigning & Capabilities → add Push Notifications and Background Modes → Remote notifications.
- APNs keyCreate it in your Apple Developer account and upload it in the Firebase console (Project settings → Cloud Messaging).
- Register the deviceHand the Firebase token to ZabPush with
registerDevice(see below).
iOS may delay or skip the background wake-up: in Low Power Mode, when the app was force-quit by the user, or when the app used too much background time recently. The visible notification is the guarantee; the wake-up is a bonus. Tapping the notification opens the app, which connects and replays.
Flutter
Flutter runs on both systems, so you combine the two behaviours above. The Dart package is plain Dart and does not know about the app lifecycle, so you add two small pieces.
Reconnect when the app returns (Android and iOS)
class _AppState extends State<App> with WidgetsBindingObserver {
@override
void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); }
@override
void didChangeAppLifecycleState(AppLifecycleState s) {
// back in the foreground: do not wait for the next retry
if (s == AppLifecycleState.resumed && zp.status != PushStatus.connected) zp.reconnectNow();
}
@override
void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); }
}Android: stay connected in the background
A foreground service has to be native code. Use a Flutter plugin that provides one (for example flutter_foreground_task), start it while the app is visible, and create the ZabPush client inside the task so it lives as long as the service. Declare the specialUse service type and the permissions listed in the Android section.
iOS: notification, then catch-up
The app is suspended a few seconds after it leaves the foreground, as described in the iOS section. Use firebase_messaging for the notification; the resumed handler above fills in the gap when the user returns.
Both: closed app
Register the Firebase token with ZabPush, shown in the next section.
When ZabPush sends a notification
The server can only know a phone is gone when its connection ends, and a suspended iPhone or a sleeping Android phone often leaves a dead connection that looks open for up to 40 seconds. So "is the user connected?" is not enough. ZabPush uses two rules for every device that registered a token:
- Not connectedThe notification is sent at once.
- Connected, but no confirmationThe SDK acknowledges every push automatically. If no acknowledgement arrives within 5 seconds, the connection is treated as dead and the notification is sent too. A healthy phone confirms in milliseconds and gets no notification.
The wait is 5 seconds unless we agree otherwise for your account. If you disable automatic receipts in the SDK (autoAck: false), every push to a connected phone would also send a notification, so keep autoAck on, or turn rule 2 off, or publish with "fallback": false.
Lost receipts are recovered
A push can arrive just before the connection drops, with the receipt lost on the way. When the user reconnects, the SDK reports the last message it saw, and the server records receipts for everything up to there. The push then counts as delivered and no notification is sent for it.
Tested against a live server: a connected but silent client received the notification after the wait, an acknowledging client received none, an offline client received it at once, a push that arrived during airplane mode was counted as delivered once the app reconnected, and a missed push was replayed. Firebase itself was simulated, not real.
Push when the app is closed
Reaching an app that is closed (or, on iOS, suspended) needs a notification from the platform's own push service. ZabPush takes care of sending it. You do three things once.
1. Server setup (once per app)
- Create a Firebase projectAt
console.firebase.google.com. Add your Android and/or iOS app. - iOS only: upload your APNs keyFirebase console → Project settings → Cloud Messaging → Apple app configuration.
- Create a service-account keyProject settings → Service accounts → Generate new private key (a JSON file).
- Give it to ZabPushAsk us to add the file to your app. It is a private key, so do not send it in an ordinary email or chat: ask us for a safe way.
The key is kept on the ZabPush server, is not shown again, and is only used to call Google. ZabPush rejects keys that point anywhere else.
2. App setup: register the device
Get the device's Firebase token and give it to ZabPush. Do it after you create the client; the SDK re-sends it after every reconnect.
FirebaseMessaging.getInstance().token.addOnSuccessListener { token -> zp.registerDevice(token) }
// MyFirebaseService : FirebaseMessagingService
override fun onNewToken(token: String) { App.zp.registerDevice(token) }
// In your launcher Activity: the user tapped a notification
intent.extras?.getString("id")?.toLongOrNull()?.let { zp.clicked(it) }Messaging.messaging().token { token, _ in
if let token = token { zp.registerDevice(token: token) }
}
// refreshed tokens (MessagingDelegate)
func messaging(_ m: Messaging, didReceiveRegistrationToken token: String?) {
if let token = token { zp.registerDevice(token: token) }
}
// the user tapped a notification (UNUserNotificationCenterDelegate)
func userNotificationCenter(_ c: UNUserNotificationCenter, didReceive r: UNNotificationResponse, withCompletionHandler done: @escaping () -> Void) {
if let id = r.notification.request.content.userInfo["id"] as? String, let n = Int64(id) { zp.clicked(n) }
done()
}import 'dart:io' show Platform;
import 'package:firebase_messaging/firebase_messaging.dart';
final platform = Platform.isIOS ? 'ios' : 'android';
final fcm = FirebaseMessaging.instance;
await fcm.requestPermission();
final token = await fcm.getToken();
if (token != null) zp.registerDevice(token, platform);
fcm.onTokenRefresh.listen((t) => zp.registerDevice(t, platform));
// the user tapped a notification: tell the server (feeds the list of who clicked)
FirebaseMessaging.onMessageOpenedApp.listen((m) => zp.clicked(int.parse(m.data['id'])));
final initial = await fcm.getInitialMessage(); // app launched from a notification
if (initial != null) zp.clicked(int.parse(initial.data['id']));React Native: get the token with @react-native-firebase/messaging (messaging().getToken()) and call client.registerDevice(token, Platform.OS). On Android 13+ request the POST_NOTIFICATIONS permission; on iOS request notification permission with UNUserNotificationCenter.requestAuthorization.
3. Publish as usual
ZabPush builds the notification from your message: if data is a JSON object with title and body they are used; otherwise the title is the event name. The notification data carries id, channel, event and payload.
{ "channel": "orders", "event": "order.shipped",
"data": { "title": "Your order shipped", "body": "Arriving Friday", "orderId": 981 } }Publish with "fallback": false to send only over the live connection (for example chat typing events).
Test each state
- Open: send a test push from your customer panel. It appears instantly.
- Background: press Home, wait a minute, send again. Android with the service running: instant. iOS: a notification appears.
- Closed: swipe the app away and send again. A notification should appear on both platforms. The Messages tab shows an FCM count for it.
- Catch-up: open the app. The pushes you missed appear and the receipts update.
- Flight mode: send a push, then turn the network back on. The push arrives on reconnect.
Nothing arrives while closed? The usual causes: the service-account JSON was not saved for this app, the device never called registerDevice (the app's Settings shows how many devices are registered), the user never subscribed to that channel, notification permission is off, or (iOS) the APNs key is missing in Firebase.
Limits to know
| Limit | What it means |
|---|---|
| iOS suspends apps | No live socket in the background. Notifications and catch-up on return are the design, not a workaround. |
| iOS wake-up is not guaranteed | Skipped in Low Power Mode and after a force-quit. The notification is still shown. |
| Android Doze and battery managers | Behaviour differs between phones. The notification path is the safety net for pushes that must arrive. |
| Manufacturer battery managers | Some stop background apps even with a foreground service. Ask the user to exempt the app. |
| Notification required on Android | The foreground service must show one; it cannot be hidden. |
| Notifications run through Firebase | ZabPush sends to Firebase (and APNs through it); it does not speak to APNs directly. |
Android was built and run on an Android 16 emulator: connection kept with the screen off, after swiping the app away, after a system kill, in forced Doze and across airplane mode. Flutter was run on the same emulator. The iOS helper is in preview. Test on real phones before launch, especially with manufacturer battery managers.
Go-live checklist
Everything to check before real users connect, in one place.
Security
- Your server uses HTTPS, and clients connect with
secure: true(wss://). - The app secret and access tokens exist only on your backend. Search your mobile and web code for them.
- Sensitive data goes on private channels, and your auth endpoint checks the signed-in user before signing.
- User ids come from your own authenticated session, never from user input.
- Ask us to limit your server keys to your own IP addresses.
Reliability
- Your UI reacts to connection states (
connecting / connected / reconnecting / disconnected) instead of assuming a live link. - You treat the server SDK's errors and
429responses as retryable, with backoff. - You keep user ids stable across app launches, so replay and the inbox work.
- Mobile apps register an FCM token so users get pushes when the app is closed. See Background delivery.
- You tried the real flow end to end: kill the network on a device, send a push, restore it, and confirm the push arrives.
Scale and cost
- Prefer one channel per audience (per user, per topic) over thousands of tiny channels.
- Use
ttlon time-sensitive messages so stale ones are not replayed. - At very high volume set
autoAck: falseif you do not need delivered receipts for every message. - Before a big launch, tell us the numbers you expect and test with them.
Platform specifics
| Platform | Remember |
|---|---|
| Web | Serve over HTTPS; pass userId from your session; call close() on logout. |
| React Native | Android release builds need no cleartext exception on wss://; install AsyncStorage and NetInfo for best behaviour. |
| Android | Add INTERNET permission; create the client once (Application class); use FCM for background delivery. |
| iOS | App Transport Security allows wss:// by default; sockets suspend in background, so use FCM. |
| Backends | Reuse one server-SDK instance; keep the secret in an environment variable or secret manager. |
JavaScript / TypeScript
One file for browsers, Node.js 22+, Deno and Bun. No dependencies, TypeScript types included.
Overview
The JavaScript client connects to ZabPush over a WebSocket, reconnects by itself, replays what you missed, and sends delivery receipts. The same file is also what React Native uses under the hood. Backends written in Node.js use the separate Node.js server SDK to send pushes.
| Where it runs | Notes |
|---|---|
| Browsers (Chrome, Edge, Firefox, Safari) | Load the script served by your own ZabPush server. No build step. |
| Node.js 22+, Deno, Bun | Built-in WebSocket. |
| Node.js 18–21 | Pass the ws package: { WebSocket: require('ws') }. |
| Bundlers (Vite, webpack, Next.js client code) | Import as an ES module or CommonJS. |
Requirements
- A ZabPush app key (see Getting started) and your server's address.
- For TypeScript: 4.5 or newer (types ship with the package).
- Production pages must be served over HTTPS and connect with
secure: true.
Installation
<script src="https://cloud-zabpush.zabsys.com/sdk/zabpush.js"></script>npm install ./sdk/js # from the SDK package folder (or publish it to your registry as "zabpush")npm install ./sdk/js wsThe script tag option defines a global ZabPush and is always the same version as your server.
Quick start
<script src="https://cloud-zabpush.zabsys.com/sdk/zabpush.js"></script>
<script>
const zp = new ZabPush('APP_KEY', {
host: 'cloud-zabpush.zabsys.com', // in a browser the default is the page's own host
secure: true, // wss://
userId: 'user-42', // YOUR unique id for this user
});
zp.subscribe('news').bind('promo', (data, msg) => {
console.log(data.title, data.body);
zp.read(msg.id); // tell the server the user saw it ("delivered" is automatic)
});
</script>import ZabPush from 'zabpush';
interface Promo { title: string; body: string }
const zp = new ZabPush('APP_KEY', { host: 'cloud-zabpush.zabsys.com', secure: true, userId: 'user-42' });
zp.subscribe('news').bind<Promo>('promo', (data) => console.log(data.title));const ZabPush = require('zabpush'); // Node 22+; on older Node pass { WebSocket: require('ws') }
const zp = new ZabPush('APP_KEY', { host: 'cloud-zabpush.zabsys.com', secure: true, userId: 'worker-1' });
zp.subscribe('jobs').bind('*', (data) => console.log('job', data));Complete example
A complete, working page: live list of pushes, server inbox (history that survives reloads), unread badge, read and click receipts, and a connection status line. Save it as index.html, put your app key and host in, and open it in a browser.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ZabPush browser example</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; max-width: 640px; margin: 32px auto; padding: 0 16px; }
#status { display: inline-block; padding: 2px 12px; border-radius: 99px; background: #eee; font-weight: 600; }
#status.connected { background: #dcfce7; color: #166534; }
#status.disconnected, #status.reconnecting { background: #fee2e2; color: #991b1b; }
.msg { border: 1px solid #ddd; border-left: 4px solid #e11d2e; border-radius: 8px; padding: 8px 12px; margin: 8px 0; }
.msg.unread { background: #fff1f2; }
.msg button { margin-right: 6px; }
#badge { background: #e11d2e; color: #fff; border-radius: 99px; padding: 0 9px; font-size: 13px; }
</style>
</head>
<body>
<h1>Notifications <span id="badge">0</span></h1>
<p>Status: <span id="status">connecting</span> · you are <b id="who"></b></p>
<p>
<button id="markAll">Mark all read</button>
<button id="reload">Reload from server inbox</button>
</p>
<div id="list"></div>
<!-- the client file is served by your own ZabPush server -->
<script src="https://cloud-zabpush.zabsys.com/sdk/zabpush.js"></script>
<script>
const CHANNEL = 'news';
const USER_ID = 'user-42'; // YOUR id for the signed-in user (from your session)
const $ = (id) => document.getElementById(id);
let unread = 0;
const setUnread = (n) => { unread = Math.max(0, n); $('badge').textContent = unread; };
const zp = new ZabPush('APP_KEY', {
host: 'cloud-zabpush.zabsys.com',
secure: true, // wss:// (required on https pages)
userId: USER_ID,
clientName: 'browser-example',
onState: (state, info) => { // connecting | connected | reconnecting | disconnected
$('status').textContent = state === 'disconnected' && info.retryIn ? `disconnected, retrying in ${Math.round(info.retryIn / 1000)}s` : state;
$('status').className = state;
},
});
$('who').textContent = zp.userId;
// One card per message. textContent (not innerHTML) keeps pushed data from injecting HTML.
function addCard(msg, read) {
const card = document.createElement('div');
card.className = 'msg' + (read ? '' : ' unread');
const title = document.createElement('b');
title.textContent = (msg.data && msg.data.title) || msg.event;
const body = document.createElement('div');
body.textContent = (msg.data && msg.data.body) || '';
const readBtn = document.createElement('button');
readBtn.textContent = 'Mark read';
readBtn.onclick = () => { zp.read(msg.id); card.classList.remove('unread'); readBtn.remove(); setUnread(unread - 1); };
const clickBtn = document.createElement('button');
clickBtn.textContent = 'Open';
clickBtn.onclick = () => { zp.clicked(msg.id); if (card.classList.contains('unread')) setUnread(unread - 1); card.classList.remove('unread'); readBtn.remove(); };
card.append(title, body, ...(read ? [] : [readBtn]), clickBtn);
$('list').prepend(card);
}
// 1) live pushes ("delivered" receipts are sent automatically)
zp.subscribe(CHANNEL).bind('*', (data, msg) => { addCard(msg, false); setUnread(unread + 1); });
// 2) history from the server inbox (survives reloads, shows what you missed)
async function loadInbox() {
$('list').textContent = '';
const inbox = await zp.inbox(CHANNEL, 50);
inbox.messages.slice().reverse().forEach((m) => addCard(m, m.read));
setUnread(inbox.unread);
}
$('reload').onclick = () => loadInbox().catch(() => alert('Not connected yet'));
$('markAll').onclick = () => { zp.markAllRead(CHANNEL); document.querySelectorAll('.msg').forEach((c) => c.classList.remove('unread')); setUnread(0); };
zp.o.onState = ((prev) => (s, i) => { prev(s, i); if (s === 'connected' && !loadInbox.done) { loadInbox.done = true; loadInbox().catch(() => {}); } })(zp.o.onState);
// 3) log the user out cleanly
window.addEventListener('beforeunload', () => zp.close());
</script>
</body>
</html>Try it
# serve the folder (any static server works), then open http://localhost:5500
npx serve -l 5500 .
# send a push from your computer
curl -X POST https://cloud-zabpush.zabsys.com/api/v1/apps/1/events \
-H "Authorization: Bearer APP_SECRET" \
-d '{"channel":"news","event":"promo","data":{"title":"Hello","body":"It works"}}'What you should see
- The status turns connected and shows your user id.
- A card appears the moment you send the push. Mark read lowers the red badge; Open sends a click receipt.
- Reload the page and press Reload from server inbox: the history is back, with read cards shown as read (the state lives on the server).
- Your customer panel's Messages tab shows the delivered / read / clicked receipts for each message.
Run in a real browser against a live server: it connected, received two pushes, rendered pushed HTML as plain text (it uses textContent, never innerHTML), and the inbox reload showed the right read state.
Configuration
| Option | Default | Description |
|---|---|---|
host | page host / cloud-zabpush.zabsys.com | Server address with optional port. |
secure | follows the page | Use wss://. Always true in production. |
userId | generated, kept in storage | Your unique id for this user. clientId is an alias. |
clientName | none | Label shown in your customer panel's connected-clients list. |
platform | web / js | Platform label shown in your customer panel. |
reconnect | true | Reconnect automatically after drops. |
reconnectDelay | 500 ms | First retry delay. Doubles each attempt, with random jitter. |
maxReconnectDelay | 30000 ms | Upper bound of the backoff. |
heartbeatInterval | 15000 ms | How often a ping is sent. |
heartbeatTimeout | 10000 ms | Extra silence tolerated before the link is declared dead. |
autoAck | true | Send a "delivered" receipt for every push. |
authorize | none | Optional. Only for private-* channels: (socketId, channel) => string | Promise<string>: signature for private channels. |
onState | none | (state, info) => void: connection state changes. |
WebSocket | global | WebSocket class to use (Node < 22: require('ws')). |
storage | localStorage | Object with getItem/setItem (sync or async) for the generated user id. |
Receiving messages
const news = zp.subscribe('news');
news.bind('promo', (data, msg) => { /* event "promo" only */ });
news.bind('*', (data, msg) => { /* every event on this channel */ });
// msg = { id, event, channel, data, ts, live }
zp.unsubscribe('news');Handlers run in the order they were bound. An exception thrown by one handler is logged and never stops the others or the connection. bind returns the handle so calls chain; remove a handler with news.unbind('promo', fn).
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorize, no backend call. |
| Private | private-... | The optional authorize callback, which asks your backend for a signature (see Private channels). |
// settings: the test push of your customer panel shows these four values for your app
const kHost = 'cloud-zabpush.zabsys.com';
const kAppKey = 'APP_KEY';
const kChannel = 'app-1'; // the channel name you publish to (any name; no setup on the server)
const kUserId = 'user-42'; // YOUR id for this user
const zp = new ZabPush(kAppKey, { host: kHost, secure: true, userId: kUserId }); // no authorize: public channel
zp.subscribe(kChannel).bind('*', (data, msg) => console.log(data));
zp.subscribe('news').bind('promo', (data) => console.log(data)); // as many channels as you like, one connection
zp.unsubscribe('news'); // stop listening to one channel
zp.unsubscribeAll(); // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that throws is logged and skipped: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
const zp = new ZabPush('APP_KEY', {
host: 'cloud-zabpush.zabsys.com', secure: true, userId: 'user-42',
authorize: (socketId, channel) =>
fetch('/zabpush/auth', {
method: 'POST',
credentials: 'include', // your session cookie
body: new URLSearchParams({ socket_id: socketId, channel }),
}).then((r) => { if (!r.ok) throw new Error('not allowed'); return r.text(); }),
});
zp.subscribe('private-user-42').bind('*', (data) => console.log(data));Your backend endpoint is shown on the Node.js, PHP, Python and other server pages. If authorize throws or rejects, the subscription is skipped and the error is logged.
Receipts and inbox
zp.read(msg.id); // the user saw it
zp.clicked(msg.id); // the user opened it (also marks it read)
zp.markAllRead('news');
const { messages, unread } = await zp.inbox('news', 50); // messages: [{ id, event, data, ts, read }]
badge.textContent = unread;inbox rejects with Error('inbox timed out') after 8 seconds if the connection is down; call it again once connected.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.subscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.state: connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.isConnected |
| Which channels am I on? | zp.subscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.state // 'connecting' | 'connected' | 'reconnecting' | 'disconnected'
zp.isConnected // true while live
zp.socketId // id of the current connection (null while disconnected)
zp.subscribedChannels() // ['app-1', 'news']: the channels you are subscribed to right now
// be told about every change instead of asking
new ZabPush(kAppKey, { host: kHost, secure: true, onState: (state, info) => console.log(state, info) });The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.reconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | zp.close() disconnects for good: no more retries. To connect again create a new client. |
zp.reconnectNow(); // do not wait for the next retry (the browser already does this on "online" / tab visible)
zp.close(); // disconnect for good: on logout or when the page/component is torn down. No more retries.
// to connect again later, create a new ZabPush(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
const zp = new ZabPush('APP_KEY', {
host: 'cloud-zabpush.zabsys.com', secure: true, userId: 'user-42',
onState: (state, info) => {
// 'connecting' | 'connected' | 'reconnecting' | 'disconnected'
banner.hidden = state === 'connected';
if (state === 'disconnected' && info.retryIn) console.log(`retrying in ${info.retryIn} ms`);
},
});| State | info | Meaning |
|---|---|---|
connecting | attempt | First attempt. |
connected | socketId, userId | Live. Subscriptions are active and missed messages are replayed. |
reconnecting | attempt | Retrying after a drop. |
disconnected | reason, retryIn | Lost (will retry after retryIn ms) or closed on purpose. |
A dead connection (Wi-Fi dropped, laptop asleep, server restarted) is detected within about 25 seconds and repaired automatically. In browsers the client also reconnects immediately when the online event fires or the tab becomes visible. Call zp.reconnectNow() to force it, and zp.close() on logout.
API reference
| Member | Description |
|---|---|
new ZabPush(appKey, options?) | Creates the client and starts connecting. |
subscribe(channel) | Returns { bind(event, fn), unbind(event, fn?) }. Safe to call repeatedly. |
unsubscribe(channel) | Stops listening. |
read(id) · clicked(id) | Send a read / clicked receipt. |
markAllRead(channel) | Mark the whole channel read for this user. |
inbox(channel, limit = 50) | Promise of { messages, unread }. |
registerDevice(token, platform?) | Give the server an FCM token for offline pushes. |
reconnectNow() | Reconnect immediately. |
close() | Disconnect for good and stop all timers. |
userId · socketId · state | Read-only properties. |
Error handling
- Connection problems never throw: they surface as state changes and are retried.
- Malformed frames from the network are ignored; the connection stays up.
- Handler exceptions are caught and logged with
console.error. - No WebSocket available (old Node) throws at construction with a message telling you to pass
ws. - inbox() rejects on timeout; wrap it in
try/catch.
Test your integration
cd sdk/js
ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=APP_KEY ZP_ID=1 ZP_SECRET=APP_SECRET node examples/smoke.js
# -> state: connected / ok public / ok private / ok inbox / PASS jsThe test connects, subscribes to a public and a private channel, publishes with the Node server SDK, and expects both messages, a read receipt and the inbox. examples/reconnect.js shows recovery: run it, cut the network for a moment, and watch it print RECONNECTED.
Go-live checklist
secure: trueand an HTTPS page.userIdcomes from your logged-in session; callzp.close()when the user logs out.- Private data uses private channels with a server-side
authorizeendpoint. - The UI reflects
onState, for example a small offline banner. - No app secret or token appears in your bundle (search the build output).
Troubleshooting
Mixed content error / connection blocked on an https page
ws://. Use secure: true so the client uses wss://."ZabPush: no WebSocket available"
ws and pass { WebSocket: require('ws') }.Messages arrive twice after a page navigation
close() before creating another. In a SPA, create it once outside component renders.The status is stuck on "reconnecting"
/ws request: 401 means a wrong key, 429 a rate limit, and a failed handshake usually means the proxy is not forwarding WebSocket upgrades.
React Native
The JavaScript client with the parts mobile needs: a remembered user id, instant reconnect when the app returns to the foreground or the network comes back, and React hooks.
Overview
React Native has a built-in WebSocket, so the standard JavaScript client runs unchanged. The zabpush-react-native package adds createZabPush, useZabPush and useChannel, wires up AppState and (optionally) NetInfo, and stores the generated user id in AsyncStorage.
The JavaScript client, including async-storage handling and unbind, passes against a live server. The React Native layer is in preview: test on a device or emulator before shipping.
Requirements
- React Native 0.70 or newer, React 17+. Works with Hermes.
- Optional but recommended:
@react-native-async-storage/async-storage(keeps the user id) and@react-native-community/netinfo(instant reconnect when the network returns).
Installation
npm install ./sdk/js ./sdk/react-native
npm install @react-native-async-storage/async-storage @react-native-community/netinfo
cd ios && pod install # iOS only, for the two optional packagesQuick start
import React, { useState } from 'react';
import { FlatList, SafeAreaView, Text, TouchableOpacity, View } from 'react-native';
import { useChannel, useZabPush } from 'zabpush-react-native';
export default function App() {
const [items, setItems] = useState([]);
const { client, state } = useZabPush('APP_KEY', {
host: 'cloud-zabpush.zabsys.com', // your ZabPush server: host name only
userId: 'user-42', // YOUR id (omit: generated and remembered in AsyncStorage)
});
useChannel(client, 'news', '*', (data, msg) => {
setItems((prev) => [msg, ...prev]);
client.read(msg.id);
});
return (
<SafeAreaView style={{ flex: 1, padding: 16 }}>
<Text style={{ fontSize: 20, fontWeight: '700' }}>ZabPush: {state}</Text>
<FlatList data={items} keyExtractor={(m) => String(m.id)}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => client.clicked(item.id)}>
<View style={{ paddingVertical: 10 }}>
<Text style={{ fontWeight: '600' }}>{item.data?.title ?? item.event}</Text>
{item.data?.body ? <Text>{item.data.body}</Text> : null}
</View>
</TouchableOpacity>
)} />
</SafeAreaView>
);
}No hooks? createZabPush('APP_KEY', options) returns the same client as the JavaScript SDK; call client.close() when you are done.
Complete example
A complete screen: live pushes on a public channel and the user's private channel, history from the server inbox (reloaded on every reconnect), unread count, tap-to-click receipts, a connection banner, and an optional Firebase block for pushes while the app is closed.
// Complete React Native screen: live pushes, server inbox, unread badge, read / click receipts, a private channel,
// connection banner and optional Firebase push for when the app is closed.
//
// npm install ./sdk/js ./sdk/react-native @react-native-async-storage/async-storage @react-native-community/netinfo
// (offline pushes, optional: npm install @react-native-firebase/app @react-native-firebase/messaging)
//
// Your ZabPush server: just the host name (no scheme), with secure: true for wss://.
import React, { useCallback, useEffect, useState } from 'react';
import { Button, FlatList, Platform, SafeAreaView, Text, TouchableOpacity, View } from 'react-native';
import { useChannel, useZabPush } from 'zabpush-react-native';
const HOST = 'cloud-zabpush.zabsys.com';
const AUTH_URL = 'https://api.example.com/zabpush/auth'; // YOUR backend: checks the user, returns the signature
const USER = { id: 'user-42', token: 'YOUR_SESSION_TOKEN' }; // from your login
export default function App() {
const [items, setItems] = useState([]); // { id, title, body, read }
const [unread, setUnread] = useState(0);
const { client, state } = useZabPush('APP_KEY', {
host: HOST,
secure: true, // wss://
userId: USER.id,
clientName: 'rn-example',
// Called for every private-* channel, with the current socket id. YOUR backend decides who may join.
authorize: async (socketId, channel) => {
const r = await fetch(AUTH_URL, {
method: 'POST',
headers: { Authorization: `Bearer ${USER.token}`, 'Content-Type': 'application/x-www-form-urlencoded' },
body: `socket_id=${encodeURIComponent(socketId)}&channel=${encodeURIComponent(channel)}`,
});
if (!r.ok) throw new Error('not allowed');
return r.text();
},
});
const toItem = (m, read) => ({ id: m.id, title: m.data?.title ?? m.event, body: m.data?.body ?? '', read });
// Live pushes on a public channel and on this user's private channel ("delivered" receipts are automatic).
const onPush = useCallback((data, msg) => {
setItems((prev) => [toItem(msg, false), ...prev]);
setUnread((n) => n + 1);
}, []);
useChannel(client, 'news', '*', onPush);
useChannel(client, `private-user-${USER.id}`, '*', onPush);
// History from the server inbox, loaded every time we (re)connect.
useEffect(() => {
if (state !== 'connected') return;
client.inbox('news', 50)
.then((inbox) => { setItems(inbox.messages.map((m) => toItem(m, m.read))); setUnread(inbox.unread); })
.catch(() => {}); // offline right now: try again on the next connect
}, [state, client]);
const open = (item) => {
client.clicked(item.id); // also marks it read
if (!item.read) setUnread((n) => Math.max(0, n - 1));
setItems((prev) => prev.map((i) => (i.id === item.id ? { ...i, read: true } : i)));
};
const readAll = () => { client.markAllRead('news'); setItems((p) => p.map((i) => ({ ...i, read: true }))); setUnread(0); };
// OPTIONAL: Firebase push for when the app is closed (see the "Offline push" page).
// useEffect(() => {
// if (!client) return;
// const messaging = require('@react-native-firebase/messaging').default;
// (async () => { await messaging().requestPermission(); client.registerDevice(await messaging().getToken(), Platform.OS); })();
// const off = messaging().onTokenRefresh((t) => client.registerDevice(t, Platform.OS));
// messaging().onNotificationOpenedApp((m) => client.clicked(Number(m.data.id)));
// return off;
// }, [client]);
return (
<SafeAreaView style={{ flex: 1 }}>
{state !== 'connected' && (
<View style={{ backgroundColor: '#fee2e2', padding: 8 }}>
<Text style={{ color: '#991b1b', textAlign: 'center' }}>{state}…</Text>
</View>
)}
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 }}>
<Text style={{ fontSize: 22, fontWeight: '700' }}>Notifications ({unread})</Text>
<Button title="Mark all read" onPress={readAll} />
</View>
<FlatList
data={items}
keyExtractor={(i) => String(i.id)}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => open(item)}>
<View style={{ padding: 14, backgroundColor: item.read ? '#fff' : '#fff1f2', borderBottomWidth: 1, borderColor: '#eee' }}>
<Text style={{ fontWeight: '600' }}>{item.title}</Text>
{item.body ? <Text>{item.body}</Text> : null}
</View>
</TouchableOpacity>
)}
ListEmptyComponent={<Text style={{ textAlign: 'center', marginTop: 40, color: '#888' }}>No notifications yet</Text>}
/>
</SafeAreaView>
);
}Run it
npm install ./sdk/js ./sdk/react-native @react-native-async-storage/async-storage @react-native-community/netinfo
npx react-native run-android # or: run-iosWhat you should see
- No banner once connected; a red banner while connecting or reconnecting.
- A test push sent from your customer panel appears at the top of the list; tapping it clears the highlight and the count.
- Switch airplane mode on and off: the banner appears, then disappears, and pushes sent meanwhile are filled in from the inbox.
This screen is built on the tested JavaScript client. Run it on a device or emulator, and tell us what you see.
Configuration
All options of the JavaScript client apply. Differences in React Native:
| Option | Default here |
|---|---|
platform | Platform.OS (ios / android) |
storage | AsyncStorage when installed (async storage is supported) |
host | no page host exists: always set it |
useZabPush recreates the client when appKey, host, userId or secure change, and closes it on unmount.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorize, no backend call. |
| Private | private-... | The optional authorize callback, which asks your backend for a signature (see Private channels). |
const kHost = 'cloud-zabpush.zabsys.com';
const kAppKey = 'APP_KEY';
const kChannel = 'app-1';
const kUserId = 'user-42';
const { client } = useZabPush(kAppKey, { host: kHost, secure: true, userId: kUserId }); // no authorize: public channel
const { messages } = useChannel(client, kChannel); // re-renders on every message
client.subscribe('orders').bind('shipped', (data) => console.log(data));
client.unsubscribe('orders');
client.unsubscribeAll(); // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that throws is logged and skipped: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
const { client } = useZabPush('APP_KEY', {
host: 'cloud-zabpush.zabsys.com', secure: true, userId: user.id,
authorize: async (socketId, channel) => {
const r = await fetch('https://api.example.com/zabpush/auth', {
method: 'POST',
headers: { Authorization: `Bearer ${authToken}`, 'Content-Type': 'application/x-www-form-urlencoded' },
body: `socket_id=${encodeURIComponent(socketId)}&channel=${encodeURIComponent(channel)}`,
});
if (!r.ok) throw new Error('not allowed');
return r.text();
},
});
useChannel(client, `private-user-${user.id}`, '*', (data) => console.log(data));Receipts and inbox
client.read(msg.id);
client.clicked(msg.id);
client.markAllRead('news');
const { messages, unread } = await client.inbox('news');Stay connected in the background
The React Native layer already reconnects the moment the app returns to the foreground or the network comes back, and replays what was missed. For a connection that survives while the app is in the background:
Android: needs a native foreground service. Use a library that provides one, such as @notifee/react-native (notifee.displayNotification with asForegroundService: true and registerForegroundService), and keep the ZabPush client in a module that stays loaded. Declare the specialUse foreground-service type and the permissions as described on the Android page.
iOS: the system suspends the app a few seconds after it leaves the foreground and cannot be asked to do otherwise. Use the FCM/APNs fallback in Offline push; the replay on return fills in the gap.
Try the foreground service on your own devices. The reconnect-on-foreground behaviour is part of the JavaScript client.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your client.subscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | state: connecting, connected, reconnecting or disconnected |
| Is it live right now? | client.isConnected |
| Which channels am I on? | client.subscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
const { client, state } = useZabPush(kAppKey, { host: kHost, secure: true, userId: kUserId });
state // 'connecting' | 'connected' | 'reconnecting' | 'disconnected' (re-renders on every change)
client.isConnected // true while live
client.subscribedChannels() // ['app-1', 'news']: the channels you are subscribed to right now
client.socketId // id of the current connectionThe list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | client.reconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | client.close() disconnects for good: no more retries. To connect again create a new client. |
client.reconnectNow(); // force a retry now (the SDK already does it when the app returns or the network comes back)
client.close(); // disconnect for good, for example on logout. useZabPush closes it for you when the component unmounts.If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Foreground, background and network
- When the app returns to the foreground (
AppState = active) and the client is not connected, it reconnects immediately. - With NetInfo installed, it also reconnects the moment the network comes back.
- While in the background the socket may be suspended by the OS: that is what FCM covers. Missed messages are replayed when the app is active again.
API reference
| Export | Description |
|---|---|
createZabPush(appKey, options?) | Creates a client with the React Native defaults and lifecycle wiring. close() also removes the listeners. |
useZabPush(appKey, options?) | Hook returning { client, state }. client is null on the first render. |
useChannel(client, channel, event, handler) | Subscribes while the component is mounted. The latest handler is always used. |
The client object has every method of the JavaScript API.
Test your integration
- Run the app and watch the title change to connected.
- Send a test push from your customer panel to your channel: the item appears in the list.
- Turn Wi-Fi off, send a push, turn it on: the push arrives after the reconnect.
- Background the app, send a push (with FCM configured), and tap the notification.
Go-live checklist
secure: truewith your real domain.userIdis your logged-in user's id; the hook recreates the client when it changes.- FCM token registration tested on a real device for both platforms.
Troubleshooting
The user id changes on every app launch
pod install on iOS). Install it, or pass your own userId.Handlers fire twice in development
useChannel cleans up with unbind, so this resolves itself; if you call subscribe().bind() manually, unbind in your effect cleanup.
Flutter / Dart
One codebase for Android, iOS, web, macOS, Windows and Linux. The only dependency is web_socket_channel.
Overview
The Flutter SDK is a plain Dart package: subscribe() returns a Stream of messages, connection changes arrive on a state stream, and the client reconnects, replays and acknowledges for you. It also runs in pure Dart programs (command-line tools, servers that only receive).
The Dart core passes the analyzer and a live end-to-end run (connect, receive, read receipt, inbox) and survives a server restart. The Flutter example screen itself was not launched on a device.
Requirements
- Dart 3.0+ (Flutter 3.10+). Android, iOS, web, macOS, Windows and Linux are supported.
- Android: the
INTERNETpermission (Flutter adds it for debug builds; add it to the main manifest for release). - For offline pushes:
firebase_messaging(see below).
Installation
dependencies:
zabpush:
path: ../zabpush/sdk/flutter # path to the package's sdk/flutter folder
shared_preferences: ^2.2.0 # optional: to keep a user id across launchesflutter pub getQuick start
import 'package:zabpush/zabpush.dart';
final zp = ZabPush(
'APP_KEY',
const ZabPushOptions(
host: 'cloud-zabpush.zabsys.com', // your ZabPush server: host name only
secure: true,
userId: 'user-42', // YOUR id for this user
clientName: 'my-app',
platform: 'android',
),
);
zp.state.listen((s) => print('connection: ${s.status.name}'));
zp.subscribe('news').listen((m) {
print('${m.event}: ${m.data}');
zp.read(m.id); // tell the server the user saw it ("delivered" is automatic)
});class _PushScreenState extends State<PushScreen> {
late final ZabPush zp;
final messages = <PushMessage>[];
PushStatus status = PushStatus.connecting;
@override
void initState() {
super.initState();
zp = ZabPush('APP_KEY', const ZabPushOptions(host: 'cloud-zabpush.zabsys.com', secure: true, userId: 'user-42'));
zp.state.listen((s) => setState(() => status = s.status));
zp.subscribe('news').listen((m) { setState(() => messages.insert(0, m)); zp.read(m.id); });
}
@override
void dispose() { zp.close(); super.dispose(); }
// build(): ListView of messages, title 'ZabPush: ${status.name}' (full file: sdk/flutter/example/main.dart)
}Complete example
A complete app: live pushes on a public channel and the user's private channel, server inbox, unread badge, tap-to-click receipts, a connection banner, and reconnect when the app returns to the foreground.
Dependencies
dependencies:
flutter: { sdk: flutter }
zabpush: { path: ../zabpush/sdk/flutter } # the package's sdk/flutter folder
http: ^1.2.0 # only for the private-channel signature request// Complete Flutter app: live pushes, server inbox, unread badge, read / click receipts, a private channel,
// reconnect when the app returns to the foreground, and a connection banner.
//
// pubspec.yaml:
// dependencies:
// flutter: { sdk: flutter }
// zabpush: { path: ../zabpush/sdk/flutter }
// http: ^1.2.0
//
// Your ZabPush server: just the host name (no scheme), with secure: true for wss://.
// Pushes while the app is closed: add firebase_messaging as shown on the "Background delivery" page and call zp.registerDevice(token, platform).
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:zabpush/zabpush.dart';
const kHost = 'cloud-zabpush.zabsys.com';
const kAppKey = 'APP_KEY';
const kAuthUrl = 'https://api.example.com/zabpush/auth'; // YOUR backend: checks the user, returns the signature
const kChannel = 'news'; // the channel to listen to: publish to this name
const kUserId = 'user-42'; // from your login
const kUserToken = 'YOUR_SESSION_TOKEN';
void main() => runApp(const MaterialApp(home: PushScreen()));
class Item {
Item(this.id, this.title, this.body, this.read);
final int id;
final String title, body;
bool read;
}
class PushScreen extends StatefulWidget {
const PushScreen({super.key});
@override
State<PushScreen> createState() => _PushScreenState();
}
class _PushScreenState extends State<PushScreen> with WidgetsBindingObserver {
late final ZabPush zp;
final items = <Item>[];
int unread = 0;
PushStatus status = PushStatus.connecting;
bool inboxLoaded = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
zp = ZabPush(
kAppKey,
ZabPushOptions(
host: kHost,
secure: true, // wss://
userId: kUserId,
clientName: 'flutter-example',
platform: 'android',
// OPTIONAL: only needed because this example also joins a private-* channel. A client that uses public
// channels only is just ZabPushOptions(host:, secure:, userId:). YOUR backend decides who may join.
authorize: (socketId, channel) async {
final r = await http.post(
Uri.parse(kAuthUrl),
headers: {'Authorization': 'Bearer $kUserToken'},
body: {'socket_id': socketId, 'channel': channel},
);
if (r.statusCode != 200) throw Exception('not allowed');
return r.body;
},
),
);
zp.state.listen((s) {
setState(() => status = s.status);
if (s.status == PushStatus.connected && !inboxLoaded) {
inboxLoaded = true;
_loadInbox();
}
});
// Live pushes on a public channel and on this user's private channel ("delivered" receipts are automatic).
for (final channel in [kChannel]) {
zp.subscribe(channel).listen((m) {
final d = m.data is Map ? m.data as Map : const {};
setState(() {
items.insert(
0,
Item(m.id, '${d['title'] ?? m.event}', '${d['body'] ?? ''}', false),
);
unread++;
});
});
}
}
Future<void> _loadInbox() async {
try {
final inbox = await zp.inbox(
kChannel,
limit: 50,
); // history kept by the server for this user
setState(() {
items
..clear()
..addAll(
(inbox['messages'] as List).map((m) {
final d = m['data'] is Map ? m['data'] as Map : const {};
return Item(
m['id'] as int,
'${d['title'] ?? m['event']}',
'${d['body'] ?? ''}',
m['read'] == true,
);
}),
);
unread = inbox['unread'] as int;
});
} catch (_) {
inboxLoaded = false; // offline right now: try again on the next connect
}
}
void _open(Item item) {
zp.clicked(item.id); // also marks it read
if (!item.read) {
setState(() {
item.read = true;
unread = unread > 0 ? unread - 1 : 0;
});
}
}
// Mobile OSes suspend sockets in the background: reconnect the moment the app is visible again.
@override
void didChangeAppLifecycleState(AppLifecycleState s) {
if (s == AppLifecycleState.resumed && zp.status != PushStatus.connected) {
zp.reconnectNow();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
zp.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Notifications ($unread)'),
actions: [
TextButton(
onPressed: () {
zp.markAllRead(kChannel);
setState(() {
for (final i in items) {
i.read = true;
}
unread = 0;
});
},
child: const Text('Mark all read'),
),
],
),
body: Column(
children: [
if (status != PushStatus.connected)
Container(
width: double.infinity,
color: const Color(0xFFFEE2E2),
padding: const EdgeInsets.all(8),
child: Text(
'${status.name}…',
textAlign: TextAlign.center,
style: const TextStyle(color: Color(0xFF991B1B)),
),
),
Expanded(
child: items.isEmpty
? const Center(child: Text('No notifications yet'))
: ListView.builder(
itemCount: items.length,
itemBuilder: (_, i) {
final it = items[i];
return ListTile(
tileColor: it.read ? null : const Color(0xFFFFF1F2),
title: Text(
it.title,
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: it.body.isEmpty ? null : Text(it.body),
onTap: () => _open(it),
);
},
),
),
],
),
);
}
}Or: a pure-Dart program (no Flutter, no device)
Dart command-line tools and servers can receive too. This is the program used to test the package against a live server.
// Pure-Dart end-to-end check (no Flutter needed):
// ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=... ZP_ID=1 ZP_SECRET=... dart run example/smoke.dart
// Subscribes, publishes through the REST API, and expects the message, a read receipt and the inbox.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:zabpush/zabpush.dart';
Future<void> main() async {
final env = Platform.environment;
final host = env['ZP_HOST'] ?? '%s';
// https/wss for a real domain; plain http/ws only when you point it at a local server
final secure =
env['ZP_SECURE'] == '1' ||
!(host.startsWith('localhost') || host.startsWith('127.'));
final key = env['ZP_KEY'], id = env['ZP_ID'], secret = env['ZP_SECRET'];
if (key == null || id == null || secret == null) {
stderr.writeln('set ZP_KEY, ZP_ID and ZP_SECRET');
exit(2);
}
final run = DateTime.now().millisecondsSinceEpoch.toRadixString(36);
final channel = 'smoke-dart-$run';
final connected = Completer<void>();
final got = Completer<PushMessage>();
final zp = ZabPush(
key,
ZabPushOptions(
host: host,
secure: secure,
userId: 'smoke-dart-$run',
clientName: 'dart-smoke',
platform: 'dart',
),
);
zp.state.listen((s) {
print('state: ${s.status.name}');
if (s.status == PushStatus.connected && !connected.isCompleted)
connected.complete();
});
zp.subscribe(channel).listen((m) {
zp.read(m.id);
if (!got.isCompleted) got.complete(m);
});
Never fail(String why) {
print('FAIL $why');
exit(1);
}
await connected.future.timeout(
const Duration(seconds: 8),
onTimeout: () => fail('never connected'),
);
await Future<void>.delayed(
const Duration(milliseconds: 500),
); // let the subscription be accepted
// Your backend normally does this (see the server SDKs); plain HTTP here to keep the example self-contained.
final http = HttpClient();
final req = await http.postUrl(
Uri.parse('${secure ? 'https' : 'http'}://$host/api/v1/apps/$id/events'),
);
req.headers.set('Authorization', 'Bearer $secret');
req.headers.contentType = ContentType.json;
req.write(
jsonEncode({
'channel': channel,
'event': 'hello',
'data': {'n': 1},
}),
);
final res = await req.close();
if (res.statusCode != 200) fail('publish failed: HTTP ${res.statusCode}');
await res.drain<void>();
final m = await got.future.timeout(
const Duration(seconds: 8),
onTimeout: () => fail('message did not arrive'),
);
print('ok received ${m.event} ${jsonEncode(m.data)}');
await Future<void>.delayed(
const Duration(milliseconds: 400),
); // let the receipt reach the server
final inbox = await zp.inbox(channel);
final msgs = inbox['messages'] as List;
if (msgs.isEmpty) fail('inbox is empty');
print('ok inbox: ${msgs.length} message(s), ${inbox['unread']} unread');
zp.close();
http.close();
print('PASS dart');
exit(0);
}Run it
flutter pub get && flutter run # the app
ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=APP_KEY ZP_ID=1 ZP_SECRET=APP_SECRET dart run example/smoke.dart # the pure-Dart checkWhat the pure-Dart program prints
state: connected
ok received hello {"n":1}
ok inbox: 1 message(s), 0 unread
PASS dartThe package was run against a live server (connecting, receiving, receipts, inbox, reconnect). This screen passes flutter analyze with no issues, was built as an Android app and run on an Android 16 emulator: it connected, received pushes, and after the app had been in the background it reconnected on return and replayed every push it missed.
Configuration
| Option | Default | Description |
|---|---|---|
host | required | Server address, e.g. cloud-zabpush.zabsys.com or cloud-zabpush.zabsys.com. |
secure | false | Use wss://. Always true in production. |
userId | random per run | Your unique id for this user. Persist it if you do not have one. |
clientName | empty | Label shown in your customer panel. |
platform | app | Platform label shown in your customer panel. |
reconnect | true | Reconnect automatically. |
reconnectDelay | 500 ms | First retry; doubles each attempt with jitter. |
maxReconnectDelay | 30 s | Backoff ceiling. |
heartbeatInterval | 15 s | Ping period. |
heartbeatTimeout | 10 s | Extra silence tolerated before reconnecting. |
autoAck | true | Send "delivered" receipts automatically. |
authorize | null | Optional. Only for private-* channels: Future<String> Function(String socketId, String channel) for private channels. |
final prefs = await SharedPreferences.getInstance();
final id = prefs.getString('zp_user') ?? 'u-${DateTime.now().microsecondsSinceEpoch}';
await prefs.setString('zp_user', id);
final zp = ZabPush('APP_KEY', ZabPushOptions(host: 'cloud-zabpush.zabsys.com', secure: true, userId: id));Receiving messages
subscribe(channel) returns a broadcast Stream<PushMessage>, so you can listen from several places, use StreamBuilder, or filter by event.
zp.subscribe('orders')
.where((m) => m.event == 'order.shipped')
.listen((m) => showToast(m.data['title']));
StreamBuilder<PushMessage>(
stream: zp.subscribe('news'),
builder: (context, snap) => Text(snap.hasData ? '${snap.data!.data}' : 'waiting...'),
);
zp.unsubscribe('orders'); // closes that channel's streamPushMessage has id (0 means live-only), event, channel and data (decoded JSON: a Map, List, String, number or bool). Exceptions in malformed frames are ignored; the connection stays up.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorize, no backend call. |
| Private | private-... | The optional authorize callback, which asks your backend for a signature (see Private channels). |
const kHost = 'cloud-zabpush.zabsys.com';
const kAppKey = 'APP_KEY';
const kChannel = 'app-1'; // the channel name you publish to (any name; no setup on the server)
const kUserId = 'user-42'; // YOUR id for this user
// only the key and the host are needed for a public channel: no authorize
final zp = ZabPush(kAppKey, const ZabPushOptions(host: kHost, secure: true, userId: kUserId));
final sub = zp.subscribe(kChannel).listen((m) => print(m.data)); // Stream<PushMessage>
zp.subscribe('news').listen((m) => print(m.data)); // as many channels as you like, one connection
zp.unsubscribe('news'); // closes that channel's stream and tells the server
// or just cancel your own listener: sub.cancel() (the channel stays subscribed for other listeners)
zp.unsubscribeAll(); // leave every channel at once: all their streams close, the connection stays openAfter every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. The SDK never throws into your app for connection or subscription problems. An exception thrown inside your own listen callback is handled by Dart's normal zone rules (Flutter reports it and keeps running); it does not stop the SDK, the other channels or the connection. Add onError or a try/catch inside the callback if you want to handle it yourself. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
final zp = ZabPush('APP_KEY', ZabPushOptions(
host: 'cloud-zabpush.zabsys.com', secure: true, userId: 'user-42',
authorize: (socketId, channel) async {
final r = await http.post(
Uri.parse('https://api.example.com/zabpush/auth'),
headers: {'Authorization': 'Bearer $authToken'},
body: {'socket_id': socketId, 'channel': channel},
);
if (r.statusCode != 200) throw Exception('not allowed');
return r.body;
},
));
zp.subscribe('private-user-42').listen((m) => print(m.data));Not using private channels? Then leave authorize out altogether: ZabPush('APP_KEY', ZabPushOptions(host: ..., secure: true, userId: ...)) is the whole setup for public channels.
Your backend endpoint is shown on the Node.js, Python, PHP and other server pages.
Receipts and inbox
zp.read(m.id);
zp.clicked(m.id);
zp.markAllRead('news');
final inbox = await zp.inbox('news', limit: 50); // Map: {'messages': [...], 'unread': n}
final unread = inbox['unread'] as int;
for (final item in inbox['messages'] as List) { print('${item['id']} read=${item['read']}'); }Stay connected in the background
The Dart package is pure Dart, so it does not know about the Flutter app lifecycle. Two small pieces of your own code cover it.
1. Reconnect when the app returns (all platforms)
class _AppState extends State<App> with WidgetsBindingObserver {
@override
void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); }
@override
void didChangeAppLifecycleState(AppLifecycleState s) {
// coming back to the foreground: do not wait for the next retry
if (s == AppLifecycleState.resumed && zp.status != PushStatus.connected) zp.reconnectNow();
}
@override
void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); }
// ...
}2. Keep the socket open while in the background
Android: needs a foreground service, which has to be native code. Use a plugin that provides one, such as flutter_foreground_task, and create the ZabPush client inside its task handler so it lives as long as the service. The Android page describes what the service must declare (specialUse type and the permissions).
iOS: the system suspends the app a few seconds after it leaves the foreground. This cannot be avoided; use the FCM/APNs fallback described in Offline push, and the replay on resumed above fills in whatever was missed.
On an Android 16 emulator, a Flutter app without a foreground service lost its connection within seconds of going to the background. On return, the resumed handler reconnected and all missed pushes were replayed and acknowledged.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.subscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.status: connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.isConnected |
| Which channels am I on? | zp.subscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.status // PushStatus.connecting | connected | reconnecting | disconnected
zp.isConnected // true while live
zp.socketId // id of the current connection (null while disconnected)
zp.subscribedChannels() // ['app-1', 'news']: the channels you are subscribed to right now
// be told about every change instead of asking
zp.state.listen((s) => print('${s.status} attempt=${s.attempt} retryIn=${s.retryIn}'));The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.reconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | zp.close() disconnects for good: no more retries. To connect again create a new client. |
// watch the connection (also works for a "reconnecting..." banner)
zp.state.listen((s) => print('${s.status} attempt=${s.attempt} retryIn=${s.retryIn}'));
zp.reconnectNow(); // do not wait for the next retry (call it from the resumed handler)
zp.close(); // disconnect for good: on logout / dispose(). Ends every stream, no more retries.
// after close() the client is finished: create a new ZabPush to connect again
// (zp.subscribe(...) on a closed client throws a StateError so the mistake is not silent)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
PushStatus | Meaning |
|---|---|
connecting | First attempt. |
connected | Live; subscriptions active; missed messages replayed. |
reconnecting | Trying again after a drop (PushState.attempt). |
disconnected | Lost (PushState.retryIn says when the next try happens) or closed. |
Mobile OSes suspend sockets in the background. Reconnect the moment the app comes back:
class _State extends State<MyApp> with WidgetsBindingObserver {
@override
void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); }
@override
void didChangeAppLifecycleState(AppLifecycleState s) {
if (s == AppLifecycleState.resumed && zp.status != PushStatus.connected) zp.reconnectNow();
}
}
// optional: reconnect as soon as the network returns (package: connectivity_plus)
Connectivity().onConnectivityChanged.listen((_) { if (zp.status != PushStatus.connected) zp.reconnectNow(); });API reference
| Member | Description |
|---|---|
ZabPush(appKey, ZabPushOptions) | Creates the client and connects. |
Stream<PushMessage> subscribe(channel) | Listen to a channel (broadcast stream). |
unsubscribe(channel) | Stop listening and close its stream. |
read(id) · clicked(id) · markAllRead(channel) | Receipts. |
Future<Map> inbox(channel, {limit}) | Server-kept history with read flags and unread. |
registerDevice(token, platform) | FCM token for offline pushes. |
Stream<PushState> state | Connection changes. status, attempt, retryIn. |
status · socketId | Current status and connection id. |
Stream<String> errors | Non-fatal problems as text (for example a private channel without authorize). |
reconnectNow() | Force a reconnect now. |
close() | Disconnect for good: no more reconnecting; every channel stream, state and errors end; waiting inbox() calls fail. Safe to call twice. |
Error handling
- Connection failures never throw into your code: they become
stateevents and are retried. inbox()throwsTimeoutExceptionafter 8 seconds when not connected: usetry/catch.- Non-fatal problems are not thrown: a
private-channel withoutauthorize, or anauthorizethat throws, are reported as text onzp.errors(and in the developer log). The connection and the other channels keep working, and a failed subscription is attempted again after the next reconnect. subscribe()on a client you already closed throws aStateError(create a new client).
Test your integration
cd sdk/flutter
dart pub get
ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=APP_KEY ZP_ID=1 ZP_SECRET=APP_SECRET dart run example/smoke.dart
# -> state: connected / ok received / ok inbox / PASS dart
ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=APP_KEY ZP_ID=1 ZP_SECRET=APP_SECRET dart run example/channels_check.dart
# -> public channel without authorize / private without authorize reported / unsubscribe / close(): PASS dart channelsexample/reconnect.dart prints RECONNECTED after you cut the network for a moment. A test push from your customer panel reaches your running app.
Go-live checklist
secure: truewith your real domain.- A stable
userIdfrom your login orshared_preferences. - FCM token registration tested on a real Android and iOS device; iOS needs the APNs key in Firebase.
- Create the client once (a provider or singleton) and
close()it on logout.
Troubleshooting
Web build fails to connect
secure: true. The same package works on Flutter web.
Android (Kotlin)
A small Kotlin library on OkHttp. Callbacks arrive on the main thread, so you can update views directly.
Overview
The library connects over a WebSocket, detects dead connections with WebSocket pings, reconnects with backoff, replays missed messages, and sends delivery receipts. ZabPushAndroid adds a persistent user id and instant reconnect when the network returns.
Built and run on an Android 16 emulator against a live server. Test on your own devices too, including manufacturer battery managers. For a Kotlin backend use the Java SDK.
Requirements
- Android Studio, minSdk 24, Android Gradle Plugin 9+ (Kotlin is built in; on AGP 8.x add the
org.jetbrains.kotlin.androidplugin to the library module), Java 17. - Permissions:
INTERNET, andACCESS_NETWORK_STATEfor the network helper. - For offline pushes: Firebase Cloud Messaging in your app (and
POST_NOTIFICATIONSon Android 13+).
Installation
include(":zabpush")
project(":zabpush").projectDir = file("../zabpush/sdk/android/zabpush") // the package's library moduledependencies {
implementation(project(":zabpush"))
}<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>Quick start
val zp = ZabPush(
"APP_KEY",
ZabPush.Options(
host = "cloud-zabpush.zabsys.com", // your ZabPush server: host name only
secure = true,
userId = ZabPushAndroid.persistentUserId(this), // or YOUR user id
clientName = "my-app",
onState = { state, _ -> title = "ZabPush: $state" },
),
)
zp.subscribe("news").bind("*") { m ->
textView.text = m.title ?: m.event
zp.read(m.id) // "delivered" is automatic
}Create the client once (for example in your Application class or a singleton) rather than per screen, and call close() on logout.
Complete example
A complete app in four files: an Application class that owns the single connection, an Activity with the live list, inbox, unread count and receipts, the manifest, and an optional Firebase service for pushes while the app is closed. Plain Android views, no extra libraries.
Dependencies
// settings.gradle.kts
include(":zabpush")
project(":zabpush").projectDir = file("../zabpush/sdk/android/zabpush")
// app/build.gradle.kts
dependencies { implementation(project(":zabpush")) }
// optional, for pushes while the app is closed:
// implementation(platform("com.google.firebase:firebase-bom:33.1.0")); implementation("com.google.firebase:firebase-messaging-ktx")package com.example.zabpushdemo
import android.app.Application
import com.zabpush.ZabPush
import com.zabpush.ZabPushAndroid
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* Create the client ONCE for the whole app (an Application subclass), so every screen shares one connection and
* it survives configuration changes. Register this class in AndroidManifest.xml (android:name=".App").
*/
class App : Application() {
lateinit var zp: ZabPush
private set
/** The visible screen, if any. Pushes are received even when there is none (see onCreate). */
var listener: ((ZabPush.Message) -> Unit)? = null
override fun onCreate() {
super.onCreate()
zp = ZabPush(
"APP_KEY",
ZabPush.Options(
host = "cloud-zabpush.zabsys.com", // your ZabPush server (no port, no scheme)
secure = true, // wss://
userId = ZabPushAndroid.persistentUserId(this), // or YOUR logged-in user's id
clientName = "android-example",
// Runs on a background thread, so a blocking call to YOUR backend is fine. YOUR backend decides who may join.
authorize = { socketId, channel -> signViaBackend(socketId, channel) },
),
)
// Subscribe HERE, not in an Activity. When Android kills the process and restarts the foreground service, no
// Activity exists, but Application.onCreate always runs, so the pushes keep arriving (and are acknowledged).
val onPush: (ZabPush.Message) -> Unit = { m -> listener?.invoke(m) }
zp.subscribe("news").bind("*", onPush)
zp.subscribe("private-${zp.userId}").bind("*", onPush)
}
private fun signViaBackend(socketId: String, channel: String): String {
val c = URL("https://api.example.com/zabpush/auth").openConnection() as HttpURLConnection
c.requestMethod = "POST"
c.doOutput = true
c.setRequestProperty("Authorization", "Bearer YOUR_SESSION_TOKEN")
c.outputStream.use {
it.write("socket_id=${URLEncoder.encode(socketId, "UTF-8")}&channel=${URLEncoder.encode(channel, "UTF-8")}".toByteArray())
}
if (c.responseCode != 200) throw IllegalStateException("not allowed")
return c.inputStream.bufferedReader().readText()
}
}package com.example.zabpushdemo
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.TextView
import com.zabpush.ZabPush
import com.zabpush.ZabPushAndroid
import com.zabpush.ZabPushForeground
/**
* Complete screen (plain Activity, no extra libraries): live pushes, server inbox, unread count, read / click receipts,
* a private channel, and instant reconnect when the network returns.
*
* AndroidManifest.xml needs INTERNET + ACCESS_NETWORK_STATE and android:name=".App" (see AndroidManifest.xml).
*/
class MainActivity : Activity() {
private class Item(val id: Long, val title: String, var read: Boolean) {
override fun toString() = (if (read) " " else "• ") + title
}
private val items = ArrayList<Item>()
private lateinit var adapter: ArrayAdapter<Item>
private lateinit var header: TextView
private lateinit var zp: ZabPush
private var stopNetworkWatch: (() -> Unit)? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
zp = (application as App).zp
header = TextView(this).apply { textSize = 18f; setPadding(32, 32, 32, 16) }
val markAll = Button(this).apply {
text = "Mark all read"
setOnClickListener {
zp.markAllRead("news")
items.forEach { it.read = true }
adapter.notifyDataSetChanged(); updateHeader()
}
}
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
val list = ListView(this).apply {
this.adapter = this@MainActivity.adapter
setOnItemClickListener { _, _, pos, _ ->
val item = items[pos]
zp.clicked(item.id) // also marks it read
item.read = true
this@MainActivity.adapter.notifyDataSetChanged(); updateHeader()
}
}
setContentView(LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
addView(header, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addView(markAll)
addView(list, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
})
updateHeader()
// Live pushes on a public channel and on this user's private channel.
// Callbacks run on the main thread, so views can be updated directly. "delivered" receipts are automatic.
// The subscriptions themselves live in App.kt so they also work with no screen open; this screen just listens.
(application as App).listener = { m ->
items.add(0, Item(m.id, m.title ?: m.event, false))
this@MainActivity.adapter.notifyDataSetChanged(); updateHeader()
}
loadInbox()
// Reconnect immediately when the network returns (Wi-Fi back, airplane mode off).
stopNetworkWatch = ZabPushAndroid.reconnectOnNetworkChange(this, zp)
// Stay connected while the app is in the background (shows a small ongoing notification; Android requires it).
// On Android 13+ also ask for POST_NOTIFICATIONS first, otherwise the notification is hidden (the service still runs).
ZabPushForeground.start(this, title = "Connected", text = "Receiving live updates")
}
/** History kept by the server for this user. Retries once connected if we start offline. */
private fun loadInbox() {
zp.inbox("news", 50).whenComplete { inbox, error ->
runOnUiThread {
if (error != null || inbox == null) { header.postDelayed({ loadInbox() }, 3000); return@runOnUiThread }
items.clear()
inbox.messages.forEach { items.add(Item(it.id, it.title ?: it.event, it.read)) }
adapter.notifyDataSetChanged(); updateHeader()
}
}
}
private fun updateHeader() {
val unread = items.count { !it.read }
header.text = "Notifications ($unread unread) • ${zp.state}"
header.setTextColor(if (zp.state == ZabPush.State.CONNECTED) Color.parseColor("#166534") else Color.parseColor("#991B1B"))
}
override fun onDestroy() {
(application as App).listener = null
stopNetworkWatch?.invoke()
super.onDestroy() // the client lives in App; close it on logout with (application as App).zp.close()
}
}<?xml version="1.0" encoding="utf-8"?>
<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" />
<!-- Android 13+: needed to SHOW notifications from Firebase while the app is closed -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Stay connected in the background (ZabPushForeground). The service itself is declared by the library. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<application
android:name=".App"
android:label="ZabPush example"
>
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- OPTIONAL: Firebase push for when the app is closed (see MyFirebaseService.kt) -->
<service android:name=".MyFirebaseService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>package com.example.zabpushdemo
import android.content.Intent
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
/**
* OPTIONAL: pushes for when the app is closed. Needs the Firebase setup from the "Offline push" page
* (google-services.json, the Google services Gradle plugin and implementation("com.google.firebase:firebase-messaging")).
*
* ZabPush sends a notification message: while your app is in the background Android shows it for you. This service only
* keeps the server informed about the device token.
*/
class MyFirebaseService : FirebaseMessagingService() {
/** The token changed (first install, restore, refresh): hand the new one to ZabPush. */
override fun onNewToken(token: String) {
(application as App).zp.registerDevice(token)
}
companion object {
/** Call once after login (and ask for the POST_NOTIFICATIONS permission on Android 13+). */
fun register(app: App) {
FirebaseMessaging.getInstance().token.addOnSuccessListener { app.zp.registerDevice(it) }
}
/**
* Call from your launcher Activity's onCreate/onNewIntent: when the user tapped a notification, Firebase puts the
* data fields (id, channel, event, payload) into the intent extras. Report the click so your customer panel shows it.
*/
fun reportClick(app: App, intent: Intent?) {
intent?.extras?.getString("id")?.toLongOrNull()?.let { app.zp.clicked(it) }
}
}
}What you should see
- The header reads CONNECTED in green; a test push sent from your customer panel appears at the top with a bullet while unread.
- Tapping a row sends a click receipt and clears the bullet. Mark all read clears everything.
- Toggle airplane mode: the header turns red, then green again within seconds, and pushes sent meanwhile are filled in from the inbox.
Built with Android Gradle Plugin 9.1 and Gradle 9.3 and run on an Android 16 emulator against a live server: it connected, received live pushes and acknowledged them, kept receiving with the screen off, after swiping the app away, after the system killed the process, in forced Doze mode, and across airplane mode. The optional Firebase service needs the Firebase library. Test on your own devices too.
Configuration
ZabPush.Options | Default | Description |
|---|---|---|
host | cloud-zabpush.zabsys.com | Server address. |
secure | false | Use wss://. Always true in production. |
userId | random per run | Your user id; or use ZabPushAndroid.persistentUserId(context). |
clientName | empty | Label in your customer panel. |
platform | android | Platform label. |
reconnect | true | Reconnect automatically. |
reconnectDelayMs / maxReconnectDelayMs | 500 / 30000 | Backoff start and ceiling (with jitter). |
heartbeatIntervalMs | 15000 | WebSocket ping period; a missed pong triggers a reconnect. |
autoAck | true | Send "delivered" receipts automatically. |
authorize | null | Optional. Only for private-* channels: (socketId, channel) -> String, called on a background thread. |
onState | null | (State, Map<String, Any?>) -> Unit. |
callbackExecutor | main thread | Where callbacks run. |
Receiving messages
zp.subscribe("orders")
.bind("order.shipped") { m -> notifyUser(m.title ?: "Shipped", m.body ?: "") }
.bind("*") { m -> log(m.event) }
// m: id (0 = live-only), event, channel, data (JSONObject / JSONArray / String / Number), ts, live
val orderId = (m.data as? JSONObject)?.optInt("orderId")
zp.unsubscribe("orders")Callbacks run on the main thread. An exception in one handler is swallowed so it cannot stop the others or the connection.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorize, no backend call. |
| Private | private-... | The optional authorize callback, which asks your backend for a signature (see Private channels). |
val kHost = "cloud-zabpush.zabsys.com"
val kAppKey = "APP_KEY"
val kChannel = "app-1" // the channel name you publish to
val zp = ZabPush(kAppKey, ZabPush.Options(host = kHost, secure = true, userId = ZabPushAndroid.persistentUserId(this)))
zp.subscribe(kChannel).bind("*") { m -> println(m.data) } // main thread, no authorize needed
zp.subscribe("news").bind("*") { m -> println(m.data) } // as many channels as you like, one connection
zp.unsubscribe("news") // stop listening to one channel
zp.unsubscribeAll() // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that throws is caught and skipped: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
val zp = ZabPush("APP_KEY", ZabPush.Options(
host = "cloud-zabpush.zabsys.com", secure = true, userId = user.id,
// runs on a background thread, so a blocking call to YOUR backend is fine
authorize = { socketId, channel -> backend.sign(socketId, channel, userToken) },
))
zp.subscribe("private-user-${user.id}").bind("*") { println(it.data) }Your backend endpoint: see the Java, Node.js, Python or PHP pages.
Receipts and inbox
zp.read(m.id)
zp.clicked(m.id) // e.g. when the user taps the notification
zp.markAllRead("news")
zp.inbox("news", 50).thenAccept { inbox ->
runOnUiThread { badge.text = inbox.unread.toString() } // inbox.messages: List<ZabPush.Message>
}inbox() returns a CompletableFuture that fails after 8 seconds if you are offline.
Stay connected in the background
Android stops background apps after a short while. The only reliable way to keep the socket open is a foreground service: Android requires it to show a small ongoing notification, and in return keeps your process alive. The SDK ships one, ZabPushForeground. Your ZabPush client stays in your Application class as before; the service only keeps the process running.
// from an Activity, while the app is visible (Android 12+ will not start one from the background)
ZabPushForeground.start(this, title = "Connected", text = "Receiving live updates")
// when the user logs out, or turns live updates off
ZabPushForeground.stop(this)
// optional, once, after explaining why: stop manufacturers from killing the app
ZabPushForeground.requestBatteryOptimizationExemption(this)Manifest
The library declares the service. You add the permissions (they are already in the example's manifest):
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- Android 13+: ask at runtime or the notification is hidden -->With the service running the app stays connected on Wi-Fi and mobile data and pushes arrive in under a second. The service holds a partial wake lock and a Wi-Fi lock so the heartbeat keeps firing with the screen off (without them the CPU sleeps, the server drops the silent connection after 40 seconds and the app reconnects over and over). Doze is Android's deep sleep for a still phone with the screen off. On an Android 16 emulator in forced Doze the app still received a push within seconds, but real phones and manufacturers differ, so keep the notification path (see Push when the app is closed) for pushes that must arrive.
If Android kills the process, it restarts the service and your Application, but there is no Activity. Pushes only keep arriving if the subscriptions are created in Application.onCreate. The example does this and lets the visible screen listen through App.listener. When the app was rebuilt with the subscription in the Activity, a push sent after a system kill was not delivered.
Good to know
- The notification is required by Android and cannot be hidden. The channel is the lowest importance, so it has no sound and no status-bar icon; users can still switch it off in system settings.
- The service uses type
specialUsebecausedataSyncis stopped after 6 hours on Android 15. Google Play asks you to explain it in the Console: "Keeps a WebSocket open to receive live messages the user asked for." Only enable it for users who want live updates. - It costs some battery, because the radio stays awake for the heartbeat. Make it a setting rather than forcing it on everyone.
On an Android 16 emulator with the screen off, after swiping the app away, after killing the process (the service restarted and the app reconnected on its own), in forced Doze and with airplane mode on and off: every push was received and acknowledged. Test on your own devices too.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.subscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.state: connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.isConnected |
| Which channels am I on? | zp.subscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.state // State.CONNECTING | CONNECTED | RECONNECTING | DISCONNECTED
zp.isConnected // true while live
zp.socketId // id of the current connection (null while disconnected)
zp.subscribedChannels() // ["app-1", "news"]: the channels you are subscribed to right now
// be told about every change instead of asking: Options(onState = { state, info -> ... })The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.reconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | zp.close() disconnects for good: no more retries. To connect again create a new client. |
zp.reconnectNow() // force a retry now (for example when the connectivity callback fires)
zp.close() // disconnect for good: on logout. No more retries.
// to connect again later, create a new ZabPush(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
// Reconnect immediately when a network becomes available (Wi-Fi back, airplane mode off)
val stopWatching = ZabPushAndroid.reconnectOnNetworkChange(this, zp)
// onDestroy / logout: stopWatching(); zp.close()State | Meaning |
|---|---|
CONNECTING | First attempt. |
CONNECTED | Live; subscriptions active; missed messages replayed. |
RECONNECTING | Retrying after a drop. |
DISCONNECTED | Lost (info contains retryInMs) or closed. |
Android may stop your process in the background, which ends the socket. That is what FCM covers; missed messages are replayed when the app reconnects.
API reference
| Member | Description |
|---|---|
ZabPush(appKey, options) | Creates the client and connects. |
subscribe(channel): Channel | Then .bind(event) { message -> } (use "*" for all events). |
unsubscribe(channel) | Stop listening. |
read(id) · clicked(id) · markAllRead(channel) | Receipts. |
inbox(channel, limit): CompletableFuture<Inbox> | Inbox.messages and Inbox.unread. |
registerDevice(fcmToken, platform) | FCM token for offline pushes. |
reconnectNow() · close() | Reconnect now / disconnect for good. |
userId · state · socketId | Read-only properties. |
ZabPushAndroid.persistentUserId(context) | User id stored in SharedPreferences. |
ZabPushAndroid.reconnectOnNetworkChange(context, client) | Returns a function that stops listening. |
Test your integration
- Build the example
sdk/android/example/MainActivity.ktinto a test app and run it. - The title should read CONNECTED. Send a test push from your customer panel to the
newschannel: the line appears in the list. - Switch airplane mode on and off: the state should return to CONNECTED within seconds, and a push sent meanwhile is replayed.
Go-live checklist
secure = trueand a real domain.- One shared client; a stable
userIdfrom your login. - FCM token registration and notification permission tested on a real device.
- ProGuard/R8: no extra rules are needed for OkHttp 4; keep your own model classes if you parse
datawith reflection.
Troubleshooting
UI updates crash with "CalledFromWrongThreadException"
callbackExecutor, post UI work to the main looper yourself.
iOS / macOS (Swift)
A Swift Package with no third-party dependencies, built on URLSessionWebSocketTask. iOS, macOS, tvOS and watchOS.
Overview
The client connects over a WebSocket, detects dead links with WebSocket pings, reconnects with backoff and jitter, replays missed messages and sends delivery receipts. Callbacks arrive on the main queue by default, so SwiftUI and UIKit code can update views directly. This one package also covers the macOS category in your customer panel.
Add it to Xcode, build, and run the example ContentView.swift against your server first.
Requirements
- Xcode 13.2+ (Swift 5.5), iOS 13+, macOS 10.15+, tvOS 13+, watchOS 6+.
- Offline pushes: Firebase (the FCM token) and an APNs key uploaded in the Firebase console. ZabPush sends through FCM; it does not talk to APNs directly.
Installation
In Xcode: File → Add Package Dependencies → Add Local… and choose the package's sdk/ios folder. Or in a Package.swift:
dependencies: [ .package(path: "../zabpush/sdk/ios") ],
targets: [ .target(name: "MyApp", dependencies: [ .product(name: "ZabPush", package: "ios") ]) ]Quick start
import ZabPush
var options = ZabPush.Options(host: "cloud-zabpush.zabsys.com", secure: true,
userId: ZabPush.persistentUserId(), // or YOUR user id
clientName: "my-app")
options.onState = { state, _ in print("connection:", state.rawValue) }
let zp = ZabPush(appKey: "APP_KEY", options: options)
zp.subscribe("news").bind("*") { message in
print(message.title ?? message.event, message.body ?? "")
zp.read(message.id) // "delivered" is automatic
}Keep a strong reference (for example in your app's model or an ObservableObject); the client disconnects when it is deallocated.
Complete example
A complete SwiftUI app in four files: the app entry point (one connection for the whole app), a model that owns the client, the screen with live list, inbox, unread count and receipts, and an optional Firebase delegate for pushes while the app is closed.
Add the package
Xcode: File > Add Package Dependencies > Add Local... > choose the package's sdk/ios folder
(optional, for pushes while the app is closed: add the Firebase iOS SDK the same way)import SwiftUI
/// App entry point: ONE PushModel (and so one ZabPush connection) for the whole app.
@main
struct ZabPushDemoApp: App {
@StateObject private var model = PushModel()
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(model)
}
// Reconnect immediately when the app returns to the foreground.
.onChange(of: scenePhase) { phase in
if phase == .active { model.appBecameActive() }
}
}
}import Foundation
import ZabPush
/// Owns the ZabPush client and publishes state for SwiftUI. Create ONE instance for the app (see ZabPushDemoApp.swift).
final class PushModel: ObservableObject {
struct Item: Identifiable {
let id: Int64
let title: String
let body: String
var read: Bool
}
@Published var items: [Item] = []
@Published var unread = 0
@Published var state = "connecting"
private var zp: ZabPush!
private var inboxLoaded = false
init() {
var options = ZabPush.Options(host: "cloud-zabpush.zabsys.com", // your ZabPush server (no port, no scheme)
secure: true, // wss://
userId: ZabPush.persistentUserId(), // or YOUR logged-in user's id
clientName: "ios-example")
// Callbacks arrive on the main queue, so @Published properties can be changed directly.
options.onState = { [weak self] state, _ in
guard let self = self else { return }
self.state = state.rawValue
if state == .connected && !self.inboxLoaded { self.inboxLoaded = true; self.loadInbox() }
}
// Called for every private-* channel with the current socket id. YOUR backend decides who may join.
options.authorize = { socketId, channel, completion in
var req = URLRequest(url: URL(string: "https://api.example.com/zabpush/auth")!)
req.httpMethod = "POST"
req.setValue("Bearer YOUR_SESSION_TOKEN", forHTTPHeaderField: "Authorization")
req.httpBody = "socket_id=\(socketId)&channel=\(channel)".data(using: .utf8)
URLSession.shared.dataTask(with: req) { data, response, error in
if let data = data, (response as? HTTPURLResponse)?.statusCode == 200, let sig = String(data: data, encoding: .utf8) {
completion(.success(sig))
} else {
completion(.failure(error ?? URLError(.userAuthenticationRequired)))
}
}.resume()
}
zp = ZabPush(appKey: "APP_KEY", options: options)
// Live pushes on a public channel and on this user's private channel ("delivered" receipts are automatic).
let onPush: (ZabPush.Message) -> Void = { [weak self] m in
self?.items.insert(Item(id: m.id, title: m.title ?? m.event, body: m.body ?? "", read: false), at: 0)
self?.unread += 1
}
zp.subscribe("news").bind("*", onPush)
zp.subscribe("private-\(zp.userId)").bind("*", onPush)
}
/// History kept by the server for this user.
private func loadInbox() {
zp.inbox("news", limit: 50) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let inbox):
self.items = inbox.messages.map { Item(id: $0.id, title: $0.title ?? $0.event, body: $0.body ?? "", read: $0.read) }
self.unread = inbox.unread
case .failure:
self.inboxLoaded = false // offline right now: try again on the next connect
}
}
}
func open(_ item: Item) {
zp.clicked(item.id) // also marks it read
if let i = items.firstIndex(where: { $0.id == item.id }), !items[i].read { items[i].read = true; unread = max(0, unread - 1) }
}
func markAllRead() {
zp.markAllRead("news")
for i in items.indices { items[i].read = true }
unread = 0
}
/// Mobile OSes suspend sockets in the background: call this when the app becomes active.
func appBecameActive() { if zp.state != .connected { zp.reconnectNow() } }
func logout() { zp.close() }
}import SwiftUI
import ZabPush
/// Complete SwiftUI screen: live pushes, server inbox, unread badge, read / click receipts and a connection banner.
/// The model is in PushModel.swift and is created once in ZabPushDemoApp.swift.
///
/// Xcode: File > Add Package Dependencies > Add Local... and choose the package's `sdk/ios` folder.
struct ContentView: View {
@EnvironmentObject var model: PushModel
var body: some View {
NavigationView {
VStack(spacing: 0) {
if model.state != "connected" {
Text("\(model.state)…")
.frame(maxWidth: .infinity).padding(8)
.background(Color.red.opacity(0.15)).foregroundColor(.red)
}
List(model.items) { item in
VStack(alignment: .leading, spacing: 2) {
Text(item.title).font(.headline)
if !item.body.isEmpty { Text(item.body).font(.subheadline) }
}
.listRowBackground(item.read ? Color.clear : Color.red.opacity(0.08))
.contentShape(Rectangle())
.onTapGesture { model.open(item) }
}
.listStyle(.plain)
}
.navigationTitle("Notifications (\(model.unread))")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) { Button("Mark all read") { model.markAllRead() } }
}
}
}
}import FirebaseCore
import FirebaseMessaging
import UIKit
import UserNotifications
import ZabPush
/// OPTIONAL: pushes for when the app is closed. Needs the Firebase setup from the "Offline push" page (GoogleService-Info.plist,
/// the Firebase iOS SDK via Swift Package Manager, Push Notifications + Background Modes capabilities, and your APNs key
/// uploaded in the Firebase console). ZabPush sends through Firebase; it does not talk to APNs directly.
///
/// Use it from ZabPushDemoApp: @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
/// Set by your app once the client exists (for example from PushModel).
static var zp: ZabPush?
func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } }
}
return true
}
/// The FCM token is ready or changed: hand it to ZabPush (re-sent automatically after every reconnect).
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
if let token = fcmToken { AppDelegate.zp?.registerDevice(token: token) }
}
/// The user tapped a notification: Firebase delivers the data fields (id, channel, event, payload) in userInfo.
/// Report the click so your customer panel shows who clicked.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if let id = response.notification.request.content.userInfo["id"] as? String, let n = Int64(id) {
AppDelegate.zp?.clicked(n)
}
completionHandler()
}
/// The push arrived while the app was suspended (needs the "Remote notifications" Background Mode). iOS wakes the app
/// for a few seconds: reconnect so the server replays everything missed, then tell iOS we are done. Apple may delay
/// or skip this wake-up (low power mode, force-quit apps); the notification itself is still shown.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
AppDelegate.zp?.reconnectNow()
DispatchQueue.main.asyncAfter(deadline: .now() + 8) { completionHandler(.newData) }
}
/// Show banners even while the app is open.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound])
}
}What you should see
- No banner once connected. A test push sent from your customer panel appears at the top, tinted while unread; tapping it clears the tint and lowers the count.
- Toggle the network: a red banner appears, then disappears, and pushes sent meanwhile are filled in from the inbox.
Build it in Xcode first, and tell us what you see.
Configuration
ZabPush.Options | Default | Description |
|---|---|---|
host | cloud-zabpush.zabsys.com | Server address. |
secure | false | Use wss://. Always true in production. |
userId | random | Your user id; or ZabPush.persistentUserId() (UserDefaults). |
clientName | empty | Label in your customer panel. |
platform | ios | Set macos on a Mac app. |
reconnect | true | Reconnect automatically. |
reconnectDelay / maxReconnectDelay | 0.5 s / 30 s | Backoff start and ceiling (with jitter). |
heartbeatInterval / heartbeatTimeout | 15 s / 10 s | Ping period and tolerated silence. |
autoAck | true | Send "delivered" receipts automatically. |
authorize | nil | Optional. Only for private-* channels: Closure that fetches the signature for private channels. |
onState | nil | (State, [String: Any]) -> Void. |
callbackQueue | .main | Where callbacks run. |
Receiving messages
zp.subscribe("orders")
.bind("order.shipped") { m in notify(m.title ?? "Shipped", m.body ?? "") }
.bind("*") { m in print(m.event) }
// m: id (0 = live-only), event, channel, data (decoded JSON: [String: Any], [Any], String, NSNumber), ts, live
let orderId = (m.data as? [String: Any])?["orderId"] as? Int
zp.unsubscribe("orders")Publish into an ObservableObject from the handler. See sdk/ios/Examples/ContentView.swift for a complete screen.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorize, no backend call. |
| Private | private-... | The optional authorize callback, which asks your backend for a signature (see Private channels). |
let kHost = "cloud-zabpush.zabsys.com"
let kAppKey = "APP_KEY"
let kChannel = "app-1" // the channel name you publish to
let zp = ZabPush(appKey: kAppKey, options: .init(host: kHost, secure: true, userId: ZabPush.persistentUserId()))
zp.subscribe(kChannel).bind("*") { m in print(m.data ?? "") } // no authorize needed
zp.subscribe("news").bind("*") { print($0.data ?? "") } // as many channels as you like, one connection
zp.unsubscribe("news") // stop listening to one channel
zp.unsubscribeAll() // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. Callbacks run on a background queue. Swift closures cannot throw, so a runtime trap inside your own closure (a force-unwrap of nil, for example) is yours to avoid: keep handlers short and safe. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
var options = ZabPush.Options(host: "cloud-zabpush.zabsys.com", secure: true, userId: user.id)
options.authorize = { socketId, channel, completion in
var req = URLRequest(url: URL(string: "https://api.example.com/zabpush/auth")!)
req.httpMethod = "POST"
req.setValue("Bearer \(userToken)", forHTTPHeaderField: "Authorization")
req.httpBody = "socket_id=\(socketId)&channel=\(channel)".data(using: .utf8)
URLSession.shared.dataTask(with: req) { data, _, error in
if let data = data, let sig = String(data: data, encoding: .utf8) { completion(.success(sig)) }
else { completion(.failure(error ?? URLError(.badServerResponse))) }
}.resume()
}
let zp = ZabPush(appKey: "APP_KEY", options: options)
zp.subscribe("private-user-\(user.id)").bind("*") { print($0.data ?? "") }Your backend endpoint: see the Node.js, Python, Java or PHP pages.
Receipts and inbox
zp.read(message.id)
zp.clicked(message.id)
zp.markAllRead("news")
let inbox = try await zp.inbox("news", limit: 50) // async/await
badge = inbox.unread
zp.inbox("news") { result in // or a completion handler
if case .success(let inbox) = result { print(inbox.messages.count) }
}Background behaviour
iOS does not allow an ordinary app to keep a socket open in the background. A few seconds after the user leaves the app, the system suspends it and the connection is closed. No SDK can change that, and the usual workarounds (silent audio, fake location use) get apps rejected by App Review.
What the SDK does instead is make that transition clean. ZabPushLifecycle asks iOS for its short grace period (about 30 seconds) so receipts and in-flight messages finish, and reconnects the moment the app returns. Nothing is lost: the server remembers where the device stopped and replays what it missed.
// create once, next to the client, and keep a reference
let zp = ZabPush(appKey: "APP_KEY", options: ...)
let lifecycle = ZabPushLifecycle(client: zp)Through Apple's push service. ZabPush does this for you: when a user has no live socket, the server sends through Firebase Cloud Messaging, which hands the message to APNs. Register the device token with registerDevice and upload your APNs key in the Firebase console (see Offline push). The server marks these messages high priority with a sound, so the notification shows at once.
Waking the app to sync
Each such push also carries content-available. With the Remote notifications Background Mode enabled, iOS wakes the app for a few seconds, and the example's AppDelegate reconnects so the server replays everything missed before you open the app. Apple decides when to grant that wake-up (it is skipped in Low Power Mode and for apps the user force-quit), so treat the notification as the guarantee and the wake-up as a bonus.
What to avoid
Holding the socket open with silent audio, location or VoIP background modes. They are reserved for apps that really play audio, track location or make calls, and using them for messaging gets an app rejected in App Review.
ZabPushLifecycle is plain UIKit notification handling. Build it in Xcode first, and tell us what you see.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.subscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.state: connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.isConnected |
| Which channels am I on? | zp.subscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.state // .connecting | .connected | .reconnecting | .disconnected
zp.isConnected // true while live
zp.socketId // id of the current connection (nil while disconnected)
zp.subscribedChannels() // ["app-1", "news"]: the channels you are subscribed to right now
// be told about every change instead of asking: options.onState = { state, info in ... }The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.reconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | zp.close() disconnects for good: no more retries. To connect again create a new client. |
zp.reconnectNow() // force a retry now (ZabPushLifecycle already does it when the app becomes active)
zp.close() // disconnect for good: on logout. No more retries.
// to connect again later, create a new ZabPush(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
// Reconnect immediately when the app becomes active
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ in
if zp.state != .connected { zp.reconnectNow() }
}
// ...and as soon as the network returns
import Network
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in if path.status == .satisfied && zp.state != .connected { zp.reconnectNow() } }
monitor.start(queue: DispatchQueue(label: "net"))State | Meaning |
|---|---|
.connecting | First attempt. |
.connected | Live; subscriptions active; missed messages replayed. |
.reconnecting | Retrying after a drop. |
.disconnected | Lost (info has retryIn) or closed. |
iOS suspends app sockets shortly after the app leaves the foreground. That is what FCM covers; missed messages are replayed when the app is active again. Call zp.close() on logout.
API reference
| Member | Description |
|---|---|
ZabPush(appKey:options:) | Creates the client and connects. |
subscribe(_:) -> Channel | Then .bind(_:_:) with an event name or "*". |
unsubscribe(_:) | Stop listening. |
read(_:) · clicked(_:) · markAllRead(_:) | Receipts (Int64 ids). |
inbox(_:limit:) | async throws -> Inbox, or the completion-handler form. |
registerDevice(token:platform:) | FCM token for offline pushes. |
reconnectNow() · close() | Reconnect now / disconnect for good. |
userId · state · socketId | Read-only properties. |
ZabPush.persistentUserId() | User id stored in UserDefaults. |
Error handling
- Connection problems become state changes and are retried; nothing throws into your code.
inboxthrowsZabPush.ZabPushError.notConnected/.timedOut/.server(message).- A failing
authorizecompletion skips that subscription until the next reconnect.
Test your integration
- Run the example in the simulator or on a device and watch the status become connected.
- The title shows connected. Send a test push from your customer panel: the row appears.
- Toggle the network (Network Link Conditioner or Airplane Mode): the state returns to connected and a push sent meanwhile is replayed.
Go-live checklist
secure: truewith your real domain.- A stable
userIdfrom your login; one shared client instance. - Firebase and the APNs key configured; token registration tested on a real device.
Troubleshooting
It disconnects when the app goes to the background
NNode.js (server)
Send pushes and sign private channels from your Node.js backend. Works with Express, Fastify, NestJS, Next.js API routes, serverless, Bun and Deno (node compat).
Overview
The server SDK wraps the publish API (POST /api/v1/apps/{id}/events) and the private-channel signature. Browsers and apps receive with a client SDK; your Node backend only sends.
Requirements
- Node.js 18+ (uses the global
fetch); a customfetchcan be injected. - Your app id and app secret (or an access token that owns the app).
Installation
npm install ./sdk/js # same package as the client; the server part is "zabpush/server"ZABPUSH_URL=https://cloud-zabpush.zabsys.com
ZABPUSH_APP_ID=1
ZABPUSH_APP_SECRET=... # never commit this; use your host's secret managerQuick start
const { ZabPushServer } = require('zabpush/server');
const zp = new ZabPushServer({
baseUrl: process.env.ZABPUSH_URL,
appId: process.env.ZABPUSH_APP_ID,
secret: process.env.ZABPUSH_APP_SECRET,
});
const res = await zp.publish('news', 'promo', { title: 'Hello', body: 'Sale today' });
console.log(res.results[0]); // { channel: 'news', id: 4127, delivered: 12, stored: true }Complete example
A complete backend with zero dependencies (only Node's built-in http): an endpoint that publishes pushes and an endpoint that signs private channels only for the signed-in user's own channel. Swap in Express or Fastify by moving each branch into a route.
// A complete Node.js backend for ZabPush with ZERO dependencies (only Node's built-in http module):
// POST /notify publish a push { "channel": "news", "event": "promo", "data": {...} }
// POST /zabpush/auth sign a private channel form: socket_id, channel (only for the signed-in user's own channel)
// GET /health
//
// Run: ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... node server-full.js
// Try: curl -X POST localhost:3000/notify -H "Content-Type: application/json" -d '{"channel":"news","event":"promo","data":{"title":"Hi"}}'
//
// Using Express instead? Each handler below becomes app.post('/notify', ...) with express.json() / express.urlencoded();
// the ZabPushServer calls are identical.
const http = require('http');
const { ZabPushServer, ZabPushError } = require('../server.js'); // with npm: require('zabpush/server')
const { ZABPUSH_URL, ZABPUSH_APP_ID, ZABPUSH_APP_SECRET, PORT = 3000 } = process.env;
if (!ZABPUSH_URL || !ZABPUSH_APP_ID || !ZABPUSH_APP_SECRET) {
console.error('set ZABPUSH_URL, ZABPUSH_APP_ID and ZABPUSH_APP_SECRET');
process.exit(2);
}
const zp = new ZabPushServer({ baseUrl: ZABPUSH_URL, appId: ZABPUSH_APP_ID, secret: ZABPUSH_APP_SECRET });
// Replace with YOUR authentication (session cookie, JWT, ...). Here: a header, so the example stays dependency-free.
function currentUser(req) { return req.headers['x-demo-user'] || null; }
function readBody(req) {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (c) => { data += c; if (data.length > 64 * 1024) { reject(new Error('body too large')); req.destroy(); } });
req.on('end', () => resolve(data));
req.on('error', reject);
});
}
const send = (res, code, body, type = 'application/json') => {
res.writeHead(code, { 'Content-Type': type });
res.end(typeof body === 'string' ? body : JSON.stringify(body));
};
http.createServer(async (req, res) => {
try {
if (req.method === 'GET' && req.url === '/health') return send(res, 200, 'ok', 'text/plain');
if (req.method === 'POST' && req.url === '/notify') {
const { channel, event, data } = JSON.parse(await readBody(req));
const result = await zp.publish(channel, event, data, { ttl: 3600 }); // replayable for an hour
return send(res, 200, result);
}
if (req.method === 'POST' && req.url === '/zabpush/auth') {
const form = new URLSearchParams(await readBody(req));
const user = currentUser(req);
const channel = form.get('channel') || '';
// YOUR rule, checked BEFORE signing: a user may only join their own private channel.
if (!user || channel !== `private-user-${user}`) return send(res, 403, 'forbidden', 'text/plain');
return send(res, 200, zp.authenticate(form.get('socket_id') || '', channel), 'text/plain');
}
send(res, 404, { error: 'not found' });
} catch (e) {
if (e instanceof ZabPushError) {
// 429 / 503 are worth retrying later; 401 means a wrong secret; 400 a bad channel/event/data
return send(res, e.status === 429 || e.status === 503 ? 503 : 502, { error: e.message, upstream: e.status });
}
send(res, 400, { error: String(e.message || e) });
}
}).listen(PORT, () => console.log(`backend on :${PORT}`));Run it
ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... node server.jsTry it
curl -X POST localhost:3000/notify -H "Content-Type: application/json" \
-d '{"channel":"news","event":"promo","data":{"title":"Hi"}}'
# private channel signature: only for the user's own channel
curl -X POST localhost:3000/zabpush/auth -H "X-Demo-User: alice" -d "socket_id=abc123&channel=private-user-alice"
curl -X POST localhost:3000/zabpush/auth -H "X-Demo-User: alice" -d "socket_id=abc123&channel=private-user-bob" # 403What you should see
{"results":[{"channel":"news","id":4127448,"delivered":0,"stored":true}]}
0e8ede62dfe5dd466c71348e33f7db0442033c1303dc60cbaf159692b7287d9a <- signature for alice's own channel
forbidden <- 403 for bob's channelRun against a live server: publish works, a bad channel name returns the server's error, the signature matches an independent HMAC, and signing is refused (403) for another user's channel or no user.
Configuration
| Option | Default | Description |
|---|---|---|
baseUrl | required | Your server, e.g. https://cloud-zabpush.zabsys.com. |
appId | required | The numeric app id. |
secret | — | App secret. Needed for authenticate(). |
token | — | Access token (zpt_…) instead of the secret, for publishing only. |
timeoutMs | 10000 | Request timeout. |
fetch | global fetch | Inject a fetch implementation (older runtimes, tests, proxies). |
Publishing
// one channel
await zp.publish('orders', 'order.shipped', { id: 981, title: 'Your order shipped' });
// several channels (up to 100), replayable for an hour, no FCM fallback
await zp.publish(['user-1', 'user-2'], 'alert', { n: 1 }, { ttl: 3600, fallback: false });| Option | Description |
|---|---|
ttl | Seconds the message stays replayable and in the inbox (max 30 days). Omit for the server's retention period. |
fallback | false skips the FCM push to offline devices. Default is on. |
Each result has delivered (live clients reached) and stored. stored: false means the server's database was down and the push went to live clients only.
Private channel endpoint
app.post('/zabpush/auth', express.urlencoded({ extended: false }), (req, res) => {
const { socket_id, channel } = req.body;
// YOUR rule: a user may only join their own private channel.
if (!req.session.userId || channel !== `private-user-${req.session.userId}`) return res.sendStatus(403);
res.type('text/plain').send(zp.authenticate(socket_id, channel));
});The signature is the permission. Never sign whatever channel the client asks for.
API reference
| Member | Description |
|---|---|
new ZabPushServer(options) | Create once and reuse. |
publish(channels, event, data, options?) | Promise of { results: [{ channel, id, delivered, stored }] }. |
authenticate(socketId, channel) | Returns the hex signature for a private channel. Needs the secret. |
ZabPushError | Thrown for non-2xx answers: message, status, body. |
Error handling
const { ZabPushError } = require('zabpush/server');
try {
await zp.publish('news', 'promo', data);
} catch (e) {
if (e instanceof ZabPushError) {
if (e.status === 429) return retryLater(); // rate limited
if (e.status === 503) return retryLater(); // server unavailable
if (e.status === 401) throw new Error('check the app secret / id');
if (e.status === 400) throw new Error('bad request: ' + e.message); // invalid channel / event / data
}
throw e; // network error or timeout
}Test your integration
Listen with the client example, then publish:
ZP_KEY=APP_KEY node sdk/js/examples/wait-for.js news promo # terminal 1: waits for a message
node -e "new (require('./sdk/js/server').ZabPushServer)({baseUrl:'https://cloud-zabpush.zabsys.com',appId:1,secret:'APP_SECRET'}).publish('news','promo',{hi:1}).then(console.log)"Go-live checklist
- The secret comes from an environment variable or secret manager, not from source code.
- One shared
ZabPushServerinstance; retry429and503with backoff. - Your
/zabpush/authroute checks the session first and is served over HTTPS. - You log
stored: falseresults (a sign the database had trouble).
Python
Send pushes from Django, Flask, FastAPI or scripts with a standard-library SDK, and receive them in workers and bots with the asyncio client.
Overview
Two parts in one package: ZabPushServer (publish and sign private channels, no dependencies) and ZabPush (an asyncio realtime client built on the websockets package). Use the server part in web apps and the client part for long-running workers, bots, desktop tools or tests.
Requirements
- Python 3.9 or newer.
- Server SDK: nothing else. Client: the
websocketspackage (installed with the[client]extra). - Your app id and app secret (server), or app key (client).
Installation
pip install "./sdk/python[client]" # from the SDK package folder; [client] adds websockets
pip install ./sdk/python # server-only use needs no extra packagesQuick start
import os
from zabpush import ZabPushServer
zp = ZabPushServer("https://cloud-zabpush.zabsys.com", app_id=1, secret=os.environ["ZABPUSH_APP_SECRET"])
res = zp.publish("news", "promo", {"title": "Hello", "body": "Sale today"})
print(res["results"][0]) # {'channel': 'news', 'id': 4127, 'delivered': 12, 'stored': True}import asyncio
from zabpush import ZabPush
async def main():
async with ZabPush("APP_KEY", host="cloud-zabpush.zabsys.com", secure=True, user_id="worker-1") as zp:
zp.subscribe("news").bind("promo", lambda m: print(m.data["title"]))
await asyncio.sleep(3600)
asyncio.run(main())Complete example
Two programs that work together: a backend (publish endpoint + private-channel signing, standard library only) and a worker that receives pushes on a public and a private channel, reads its inbox, acknowledges messages and shuts down cleanly.
"""A complete Python backend for ZabPush using only the standard library:
POST /notify publish a push {"channel": "news", "event": "promo", "data": {...}}
POST /zabpush/auth sign a private channel form: socket_id, channel (only the signed-in user's own channel)
GET /health
Run: ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... python server_full.py
Try: curl -X POST localhost:3000/notify -H "Content-Type: application/json" -d '{"channel":"news","event":"promo","data":{"title":"Hi"}}'
Using Flask, FastAPI or Django? Each handler below maps to a route; the ZabPushServer calls are identical.
"""
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) # with pip install: delete this line
from zabpush import ZabPushError, ZabPushServer # noqa: E402
URL, APP_ID, SECRET = os.environ.get("ZABPUSH_URL"), os.environ.get("ZABPUSH_APP_ID"), os.environ.get("ZABPUSH_APP_SECRET")
if not (URL and APP_ID and SECRET):
sys.exit("set ZABPUSH_URL, ZABPUSH_APP_ID and ZABPUSH_APP_SECRET")
zp = ZabPushServer(URL, APP_ID, secret=SECRET)
def current_user(handler):
"""Replace with YOUR authentication (session, JWT, ...). Here: a header, to stay dependency-free."""
return handler.headers.get("X-Demo-User")
class Handler(BaseHTTPRequestHandler):
def _send(self, code, body, content_type="application/json"):
raw = body.encode() if isinstance(body, str) else json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def _body(self):
n = int(self.headers.get("Content-Length") or 0)
if n > 64 * 1024:
raise ValueError("body too large")
return self.rfile.read(n).decode()
def do_GET(self):
if self.path == "/health":
return self._send(200, "ok", "text/plain")
self._send(404, {"error": "not found"})
def do_POST(self):
try:
if self.path == "/notify":
req = json.loads(self._body())
result = zp.publish(req["channel"], req["event"], req["data"], ttl=3600) # replayable for an hour
return self._send(200, result)
if self.path == "/zabpush/auth":
form = parse_qs(self._body())
channel = form.get("channel", [""])[0]
user = current_user(self)
# YOUR rule, checked BEFORE signing: a user may only join their own private channel.
if not user or channel != f"private-user-{user}":
return self._send(403, "forbidden", "text/plain")
return self._send(200, zp.authenticate(form.get("socket_id", [""])[0], channel), "text/plain")
self._send(404, {"error": "not found"})
except ZabPushError as e:
# 429 / 503 are worth retrying later; 401 means a wrong secret; 400 a bad channel/event/data
self._send(503 if e.status in (429, 503) else 502, {"error": str(e), "upstream": e.status})
except (ValueError, KeyError) as e:
self._send(400, {"error": f"bad request: {e}"})
if __name__ == "__main__":
port = int(os.environ.get("PORT", "3000"))
print(f"backend on :{port}", flush=True)
ThreadingHTTPServer(("", port), Handler).serve_forever()"""A complete ZabPush worker (asyncio): public + private channels, receipts, inbox, state logging, clean shutdown.
Run: ZP_HOST=cloud-zabpush.zabsys.com ZP_SECURE=1 ZP_KEY=APP_KEY ZP_USER=alice \
ZP_AUTH_URL=https://api.example.com/zabpush/auth python full_client.py
Stop with Ctrl+C (or set ZP_RUN_SECONDS to exit by itself).
"""
import asyncio
import logging
import os
import sys
import urllib.parse
import urllib.request
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) # with pip install: delete this line
from zabpush import ZabPush # noqa: E402
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("worker")
HOST = os.environ.get("ZP_HOST", "cloud-zabpush.zabsys.com")
SECURE = os.environ.get("ZP_SECURE") == "1"
KEY = os.environ["ZP_KEY"]
USER = os.environ.get("ZP_USER", "worker-1") # YOUR id for this user/worker
AUTH_URL = os.environ.get("ZP_AUTH_URL") # YOUR backend endpoint that signs private channels
RUN_SECONDS = float(os.environ.get("ZP_RUN_SECONDS", "0")) # 0 = run until Ctrl+C
def ask_backend_to_sign(socket_id: str, channel: str) -> str:
"""Blocking HTTP call to YOUR backend; it checks the user and returns the signature (see server_full.py)."""
req = urllib.request.Request(
AUTH_URL,
data=urllib.parse.urlencode({"socket_id": socket_id, "channel": channel}).encode(),
headers={"X-Demo-User": USER}, # your real credentials here (session cookie, bearer token, ...)
)
with urllib.request.urlopen(req, timeout=10) as r:
return r.read().decode()
async def authorize(socket_id: str, channel: str) -> str:
return await asyncio.to_thread(ask_backend_to_sign, socket_id, channel) # keep the event loop free
async def main() -> None:
zp = ZabPush(
KEY, host=HOST, secure=SECURE, user_id=USER, client_name="python-worker",
authorize=authorize if AUTH_URL else None,
on_state=lambda state, info: log.info("connection: %s %s", state, {k: v for k, v in info.items() if k != "socket_id"}),
)
async def on_order(m): # handlers may be plain functions or coroutines
log.info("order event=%s data=%s", m.event, m.data)
zp.read(m.id) # the user "saw" it ("delivered" is automatic)
zp.subscribe("orders").bind("*", on_order)
if AUTH_URL:
zp.subscribe(f"private-user-{USER}").bind("*", lambda m: log.info("PRIVATE %s: %s", m.event, m.data))
async with zp:
await zp.wait_connected(10)
await asyncio.sleep(0.5) # let the subscriptions be accepted
inbox = await zp.inbox("orders", limit=20) # what the server kept for this user
log.info("inbox: %d message(s), %d unread", len(inbox.messages), inbox.unread)
try:
await asyncio.sleep(RUN_SECONDS or 10**9)
except asyncio.CancelledError:
pass
log.info("closed cleanly")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
passRun it (two terminals)
# terminal 1: the backend
ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... python server_full.py
# terminal 2: the worker (alice)
ZP_HOST=cloud-zabpush.zabsys.com ZP_SECURE=1 ZP_KEY=APP_KEY ZP_USER=alice ZP_AUTH_URL=http://localhost:3000/zabpush/auth python full_client.py
# terminal 3: send pushes through your backend
curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
curl -X POST localhost:3000/notify -d '{"channel":"private-user-alice","event":"secret","data":{"msg":"hi alice"}}'What the worker prints
INFO connection: connecting {'attempt': 0}
INFO connection: connected {'user_id': 'alice'}
INFO inbox: 0 message(s), 0 unread
INFO order event=order.shipped data={'id': 981}
INFO PRIVATE secret: {'msg': 'hi alice'}
INFO connection: disconnected {'reason': 'closed'}
INFO closed cleanlyBoth programs were run together against a live server: the worker connected, received the public and the private push (signed by the backend after its user check), and closed cleanly; the backend refused to sign another user's channel (403).
Configuration
Client (ZabPush)
| Argument | Default | Description |
|---|---|---|
app_key | required | The public app key. |
host | cloud-zabpush.zabsys.com | Server address. |
secure | False | Use wss://. Always True in production. |
user_id | random per run | Your unique id. Persist it if the process restarts and you want replay and the inbox to continue. |
client_name / platform | "" / python | Labels shown in your customer panel. |
reconnect | True | Reconnect automatically. |
reconnect_delay / max_reconnect_delay | 0.5 / 30 s | Backoff start and ceiling (with jitter). |
heartbeat_interval / heartbeat_timeout | 15 / 10 s | WebSocket keep-alive ping and the wait for its reply. |
auto_ack | True | Send "delivered" receipts. |
authorize | None | Optional. Only for private-* channels: (socket_id, channel) -> str, sync or async: signature for private channels. |
on_state | None | (state, info) -> None, sync or async. |
Server (ZabPushServer)
| Argument | Description |
|---|---|
base_url, app_id | Your server and the numeric app id. |
secret / token | App secret (needed for authenticate) or an access token for publishing only. |
timeout | Seconds, default 10. |
Receiving messages
async def on_order(m): # handlers may be plain functions or coroutines
print(m.id, m.event, m.data) # m: id (0 = live-only), event, channel, data, ts, live
zp.read(m.id)
orders = zp.subscribe("orders")
orders.bind("order.shipped", on_order)
orders.bind("*", lambda m: print("any event", m.event))
zp.unsubscribe("orders")An exception in one handler is logged (logger zabpush) and never stops the others or the connection.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorize, no backend call. |
| Private | private-... | The optional authorize callback, which asks your backend for a signature (see Private channels). |
K_HOST = "cloud-zabpush.zabsys.com"
K_APP_KEY = "APP_KEY"
K_CHANNEL = "app-1" # the channel name you publish to
K_USER_ID = "user-42"
async with ZabPush(K_APP_KEY, host=K_HOST, secure=True, user_id=K_USER_ID) as zp: # no authorize: public channel
zp.subscribe(K_CHANNEL).bind("*", lambda m: print(m.data))
zp.subscribe("news").bind("*", print) # as many channels as you like, one connection
zp.unsubscribe("news") # stop listening to one channel
await asyncio.sleep(3600)
zp.unsubscribe_all() # leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that raises is logged and skipped: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
import aiohttp
async def sign(socket_id, channel): # ask YOUR backend (it checks the user first)
async with aiohttp.ClientSession() as s:
async with s.post("https://api.example.com/zabpush/auth", data={"socket_id": socket_id, "channel": channel}) as r:
r.raise_for_status()
return await r.text()
zp = ZabPush("APP_KEY", host="cloud-zabpush.zabsys.com", secure=True, user_id="user-42", authorize=sign)
zp.subscribe("private-user-42").bind("*", print)@app.post("/zabpush/auth")
def auth():
channel = request.form["channel"]
if channel != f"private-user-{session['user_id']}": # YOUR rule, checked BEFORE signing
abort(403)
return zp.authenticate(request.form["socket_id"], channel)@login_required
@require_POST
def zabpush_auth(request):
channel = request.POST["channel"]
if channel != f"private-user-{request.user.id}":
return HttpResponseForbidden()
return HttpResponse(zp.authenticate(request.POST["socket_id"], channel), content_type="text/plain")Receipts and inbox
zp.read(m.id)
zp.clicked(m.id)
zp.mark_all_read("news")
inbox = await zp.inbox("news", limit=50) # inbox.messages (each has .read) and inbox.unread
print(inbox.unread, [msg.id for msg in inbox.messages])Publishing
zp.publish("orders", "order.shipped", {"id": 981})
zp.publish(["user-1", "user-2"], "alert", {"n": 1}, ttl=3600, fallback=False) # up to 100 channels
await zp.publish_async("news", "promo", {"n": 2}) # without blocking the event loop
# Django / Celery: send from a task or a signal
@shared_task
def notify(user_id, title):
zp.publish(f"user-{user_id}", "notice", {"title": title})ttl: seconds the message stays replayable (max 30 days). fallback=False skips the FCM push to offline devices.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.subscribed_channels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.state: connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.is_connected |
| Which channels am I on? | zp.subscribed_channels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.state # "connecting" | "connected" | "reconnecting" | "disconnected"
zp.is_connected # True while live
zp.socket_id # id of the current connection (None while disconnected)
zp.subscribed_channels() # ["app-1", "news"]: the channels you are subscribed to right now
# be told about every change instead of asking: ZabPush(..., on_state=lambda state, info: print(state, info))The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.reconnect_now() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | await zp.close() disconnects for good: no more retries. To connect again create a new client. |
zp.reconnect_now() # force a retry now
await zp.close() # disconnect for good (on shutdown or logout). No more retries.
# to connect again later, create a new ZabPush(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
def on_state(state, info):
# 'connecting' | 'connected' | 'reconnecting' | 'disconnected'
print("connection:", state, info) # info has retry_in / attempt when disconnected
zp = ZabPush("APP_KEY", host="cloud-zabpush.zabsys.com", secure=True, user_id="worker-1", on_state=on_state)
await zp.wait_connected(timeout=10) # raises asyncio.TimeoutError if it cannot connect
zp.reconnect_now() # force an immediate reconnect
await zp.close() # or leave the `async with` blockA dead link is detected by WebSocket keep-alive pings (about 25 seconds worst case) and repaired automatically, with missed messages replayed after reconnecting. Run workers under systemd, Docker or Supervisor so the process itself restarts if it ever exits.
API reference
| Member | Description |
|---|---|
ZabPushServer.publish(channels, event, data, ttl=None, fallback=None) | Returns {"results": [{channel, id, delivered, stored}]}. Raises ZabPushError. |
ZabPushServer.publish_async(...) | Same, via a worker thread. |
ZabPushServer.authenticate(socket_id, channel) | Hex signature for a private channel. |
ZabPush(...) | Async context manager; also await start() / await close(). |
subscribe(channel).bind(event, handler) | Handlers receive a Message. |
read(id) · clicked(id) · mark_all_read(channel) | Receipts. |
await inbox(channel, limit=50) | Inbox(messages, unread). |
register_device(token, platform) | FCM token. |
await wait_connected(timeout) · reconnect_now() | Lifecycle helpers. |
user_id · state · socket_id | Properties. |
Error handling
from zabpush import ZabPushError
try:
zp.publish("news", "promo", data)
except ZabPushError as e:
if e.status in (429, 503):
retry_later() # rate limited / server unavailable
elif e.status == 401:
raise RuntimeError("check the app secret and app id") from e
elif e.status == 400:
raise ValueError(f"bad request: {e}") from e
else: # status None: network error or timeout
raiseTest your integration
cd sdk/python
pip install websockets
ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=APP_KEY ZP_ID=1 ZP_SECRET=APP_SECRET python examples/smoke.py
# -> state: connected / ok public / ok private / ok inbox / PASS pythonexamples/reconnect.py prints RECONNECTED after you cut the network for a moment.
Go-live checklist
- Secret from an environment variable or secret manager.
- Web apps: reuse one
ZabPushServer; catchZabPushErrorand retry 429/503 with backoff; call it from a task queue for slow paths. - Workers: a stable
user_id,secure=True, supervised process.
Troubleshooting
ImportError: the realtime client needs the websockets package
pip install "./sdk/python[client]"."RuntimeError: no running event loop"
asyncio.run(...) or an async function.Handlers are never called
asyncio.sleep) so the loop keeps running. Turn on logging with logging.basicConfig(level=logging.DEBUG).
.NET (C#)
ASP.NET, Blazor, MAUI, worker services, console apps and Unity (netstandard2.1). Client and server in one package, using only System.Text.Json.
Overview
ZabPushServer publishes pushes and signs private channels. ZabPushClient is a realtime client with auto-reconnect, heartbeat, replay, receipts and an inbox.
Build it and run the shipped smoke test (dotnet run --project sdk/dotnet/examples/Smoke) first; it should print PASS dotnet.
Requirements
- .NET 8 SDK (the library also targets
netstandard2.1for older apps and Unity). - Server: app id and app secret. Client: the app key.
Installation
dotnet add reference ../zabpush/sdk/dotnet/ZabPush/ZabPush.csprojQuick start
using ZabPush;
var zp = new ZabPushServer("https://cloud-zabpush.zabsys.com", 1, Environment.GetEnvironmentVariable("ZABPUSH_APP_SECRET"));
var res = await zp.PublishAsync("news", "promo", new { title = "Hello", body = "Sale today" });
Console.WriteLine(res.Results[0].Delivered); // live clients reachedawait using var zp = new ZabPushClient("APP_KEY", new ZabPushOptions
{
Host = "cloud-zabpush.zabsys.com", Secure = true, UserId = "user-42", ClientName = "my-app",
});
zp.Subscribe("news").Bind("promo", m =>
{
Console.WriteLine(m.Data.GetProperty("title").GetString());
zp.Read(m.Id); // "delivered" is automatic
});
await zp.WaitConnectedAsync();Complete example
A complete ASP.NET Core service: minimal-API endpoints that publish pushes and sign private channels only for the signed-in user's own channel, plus a BackgroundService that receives pushes for the lifetime of the app.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\ZabPush\ZabPush.csproj" />
</ItemGroup>
</Project>// A complete ASP.NET Core service: an HTTP backend that publishes pushes AND a background consumer that receives them.
//
// POST /notify publish a push {"channel":"orders","event":"order.shipped","data":{...}}
// POST /zabpush/auth sign a private channel form: socket_id, channel (only the signed-in user's own channel)
// GET /health
//
// Run (PowerShell):
// $env:ZABPUSH_URL='https://cloud-zabpush.zabsys.com'; $env:ZABPUSH_APP_ID='1'; $env:ZABPUSH_APP_SECRET='...'; $env:ZABPUSH_APP_KEY='...'
// dotnet run --project sdk/dotnet/examples/Full --urls http://localhost:3000
// Try:
// curl -X POST localhost:3000/notify -H "Content-Type: application/json" -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
using System.Text.Json;
using ZabPush;
var builder = WebApplication.CreateBuilder(args);
string Need(string name) => Environment.GetEnvironmentVariable(name) ?? throw new InvalidOperationException($"set {name}");
var baseUrl = Need("ZABPUSH_URL");
// One shared server SDK instance for the whole app (it is thread-safe).
builder.Services.AddSingleton(new ZabPushServer(baseUrl, long.Parse(Need("ZABPUSH_APP_ID")), Need("ZABPUSH_APP_SECRET")));
builder.Services.AddHostedService<PushConsumer>();
var app = builder.Build();
app.MapGet("/health", () => "ok");
app.MapPost("/notify", async (NotifyRequest req, ZabPushServer zp) =>
{
try
{
var result = await zp.PublishAsync(req.Channel, req.Event, req.Data, ttlSeconds: 3600); // replayable for an hour
return Results.Json(result);
}
catch (ZabPushException e) when (e.Status is 429 or 503)
{
return Results.Json(new { error = "try again later" }, statusCode: 503); // worth retrying
}
catch (ZabPushException e)
{
return Results.Json(new { error = e.Message, upstream = e.Status }, statusCode: 502); // 401 wrong secret, 400 bad input
}
});
app.MapPost("/zabpush/auth", (HttpContext ctx, ZabPushServer zp) =>
{
var user = ctx.Request.Headers["X-Demo-User"].ToString(); // replace with YOUR authentication
var channel = ctx.Request.Form["channel"].ToString();
// YOUR rule, checked BEFORE signing: a user may only join their own private channel.
if (user == "" || channel != $"private-user-{user}") return Results.StatusCode(403);
return Results.Text(zp.Authenticate(ctx.Request.Form["socket_id"].ToString(), channel));
});
app.Run();
public record NotifyRequest(string Channel, string Event, JsonElement Data);
/// <summary>Receives pushes for the lifetime of the app. Start/stop is handled by the host (clean shutdown included).</summary>
public sealed class PushConsumer : BackgroundService
{
private readonly ZabPushServer _server;
private readonly ILogger<PushConsumer> _log;
public PushConsumer(ZabPushServer server, ILogger<PushConsumer> log) { _server = server; _log = log; }
protected override async Task ExecuteAsync(CancellationToken stop)
{
var uri = new Uri(Environment.GetEnvironmentVariable("ZABPUSH_URL")!);
await using var zp = new ZabPushClient(Environment.GetEnvironmentVariable("ZABPUSH_APP_KEY")!, new ZabPushOptions
{
Host = uri.Authority, Secure = uri.Scheme == "https", UserId = "service-1", ClientName = "dotnet-service",
// This process owns the secret, so it may sign directly. A client app would call YOUR backend instead.
Authorize = (socketId, channel) => Task.FromResult(_server.Authenticate(socketId, channel)),
});
zp.StateChanged += (state, info) => _log.LogInformation("connection: {State}", state);
zp.Subscribe("orders").Bind("*", m => // handlers run on a pool thread: keep them quick
{
_log.LogInformation("order event={Event} data={Data}", m.Event, m.Data);
zp.Read(m.Id);
});
zp.Subscribe("private-user-service-1").Bind("*", m => _log.LogInformation("PRIVATE {Event}: {Data}", m.Event, m.Data));
try { await Task.Delay(Timeout.Infinite, stop); } // run until the host stops
catch (OperationCanceledException) { /* shutting down */ }
}
}Run it
$env:ZABPUSH_URL='https://cloud-zabpush.zabsys.com'; $env:ZABPUSH_APP_ID='1'; $env:ZABPUSH_APP_SECRET='...'; $env:ZABPUSH_APP_KEY='...'
dotnet run --project sdk/dotnet/examples/Full --urls http://localhost:3000
curl -X POST localhost:3000/notify -H "Content-Type: application/json" -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'What you should see
The console logs connection: Connected, then order event=order.shipped data={"id":981} right after the curl call, and the curl response contains "delivered":1.
Build it first (dotnet build); dotnet run --project sdk/dotnet/examples/Smoke is the quickest end-to-end check.
Configuration
ZabPushOptions | Default | Description |
|---|---|---|
Host | cloud-zabpush.zabsys.com | Server address. |
Secure | false | Use wss://. Always true in production. |
UserId | random per run | Your unique id; persist it to keep replay and the inbox across restarts. |
ClientName / Platform | "" / dotnet | Labels in your customer panel. |
Reconnect | true | Reconnect automatically. |
ReconnectDelay / MaxReconnectDelay | 500 ms / 30 s | Backoff start and ceiling (with jitter). |
HeartbeatInterval / HeartbeatTimeout | 15 s / 10 s | Ping period and tolerated silence. |
AutoAck | true | Send "delivered" receipts. |
Authorize | null | Optional. Only for private-* channels: Func<string, string, Task<string>> (socketId, channel) for private channels. |
Server: new ZabPushServer(baseUrl, appId, secret: ..., token: ..., http: ...). Pass your own HttpClient (for example from IHttpClientFactory).
Receiving messages
zp.Subscribe("orders")
.Bind("order.shipped", m => Notify(m.Data.GetProperty("title").GetString()))
.Bind("*", m => Console.WriteLine(m.Event));
// m: Id (0 = live-only), Event, Channel, Data (JsonElement), Ts, Live
zp.Unsubscribe("orders");
zp.StateChanged += (state, info) => Console.WriteLine($"connection: {state}");Handlers run on a thread-pool thread. An exception in one handler is swallowed so it cannot stop the others or the connection. Marshal to the UI thread yourself in WPF/MAUI.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No Authorize, no backend call. |
| Private | private-... | The optional Authorize callback, which asks your backend for a signature (see Private channels). |
const string kHost = "cloud-zabpush.zabsys.com", kAppKey = "APP_KEY", kChannel = "app-1", kUserId = "user-42";
await using var zp = new ZabPushClient(kAppKey, new ZabPushOptions { Host = kHost, Secure = true, UserId = kUserId });
zp.Subscribe(kChannel).Bind("*", m => Console.WriteLine(m.Data)); // no Authorize needed
zp.Subscribe("news").Bind("*", m => Console.WriteLine(m.Data)); // as many channels as you like, one connection
zp.Unsubscribe("news"); // stop listening to one channel
zp.UnsubscribeAll(); // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that throws is swallowed: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
var zp = new ZabPushClient("APP_KEY", new ZabPushOptions
{
Host = "cloud-zabpush.zabsys.com", Secure = true, UserId = user.Id,
Authorize = async (socketId, channel) =>
{
var r = await http.PostAsync("https://api.example.com/zabpush/auth", new FormUrlEncodedContent(
new Dictionary<string, string> { ["socket_id"] = socketId, ["channel"] = channel }));
r.EnsureSuccessStatusCode();
return await r.Content.ReadAsStringAsync();
},
});
zp.Subscribe($"private-user-{user.Id}").Bind("*", m => Console.WriteLine(m.Data));app.MapPost("/zabpush/auth", [Authorize] (HttpContext ctx, ZabPushServer zp) =>
{
var channel = ctx.Request.Form["channel"].ToString();
if (channel != $"private-user-{ctx.User.FindFirst("sub")?.Value}") // YOUR rule, BEFORE signing
return Results.Forbid();
return Results.Text(zp.Authenticate(ctx.Request.Form["socket_id"]!, channel));
});Receipts and inbox
zp.Read(m.Id);
zp.Clicked(m.Id);
zp.MarkAllRead("news");
var inbox = await zp.InboxAsync("news", 50); // inbox.Messages (each .Read) and inbox.UnreadPublishing (ASP.NET dependency injection)
builder.Services.AddSingleton(_ => new ZabPushServer(
builder.Configuration["ZabPush:Url"]!, long.Parse(builder.Configuration["ZabPush:AppId"]!),
builder.Configuration["ZabPush:Secret"]));await zp.PublishAsync("orders", "order.shipped", new { id = 981 });
await zp.PublishAsync(new[] { "user-1", "user-2" }, "alert", new { n = 1 }, ttlSeconds: 3600, fallback: false);Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.SubscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.State: connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.IsConnected |
| Which channels am I on? | zp.SubscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.State // ConnectionState.Connecting | Connected | Reconnecting | Disconnected
zp.IsConnected // true while live
zp.SocketId // id of the current connection (null while disconnected)
zp.SubscribedChannels() // ["app-1", "news"]: the channels you are subscribed to right now
// be told about every change instead of asking
zp.StateChanged += (state, info) => Console.WriteLine(state);The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.ReconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | await zp.DisposeAsync() disconnects for good: no more retries. To connect again create a new client. |
zp.ReconnectNow(); // force a retry now (for example from a connectivity callback)
await zp.DisposeAsync(); // disconnect for good (on shutdown or logout). No more retries.
// to connect again later, create a new ZabPushClient(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
ConnectionState | Meaning |
|---|---|
Connecting | First attempt. |
Connected | Live; subscriptions active; missed messages replayed. |
Reconnecting | Retrying after a drop. |
Disconnected | Lost (info has retryIn) or closed. |
zp.ReconnectNow() forces an immediate reconnect (for example from a connectivity callback in MAUI). await zp.DisposeAsync() closes for good. In a worker service, create the client in BackgroundService.ExecuteAsync and dispose it on shutdown.
API reference
| Member | Description |
|---|---|
ZabPushServer.PublishAsync(channel(s), event, data, ttlSeconds, fallback, ct) | Returns PublishResponse with Results[] (Channel, Id, Delivered, Stored). |
ZabPushServer.Authenticate(socketId, channel) | Hex signature. |
ZabPushException | Thrown by the server SDK: Message, Status. |
ZabPushClient(appKey, options) | Connects in the background. |
Subscribe(channel).Bind(event, handler) · Unsubscribe | Handlers receive a PushMessage. |
Read · Clicked · MarkAllRead | Receipts. |
InboxAsync(channel, limit) | Inbox with Messages and Unread. |
RegisterDevice(token, platform) | FCM token. |
WaitConnectedAsync(timeout) · ReconnectNow() | Lifecycle helpers. |
UserId · State · SocketId · StateChanged | Properties and event. |
Error handling
try { await zp.PublishAsync("news", "promo", data); }
catch (ZabPushException e) when (e.Status is 429 or 503) { await RetryLater(); }
catch (ZabPushException e) when (e.Status == 401) { throw new InvalidOperationException("check the app secret and id", e); }
catch (ZabPushException e) { logger.LogError(e, "publish failed"); } // Status 0: network error or timeoutTest your integration
$env:ZP_HOST='cloud-zabpush.zabsys.com'; $env:ZP_KEY='APP_KEY'; $env:ZP_ID='1'; $env:ZP_SECRET='APP_SECRET'
dotnet run --project sdk/dotnet/examples/Smoke
# expect: state: Connected / ok public / ok private / ok inbox / PASS dotnetGo-live checklist
- The smoke test passes against your server.
Secure = true; secret in configuration or a vault; one sharedZabPushServer.- Handle
ZabPushException429/503 with retry and backoff.
Troubleshooting
Build errors in the SDK itself
using or nullable warning) and tell us, so we can fix it too.Handlers update the UI from the wrong thread
Dispatcher.Invoke (WPF), MainThread.BeginInvokeOnMainThread (MAUI) or SynchronizationContext.Post.WaitConnectedAsync times out
Host, Secure and the app key. HTTP 401 on the /ws request means a wrong key.GoGo
A realtime client and a publisher in one module. Idiomatic Go: contexts, goroutines, and no global state.
Overview
Use zabpush.Server in your services to publish and sign private channels, and zabpush.Client for long-running consumers (workers, bridges, CLIs). The client reconnects by itself, replays missed messages and sends receipts.
Requirements
- Go 1.21+. One dependency:
github.com/gorilla/websocket.
Installation
go get github.com/zabsys/zabpush-go
# until you host it under that path, point Go at the project folder:
go mod edit -replace github.com/zabsys/zabpush-go=../zabpush/sdk/go
go mod tidyThe module path github.com/zabsys/zabpush-go is a placeholder: change module in sdk/go/go.mod to wherever you host the code.
Quick start
import zabpush "github.com/zabsys/zabpush-go"
s := zabpush.NewServer("https://cloud-zabpush.zabsys.com", 1, os.Getenv("ZABPUSH_APP_SECRET"))
res, err := s.Publish(ctx, []string{"news"}, "promo", map[string]string{"title": "Hello", "body": "Sale today"}, nil)
if err != nil { log.Fatal(err) }
fmt.Println(res.Results[0].Delivered, "live clients reached")c := zabpush.New("APP_KEY", zabpush.Options{
Host: "cloud-zabpush.zabsys.com", Secure: true, UserID: "worker-1", ClientName: "my-service",
OnState: func(st zabpush.State, _ zabpush.StateInfo) { log.Println("connection:", st) },
})
defer c.Close()
c.Subscribe("news").Bind("promo", func(m zabpush.Message) {
fmt.Println(string(m.Data))
c.Read(m.ID) // "delivered" is automatic
})
select {} // keep the process aliveComplete example
A complete service in one file: an HTTP backend (publish endpoint and private-channel signing for the signed-in user's own channel) and a consumer in the same process, with graceful shutdown.
// A complete Go service: an HTTP backend that publishes pushes AND a consumer that receives them.
//
// POST /notify publish a push {"channel":"orders","event":"order.shipped","data":{...}}
// POST /zabpush/auth sign a private channel form: socket_id, channel (only the signed-in user's own channel)
// GET /health
//
// Run:
//
// ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... ZABPUSH_APP_KEY=... go run ./examples/full
//
// Try:
//
// curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"syscall"
"time"
zabpush "github.com/zabsys/zabpush-go"
)
func mustEnv(k string) string {
v := os.Getenv(k)
if v == "" {
log.Fatalf("set %s", k)
}
return v
}
func main() {
base := mustEnv("ZABPUSH_URL")
appID, _ := strconv.ParseInt(mustEnv("ZABPUSH_APP_ID"), 10, 64)
secret, appKey := mustEnv("ZABPUSH_APP_SECRET"), mustEnv("ZABPUSH_APP_KEY")
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
u, err := url.Parse(base)
if err != nil {
log.Fatal(err)
}
server := zabpush.NewServer(base, appID, secret) // one shared instance, safe for concurrent use
// ---------- consumer: receives pushes in this process ----------
client := zabpush.New(appKey, zabpush.Options{
Host: u.Host, Secure: u.Scheme == "https", UserID: "service-1", ClientName: "go-service",
OnState: func(s zabpush.State, info zabpush.StateInfo) { log.Printf("connection: %s %+v", s, info) },
// This process owns the secret, so it may sign directly. A client app would call YOUR backend instead.
Authorize: func(socketID, channel string) (string, error) { return server.Authenticate(socketID, channel) },
})
defer client.Close()
client.Subscribe("orders").Bind("*", func(m zabpush.Message) { // handlers should return quickly
log.Printf("order event=%s data=%s", m.Event, m.Data)
client.Read(m.ID)
})
client.Subscribe("private-user-service-1").Bind("*", func(m zabpush.Message) { log.Printf("PRIVATE %s: %s", m.Event, m.Data) })
// ---------- backend: HTTP endpoints ----------
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })
mux.HandleFunc("/notify", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
var req struct {
Channel string `json:"channel"`
Event string `json:"event"`
Data json.RawMessage `json:"data"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&req); err != nil {
http.Error(w, `{"error":"bad json"}`, http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
res, err := server.Publish(ctx, []string{req.Channel}, req.Event, req.Data, &zabpush.PublishOptions{TTL: 3600})
var apiErr *zabpush.APIError
switch {
case errors.As(err, &apiErr) && (apiErr.Status == 429 || apiErr.Status == 503):
http.Error(w, `{"error":"try again later"}`, http.StatusServiceUnavailable) // worth retrying
case errors.As(err, &apiErr):
http.Error(w, fmt.Sprintf(`{"error":%q,"upstream":%d}`, apiErr.Message, apiErr.Status), http.StatusBadGateway)
case err != nil:
http.Error(w, `{"error":"push service unreachable"}`, http.StatusBadGateway)
default:
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
})
mux.HandleFunc("/zabpush/auth", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
user := r.Header.Get("X-Demo-User") // replace with YOUR authentication (session, JWT, ...)
channel := r.FormValue("channel")
// YOUR rule, checked BEFORE signing: a user may only join their own private channel.
if user == "" || channel != "private-user-"+user {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
sig, _ := server.Authenticate(r.FormValue("socket_id"), channel)
fmt.Fprint(w, sig)
})
srv := &http.Server{Addr: ":" + port, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
log.Printf("backend on :%s", port)
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
<-ctx.Done() // Ctrl+C: shut down cleanly
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(shutdown)
log.Print("stopped")
}Run it
ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... ZABPUSH_APP_KEY=... go run ./examples/full
curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
curl -X POST localhost:3000/notify -d '{"channel":"private-user-service-1","event":"secret","data":{"hi":1}}'What the service logs
backend on :3000
connection: connecting {Attempt:0 RetryIn:0s Reason:}
connection: connected {Attempt:0 RetryIn:0s Reason:}
order event=order.shipped data={"id":981}
PRIVATE secret: {"hi":1}Built and run against a live server: publish, the error mapping (a bad channel returns the server's message, a wrong method returns 405), signing refused for another user's channel (403), and both pushes received by the consumer.
Configuration
zabpush.Options | Default | Description |
|---|---|---|
Host | required | Server address. |
Secure | false | Use wss://. Always true in production. |
UserID | random per process | Your unique id; persist it to keep replay and the inbox across restarts. |
ClientName / Platform | "" / go | Labels in your customer panel. |
NoReconnect | false | Disable auto-reconnect. |
ReconnectDelay / MaxReconnectDelay | 500 ms / 30 s | Backoff start and ceiling (with jitter). |
HeartbeatInterval / HeartbeatTimeout | 15 s / 10 s | Ping period and tolerated silence. |
DisableAutoAck | false | Stop sending "delivered" receipts. |
Authorize | nil | Optional. Only for private-* channels: func(socketID, channel string) (string, error), called in its own goroutine. |
OnState | nil | func(State, StateInfo). Panics inside it are recovered. |
Logger | nil (silent) | *log.Logger for diagnostics. |
Receiving messages
ch := c.Subscribe("orders")
ch.Bind("order.shipped", func(m zabpush.Message) {
var order struct{ ID int `json:"id"` }
if err := json.Unmarshal(m.Data, &order); err == nil { process(order.ID) }
})
ch.Bind("*", func(m zabpush.Message) { log.Println(m.Event) })
// m: ID (0 = live-only), Event, Channel, Data (json.RawMessage), TS, Live
c.Unsubscribe("orders")Handlers run on the client's read goroutine in order: keep them quick or hand off to a channel or worker pool. A panic in a handler is recovered and logged; it never stops the others or the connection.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No Authorize, no backend call. |
| Private | private-... | The optional Authorize callback, which asks your backend for a signature (see Private channels). |
const (
kHost = "cloud-zabpush.zabsys.com"
kAppKey = "APP_KEY"
kChannel = "app-1" // the channel name you publish to
kUserID = "user-42"
)
c := zabpush.New(kAppKey, zabpush.Options{Host: kHost, Secure: true, UserID: kUserID}) // no Authorize: public channel
c.Subscribe(kChannel).Bind("*", func(m zabpush.Message) { log.Println(string(m.Data)) })
c.Subscribe("news").Bind("*", func(m zabpush.Message) { log.Println(string(m.Data)) }) // many channels, one connection
c.Unsubscribe("news") // stop listening to one channel
c.UnsubscribeAll() // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that panics is recovered and logged: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
c := zabpush.New("APP_KEY", zabpush.Options{
Host: "cloud-zabpush.zabsys.com", Secure: true, UserID: userID,
Authorize: func(socketID, channel string) (string, error) {
resp, err := http.PostForm("https://api.example.com/zabpush/auth", url.Values{"socket_id": {socketID}, "channel": {channel}})
if err != nil { return "", err }
defer resp.Body.Close()
if resp.StatusCode != 200 { return "", fmt.Errorf("not allowed: %s", resp.Status) }
b, _ := io.ReadAll(resp.Body)
return string(b), nil
},
})
c.Subscribe("private-user-" + userID).Bind("*", func(m zabpush.Message) { log.Println(string(m.Data)) })http.HandleFunc("/zabpush/auth", func(w http.ResponseWriter, r *http.Request) {
user := currentUser(r) // YOUR authentication
if user == nil || r.FormValue("channel") != "private-user-"+user.ID { // YOUR rule, BEFORE signing
http.Error(w, "forbidden", http.StatusForbidden)
return
}
sig, _ := s.Authenticate(r.FormValue("socket_id"), r.FormValue("channel"))
fmt.Fprint(w, sig)
})Receipts and inbox
c.Read(m.ID)
c.Clicked(m.ID)
c.MarkAllRead("news")
in, err := c.Inbox(ctx, "news", 50) // in.Messages ([]InboxItem with .Read) and in.Unread
if err != nil { log.Println("inbox:", err) }Publishing
s.Publish(ctx, []string{"orders"}, "order.shipped", map[string]int{"id": 981}, nil)
noFCM := false
s.Publish(ctx, []string{"user-1", "user-2"}, "alert", map[string]int{"n": 1},
&zabpush.PublishOptions{TTL: 3600, Fallback: &noFCM}) // up to 100 channelsUse zabpush.NewServerWithToken(...) to publish with an access token instead of the secret (then Authenticate is unavailable). s.HTTP is an *http.Client you can replace.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your c.SubscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | c.State(): connecting, connected, reconnecting or disconnected |
| Is it live right now? | c.IsConnected() |
| Which channels am I on? | c.SubscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
c.State() // zabpush.StateConnecting | StateConnected | StateReconnecting | StateDisconnected
c.IsConnected() // true while live
c.SocketID() // id of the current connection ("" while disconnected)
c.SubscribedChannels() // ["app-1", "news"] (sorted): the channels you are subscribed to right now
// be told about every change instead of asking: Options{OnState: func(s zabpush.State, info zabpush.StateInfo) { ... }}The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | c.ReconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | c.Close() disconnects for good: no more retries. To connect again create a new client. |
c.ReconnectNow() // force a retry now
c.Close() // disconnect for good (on shutdown or logout). No more retries.
// to connect again later, create a new client with zabpush.New(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
zabpush.State | Meaning |
|---|---|
StateConnecting | First attempt. |
StateConnected | Live; subscriptions active; missed messages replayed. |
StateReconnecting | Retrying (StateInfo.Attempt). |
StateDisconnected | Lost (StateInfo.RetryIn) or closed. |
c.ReconnectNow() forces a reconnect; c.Close() stops the client. Pair it with signal handling for a clean shutdown:
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
<-ctx.Done()
c.Close()API reference
| Member | Description |
|---|---|
zabpush.NewServer(baseURL, appID, secret) | Publisher. Publish(ctx, channels, event, data, *PublishOptions) → *PublishResponse; Authenticate(socketID, channel). |
*APIError | Returned for non-200 answers: Status, Message. |
zabpush.New(appKey, Options) | Client; connects in the background. |
Subscribe(name) *Channel · Channel.Bind(event, fn) · Unsubscribe | Listening. |
Read · Clicked · MarkAllRead | Receipts. |
Inbox(ctx, channel, limit) | Server-kept history. |
RegisterDevice(token, platform) | FCM token. |
ReconnectNow() · Close() · State() · UserID() · SocketID() | Lifecycle and properties. |
Error handling
_, err := s.Publish(ctx, []string{"news"}, "promo", data, nil)
var apiErr *zabpush.APIError
switch {
case errors.As(err, &apiErr) && (apiErr.Status == 429 || apiErr.Status == 503):
retryLater() // rate limited / server unavailable
case errors.As(err, &apiErr) && apiErr.Status == 401:
log.Fatal("check the app secret and app id")
case err != nil:
log.Println("publish failed:", err) // network error or timeout
}Test your integration
cd sdk/go
ZP_HOST=cloud-zabpush.zabsys.com ZP_KEY=APP_KEY ZP_ID=1 ZP_SECRET=APP_SECRET go run ./examples/smoke
# -> state: connected / ok public / ok private / ok inbox / PASS gogo run ./examples/reconnect prints RECONNECTED after you cut the network for a moment.
Go-live checklist
- Secret from the environment; reuse one
Server; set timeouts through your ownHTTPclient if needed. - Consumers: stable
UserID,Secure: true, handlers that return quickly, graceful shutdown withClose(). - Retry 429/503 with backoff.
Troubleshooting
The client never leaves "connecting"
Logger: log.Default() to see dial errors. Usually the host/port is wrong, Secure does not match the server, or the app key is invalid (HTTP 401 on the handshake).My handler blocks other messages
go: module ... not found
go mod edit -replace command above.JJava
Spring, Jakarta EE, plain Java 11+ and Kotlin backends. Uses the JDK's own HTTP and WebSocket clients plus Gson.
Overview
ZabPushServer publishes and signs private channels. ZabPushClient is a realtime client with auto-reconnect, heartbeat, replay, receipts and an inbox. For an Android app use the Android SDK.
Requirements
- Java 11 or newer, Maven or Gradle, Gson 2.x (pulled in automatically).
Installation
cd sdk/java && mvn install # installs com.zabpush:zabpush:1.0.0 into your local Maven repository<dependency>
<groupId>com.zabpush</groupId>
<artifactId>zabpush</artifactId>
<version>1.0.0</version>
</dependency>repositories { mavenLocal(); mavenCentral() }
dependencies { implementation("com.zabpush:zabpush:1.0.0") }Quick start
ZabPushServer zp = new ZabPushServer("https://cloud-zabpush.zabsys.com", 1, System.getenv("ZABPUSH_APP_SECRET"));
JsonObject res = zp.publish("news", "promo", Map.of("title", "Hello", "body", "Sale today"));
System.out.println(res.getAsJsonArray("results").get(0)); // {"channel":"news","id":4127,"delivered":12,"stored":true}ZabPushClient.Options o = new ZabPushClient.Options();
o.host = "cloud-zabpush.zabsys.com"; o.secure = true; o.userId = "worker-1"; o.clientName = "my-service";
o.onState = (state, info) -> System.out.println("connection: " + state);
try (ZabPushClient zp = new ZabPushClient("APP_KEY", o)) {
zp.subscribe("news").bind("promo", m -> {
System.out.println(m.data); // Gson JsonElement
zp.read(m.id); // "delivered" is automatic
});
Thread.sleep(Long.MAX_VALUE);
}Complete example
A complete service in one file using only the JDK (plus Gson): an HTTP backend built on the JDK's own server (publish endpoint and private-channel signing) and a consumer in the same process, with a shutdown hook.
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.zabpush.ZabPushClient;
import com.zabpush.ZabPushException;
import com.zabpush.ZabPushServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* A complete Java service: an HTTP backend that publishes pushes AND a consumer that receives them. JDK only (plus Gson).
*
* POST /notify publish a push {"channel":"orders","event":"order.shipped","data":{...}}
* POST /zabpush/auth sign a private channel form: socket_id, channel (only the signed-in user's own channel)
* GET /health
*
* Run: ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... ZABPUSH_APP_KEY=... java -cp "out:gson.jar" Full
* Try: curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
*
* In Spring, the two handlers become @PostMapping methods and ZabPushServer a @Bean (see the Java page of the docs).
*/
public class Full {
private static final Gson GSON = new Gson();
public static void main(String[] args) throws Exception {
String base = need("ZABPUSH_URL");
long appId = Long.parseLong(need("ZABPUSH_APP_ID"));
String secret = need("ZABPUSH_APP_SECRET"), appKey = need("ZABPUSH_APP_KEY");
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "3000"));
ZabPushServer server = new ZabPushServer(base, appId, secret); // one shared instance
// ---------- consumer: receives pushes in this process ----------
URI u = URI.create(base);
ZabPushClient.Options o = new ZabPushClient.Options();
o.host = u.getAuthority();
o.secure = "https".equals(u.getScheme());
o.userId = "service-1";
o.clientName = "java-service";
o.onState = (state, info) -> System.out.println("connection: " + state);
// This process owns the secret, so it may sign directly. A client app would call YOUR backend instead.
o.authorizer = server::authenticate;
ZabPushClient client = new ZabPushClient(appKey, o);
client.subscribe("orders").bind("*", m -> { // handlers run on the receive thread: keep them quick
System.out.println("order event=" + m.event + " data=" + m.data);
client.read(m.id);
});
client.subscribe("private-user-service-1").bind("*", m -> System.out.println("PRIVATE " + m.event + ": " + m.data));
// ---------- backend: HTTP endpoints (JDK built-in server) ----------
HttpServer http = HttpServer.create(new InetSocketAddress(port), 0);
http.createContext("/health", ex -> reply(ex, 200, "text/plain", "ok"));
http.createContext("/notify", ex -> {
if (!"POST".equals(ex.getRequestMethod())) { reply(ex, 405, "text/plain", "POST only"); return; }
try {
JsonObject req = GSON.fromJson(body(ex), JsonObject.class);
JsonObject res = server.publish(java.util.List.of(req.get("channel").getAsString()), req.get("event").getAsString(),
req.get("data"), 3600, null); // replayable for an hour
reply(ex, 200, "application/json", res.toString());
} catch (ZabPushException e) {
// 429 / 503 are worth retrying later; 401 means a wrong secret; 400 a bad channel/event/data
int s = e.getStatus() == 429 || e.getStatus() == 503 ? 503 : 502;
reply(ex, s, "application/json", GSON.toJson(Map.of("error", String.valueOf(e.getMessage()), "upstream", e.getStatus())));
} catch (RuntimeException e) {
reply(ex, 400, "application/json", GSON.toJson(Map.of("error", "bad request")));
}
});
http.createContext("/zabpush/auth", ex -> {
if (!"POST".equals(ex.getRequestMethod())) { reply(ex, 405, "text/plain", "POST only"); return; }
Map<String, String> form = parseForm(body(ex));
String user = ex.getRequestHeaders().getFirst("X-Demo-User"); // replace with YOUR authentication
String channel = form.getOrDefault("channel", "");
// YOUR rule, checked BEFORE signing: a user may only join their own private channel.
if (user == null || !channel.equals("private-user-" + user)) { reply(ex, 403, "text/plain", "forbidden"); return; }
reply(ex, 200, "text/plain", server.authenticate(form.getOrDefault("socket_id", ""), channel));
});
http.start();
System.out.println("backend on :" + port);
Runtime.getRuntime().addShutdownHook(new Thread(() -> { client.close(); http.stop(0); System.out.println("stopped"); }));
Thread.currentThread().join(); // run until Ctrl+C
}
private static String need(String k) {
String v = System.getenv(k);
if (v == null || v.isEmpty()) { System.err.println("set " + k); System.exit(2); }
return v;
}
private static String body(HttpExchange ex) throws IOException {
byte[] b = ex.getRequestBody().readNBytes(64 * 1024);
return new String(b, StandardCharsets.UTF_8);
}
private static void reply(HttpExchange ex, int code, String type, String text) throws IOException {
byte[] b = text.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", type);
ex.sendResponseHeaders(code, b.length);
ex.getResponseBody().write(b);
ex.close();
}
private static Map<String, String> parseForm(String s) {
Map<String, String> m = new HashMap<>();
for (String pair : s.split("&")) {
int i = pair.indexOf('=');
if (i > 0) m.put(URLDecoder.decode(pair.substring(0, i), StandardCharsets.UTF_8), URLDecoder.decode(pair.substring(i + 1), StandardCharsets.UTF_8));
}
return m;
}
}Run it
# compile against the SDK sources and Gson (use mvn / gradle in a real project)
javac -cp gson.jar -d out sdk/java/src/main/java/com/zabpush/*.java sdk/java/examples/Full.java
ZABPUSH_URL=https://cloud-zabpush.zabsys.com ZABPUSH_APP_ID=1 ZABPUSH_APP_SECRET=... ZABPUSH_APP_KEY=... java -cp "out:gson.jar" Full # Windows: out;gson.jar
curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'What the service prints
connection: CONNECTING
backend on :3000
connection: CONNECTED
order event=order.shipped data={"id":981}
PRIVATE secret: {"hi":1}Compiled and run against a live server: publish, error mapping, signing for the user's own channel (and 403 for another user's), and both pushes received by the consumer.
Configuration
ZabPushClient.Options | Default | Description |
|---|---|---|
host | cloud-zabpush.zabsys.com | Server address. |
secure | false | Use wss://. Always true in production. |
userId | random per process | Your unique id; persist it to keep replay and the inbox across restarts. |
clientName / platform | "" / java | Labels in your customer panel. |
reconnect | true | Reconnect automatically. |
reconnectDelayMs / maxReconnectDelayMs | 500 / 30000 | Backoff start and ceiling (with jitter). |
heartbeatIntervalMs / heartbeatTimeoutMs | 15000 / 10000 | Ping period and tolerated silence. |
autoAck | true | Send "delivered" receipts. |
authorizer | null | Optional. Only for private-* channels: (socketId, channel) -> String for private channels (runs off the receive thread). |
onState | null | (State, Map) -> void. |
Receiving messages
zp.subscribe("orders")
.bind("order.shipped", m -> notify(m.data.getAsJsonObject().get("id").getAsInt()))
.bind("*", m -> System.out.println(m.event));
// m: id (0 = live-only), event, channel, data (JsonElement), ts, live
zp.unsubscribe("orders");Handlers run on the JDK WebSocket receive thread: keep them quick or hand work to an executor. A RuntimeException in one handler is caught and printed; it never stops the others or the connection.
Channels: subscribe and unsubscribe
A channel is just a name you choose (news, orders, user-42). Nothing is created on the server beforehand: you subscribe, and whoever publishes to that name reaches you. One connection carries any number of channels.
| Kind | Name | What you need |
|---|---|---|
| Public | anything not starting with private- | Only the app key and the host. No authorizer, no backend call. |
| Private | private-... | The optional authorizer callback, which asks your backend for a signature (see Private channels). |
String kHost = "cloud-zabpush.zabsys.com", kAppKey = "APP_KEY", kChannel = "app-1", kUserId = "user-42";
ZabPushClient.Options o = new ZabPushClient.Options();
o.host = kHost; o.secure = true; o.userId = kUserId; // no authorizer: public channel
ZabPushClient zp = new ZabPushClient(kAppKey, o);
zp.subscribe(kChannel).bind("*", m -> System.out.println(m.data));
zp.subscribe("news").bind("*", m -> System.out.println(m.data)); // as many channels as you like, one connection
zp.unsubscribe("news"); // stop listening to one channel
zp.unsubscribeAll(); // leave every channel at once (connection stays open)After every reconnect the client subscribes again to all its channels by itself and asks for what it missed, so you subscribe once; you do not repeat it when the connection comes back.
Dispose: leave one channel with unsubscribe, leave all of them with unsubscribeAll (the connection stays open and you can subscribe again), or disconnect completely with close (see Reconnect and disconnect).
One user never affects another. A handler that throws is caught and skipped: the other handlers, the other channels and the connection carry on. If this user's app crashes or its connection is cut, the server simply drops that one connection and removes it from its channels; every other user keeps receiving. When the user comes back it is replayed what it missed.
Private channels
You only need it for channels whose name starts with private-. To receive on public channels, give the client just the app key and the host: no backend, no signing. Without it, subscribing to a private- channel does not crash or disconnect anything; that one channel is simply not subscribed and a message is logged.
o.authorizer = (socketId, channel) -> {
HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.example.com/zabpush/auth"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString("socket_id=" + socketId + "&channel=" + channel)).build();
HttpResponse<String> r = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
if (r.statusCode() != 200) throw new IllegalStateException("not allowed");
return r.body();
};@PostMapping("/zabpush/auth")
String auth(@RequestParam("socket_id") String socketId, @RequestParam String channel, Principal user) {
if (!channel.equals("private-user-" + user.getName())) // YOUR rule, BEFORE signing
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
return zp.authenticate(socketId, channel);
}Receipts and inbox
zp.read(m.id);
zp.clicked(m.id);
zp.markAllRead("news");
ZabPushClient.Inbox inbox = zp.inbox("news", 50).get(10, TimeUnit.SECONDS); // CompletableFuture
System.out.println(inbox.unread + " unread of " + inbox.messages.size());Publishing
zp.publish("orders", "order.shipped", Map.of("id", 981));
zp.publish(List.of("user-1", "user-2"), "alert", Map.of("n", 1), 3600, Boolean.FALSE); // ttl seconds, fallback off
@Bean ZabPushServer zabPush(@Value("${zabpush.url}") String url, @Value("${zabpush.app-id}") long id,
@Value("${zabpush.secret}") String secret) { return new ZabPushServer(url, id, secret); }The last argument pair is ttlSeconds (0 = server default) and fallback (null = default on). Use new ZabPushServer(url, id, null, token) for an access token.
Connection status and channels
You can always ask the client two things: is it connected and which channels is it subscribed to right now. Use them for a "connected" indicator, a settings or debug screen, or to check that your zp.subscribedChannels() list is what you expect.
| Question | Use |
|---|---|
| What is the connection doing? | zp.getState(): connecting, connected, reconnecting or disconnected |
| Is it live right now? | zp.isConnected() |
| Which channels am I on? | zp.subscribedChannels(): the channels you subscribed to and did not unsubscribe from. After a reconnect they are re-subscribed automatically, so the list stays the same while the connection comes and goes. |
zp.getState(); // State.CONNECTING | CONNECTED | RECONNECTING | DISCONNECTED
zp.isConnected(); // true while live
zp.getSocketId(); // id of the current connection (null while disconnected)
zp.subscribedChannels(); // ["app-1", "news"]: the channels you are subscribed to right now
// be told about every change instead of asking: o.onState = (state, info) -> { ... }The list is what this client asked for; the server confirms each subscription when the connection is live. A private channel that could not be signed (see Private channels) is still in the list but gets no messages until it is fixed.
Reconnect and disconnect
| Situation | What happens |
|---|---|
| The connection drops (network lost, server restarted, phone asleep) | The client retries by itself, first after about 0.5 s, then doubling with a little randomness up to 30 s, until it works. Nothing for you to code. |
| A silently dead connection | The client pings every ~15 s and gives up on a silent socket after a further 10 s (the server drops silent sockets after 40 s), then reconnects. |
| It is back | The client subscribes again to every channel and the server replays the messages missed meanwhile (up to 100 per channel). Receipts for them are sent automatically. |
| You want it now | zp.reconnectNow() skips the waiting (good in a "network is back" or "app came to the foreground" callback). |
| You are done (logout, screen closed, process ending) | zp.close() disconnects for good: no more retries. To connect again create a new client. |
zp.reconnectNow(); // force a retry now
zp.close(); // disconnect for good (also done by try-with-resources). No more retries.
// to connect again later, create a new ZabPushClient(...)If you never call close, the client keeps itself connected for as long as the process lives, which is what you want for a push connection. Change the timings with the reconnect and heartbeat options in Configuration.
Connection lifecycle
State | Meaning |
|---|---|
CONNECTING | First attempt. |
CONNECTED | Live; subscriptions active; missed messages replayed. |
RECONNECTING | Retrying after a drop. |
DISCONNECTED | Lost (info has retryInMs) or closed. |
zp.reconnectNow() forces a reconnect; zp.close() (or try-with-resources) disconnects for good. In Spring, create the client as a bean with destroyMethod = "close".
API reference
| Member | Description |
|---|---|
ZabPushServer.publish(channel, event, data) | One channel. Returns a Gson JsonObject. |
ZabPushServer.publish(channels, event, data, ttlSeconds, fallback) | Up to 100 channels. |
ZabPushServer.authenticate(socketId, channel) | Hex signature. |
ZabPushException | Unchecked: getMessage(), getStatus() (0 = network error). |
new ZabPushClient(appKey, options) | Connects in the background; AutoCloseable. |
subscribe(channel).bind(event, handler) · unsubscribe | Listening. |
read · clicked · markAllRead | Receipts. |
inbox(channel, limit) | CompletableFuture<Inbox>. |
registerDevice(token, platform) | FCM token. |
reconnectNow() · close() · getState() · getUserId() · getSocketId() | Lifecycle and properties. |
Error handling
try {
zp.publish("news", "promo", data);
} catch (ZabPushException e) {
switch (e.getStatus()) {
case 429, 503 -> retryLater(); // rate limited / server unavailable
case 401 -> throw new IllegalStateException("check the app secret and id", e);
case 400 -> throw new IllegalArgumentException(e.getMessage(), e);
default -> log.error("publish failed", e); // 0 = network error or timeout
}
}(The case 429, 503 -> form needs Java 14+; use if/else on Java 11.)
Test your integration
.\sdk\run-smoke.ps1 -Key APP_KEY -Id 1 -Secret APP_SECRET # downloads Gson and runs the Java test with the others
# expect: state: CONNECTED / ok public / ok private / ok inbox / PASS javasdk/java/examples/Reconnect.java prints RECONNECTED after you cut the network for a moment.
Go-live checklist
- Secret from configuration or a vault; one shared
ZabPushServer. - Consumers: stable
userId,secure = true, quick handlers, close on shutdown. - Retry 429/503 with backoff.
Troubleshooting
NoClassDefFoundError: com/google/gson/...
The state flips between CONNECTING and DISCONNECTED
host, secure and the app key (401 means a wrong key).Nothing printed and the program exits
Thread.sleep, a server, or CountDownLatch).PPHP
Send pushes from Laravel, Symfony, WordPress or plain PHP, and sign private channels. Browsers and apps receive them with the other SDKs.
Overview
PHP is request-based, so it is used to send. The SDK uses cURL when available and PHP streams otherwise, and throws a clear exception on any failure. Pair it with the JavaScript, Flutter, Android or iOS client to receive.
Requirements
- PHP 7.4 or newer with the
jsonextension.curlrecommended; otherwiseallow_url_fopenmust be on. - Your app id and app secret (or an access token).
Installation
{
"repositories": [ { "type": "path", "url": "../zabpush/sdk/php" } ],
"require": { "zabsys/zabpush": "*" }
}composer update zabsys/zabpushWithout Composer: require 'ZabPush/src/ZabPushException.php'; require 'ZabPush/src/Server.php';
Quick start
<?php
use ZabPush\Server;
use ZabPush\ZabPushException;
$zp = new Server('https://cloud-zabpush.zabsys.com', 1, getenv('ZABPUSH_APP_SECRET'));
try {
$res = $zp->publish('news', 'promo', ['title' => 'Hello', 'body' => 'Sale today']);
echo $res['results'][0]['delivered'] . " live users reached\n";
} catch (ZabPushException $e) {
error_log('ZabPush: ' . $e->getMessage()); // $e->status is the HTTP status (0 = could not connect)
}Complete example
A complete backend in one file (a front controller): a publish endpoint and a private-channel signing endpoint that only signs the signed-in user's own channel. Run it with PHP's built-in server, or move each branch into a Laravel or Symfony controller.
<?php
// A complete PHP backend for ZabPush in one file (front controller):
//
// POST /notify publish a push {"channel":"orders","event":"order.shipped","data":{...}}
// POST /zabpush/auth sign a private channel form: socket_id, channel (only the signed-in user's own channel)
// GET /health
//
// Run locally: ZP_URL=https://cloud-zabpush.zabsys.com ZP_ID=1 ZP_SECRET=... php -S localhost:3000 examples/api.php
// Try: curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
//
// In production put this behind PHP-FPM/Apache/nginx, or move each branch into a Laravel/Symfony controller:
// the ZabPush\Server calls are identical.
declare(strict_types=1);
require __DIR__ . '/../src/ZabPushException.php'; // with Composer: require 'vendor/autoload.php';
require __DIR__ . '/../src/Server.php';
use ZabPush\Server;
use ZabPush\ZabPushException;
$url = getenv('ZP_URL');
$appId = getenv('ZP_ID');
$secret = getenv('ZP_SECRET');
if (!$url || !$appId || !$secret) {
http_response_code(500);
exit('set ZP_URL, ZP_ID and ZP_SECRET');
}
$zp = new Server($url, (int) $appId, $secret); // create once per request; it holds no connection
function reply(int $code, $body, string $type = 'application/json'): void
{
http_response_code($code);
header("Content-Type: $type");
echo is_string($body) ? $body : json_encode($body);
exit;
}
/** Replace with YOUR authentication ($_SESSION, a JWT, ...). Here: a header, to keep the example dependency-free. */
function currentUser(): ?string
{
return $_SERVER['HTTP_X_DEMO_USER'] ?? null;
}
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($path === '/health') {
reply(200, 'ok', 'text/plain');
}
if ($path === '/notify' && $method === 'POST') {
$req = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($req) || !isset($req['channel'], $req['event']) || !array_key_exists('data', $req)) {
reply(400, ['error' => 'need channel, event and data']);
}
try {
// ttl: replayable for an hour. Add 'fallback' => false to skip the FCM push for offline devices.
reply(200, $zp->publish($req['channel'], $req['event'], $req['data'], ['ttl' => 3600]));
} catch (ZabPushException $e) {
// 429 / 503 / 0 (could not connect) are worth retrying later; 401 = wrong secret; 400 = bad channel/event/data
$retry = in_array($e->status, [429, 503, 0], true);
reply($retry ? 503 : 502, ['error' => $e->getMessage(), 'upstream' => $e->status]);
}
}
if ($path === '/zabpush/auth' && $method === 'POST') {
$user = currentUser();
$channel = (string) ($_POST['channel'] ?? '');
// YOUR rule, checked BEFORE signing: a user may only join their own private channel.
if ($user === null || $channel !== "private-user-$user") {
reply(403, 'forbidden', 'text/plain');
}
reply(200, $zp->authenticate((string) ($_POST['socket_id'] ?? ''), $channel), 'text/plain');
}
reply(404, ['error' => 'not found']);Run it
ZP_URL=https://cloud-zabpush.zabsys.com ZP_ID=1 ZP_SECRET=... php -S localhost:3000 api.php
curl -X POST localhost:3000/notify -d '{"channel":"orders","event":"order.shipped","data":{"id":981}}'
curl -X POST localhost:3000/zabpush/auth -H "X-Demo-User: alice" -d "socket_id=abc123&channel=private-user-alice"
curl -X POST localhost:3000/zabpush/auth -H "X-Demo-User: alice" -d "socket_id=abc123&channel=private-user-bob" # 403What you should see
{"results":[{"channel":"orders","id":4127457,"delivered":1,"stored":true}]}
4ebfdf28b19ac7d3553fdf9ba4c6360c3acea7b55c638712dd63b3731a53dbef <- signature (matches Node and the other SDKs)
(403 forbidden)Run with PHP's built-in server against a live server: publish, a bad channel returns the server's message, a missing field returns 400, the signature matches an independent HMAC, signing is refused (403) for another user's channel, and unknown paths return 404.
Configuration
| Constructor argument | Description |
|---|---|
$baseUrl | Your server, e.g. https://cloud-zabpush.zabsys.com. |
$appId | The numeric app id. |
$secret | App secret (needed for authenticate()). |
$token | Access token (zpt_…) for publishing only. |
$timeout | Seconds, default 10. |
Publishing
$zp->publish('orders', 'order.shipped', ['id' => 981]);
$zp->publish(['user-1', 'user-2'], 'alert', ['n' => 1], ['ttl' => 3600, 'fallback' => false]); // up to 100 channelsOptions: ttl (seconds the message stays replayable, max 30 days) and fallback (false skips the FCM push to offline devices). Each result has channel, id, delivered and stored (false means the server's database was down and the push went to live clients only).
Private channels
<?php
// POST /zabpush/auth: called by the client's authorize callback. Check the signed-in user FIRST.
session_start();
if (($_POST['channel'] ?? '') !== 'private-user-' . ($_SESSION['user_id'] ?? '')) {
http_response_code(403);
exit('forbidden');
}
header('Content-Type: text/plain');
echo $zp->authenticate($_POST['socket_id'], $_POST['channel']);Route::post('/zabpush/auth', function (Request $r, \ZabPush\Server $zp) {
abort_unless($r->channel === 'private-user-' . $r->user()->id, 403); // YOUR rule, BEFORE signing
return response($zp->authenticate($r->socket_id, $r->channel), 200, ['Content-Type' => 'text/plain']);
})->middleware('auth');Laravel, Symfony, WordPress
$this->app->singleton(\ZabPush\Server::class, fn () =>
new \ZabPush\Server(config('services.zabpush.url'), config('services.zabpush.app_id'), config('services.zabpush.secret')));public function handle(\ZabPush\Server $zp): void
{
$zp->publish("user-{$this->order->user_id}", 'order.shipped', ['id' => $this->order->id]);
}ZabPush\Server:
arguments: ['%env(ZABPUSH_URL)%', '%env(int:ZABPUSH_APP_ID)%', '%env(ZABPUSH_APP_SECRET)%']add_action('publish_post', function ($id) {
$zp = new \ZabPush\Server(ZABPUSH_URL, ZABPUSH_APP_ID, ZABPUSH_APP_SECRET); // constants in wp-config.php
$zp->publish('news', 'new-post', ['title' => get_the_title($id), 'url' => get_permalink($id)]);
});Send from a queue worker rather than inside a web request when you can, so a slow network never delays your page.
API reference
| Member | Description |
|---|---|
new ZabPush\Server($baseUrl, $appId, $secret = null, $token = null, $timeout = 10.0) | Create once and reuse. |
publish($channels, $event, $data, array $options = []) | Returns ['results' => [['channel','id','delivered','stored'], …]]. Throws ZabPushException. |
authenticate($socketId, $channel) | Hex signature for a private channel. Needs the secret. |
ZabPush\ZabPushException | getMessage(), $status, $body. |
Error handling
try {
$zp->publish('news', 'promo', $data);
} catch (ZabPushException $e) {
if (in_array($e->status, [429, 503], true) || $e->status === 0) {
retryLater(); // rate limited, unavailable, or could not connect
} elseif ($e->status === 401) {
throw new RuntimeException('check the app secret and id');
} else {
error_log('ZabPush: ' . $e->getMessage()); // 400 = invalid channel/event/data
}
}Test your integration
# 1. a listener (needs Node): ZP_KEY=APP_KEY node sdk/js/examples/wait-for.js news promo
# 2. send from PHP:
ZP_HOST=cloud-zabpush.zabsys.com ZP_ID=1 ZP_SECRET=APP_SECRET php sdk/php/examples/publish.php news
# -> published id=... delivered_live=1 stored=yes and the listener prints RECEIVED {...}.\sdk\run-smoke.ps1 runs this check automatically.
Go-live checklist
- The secret lives in an environment variable or secret store, never in the repository or a public web root.
- HTTPS server URL;
curlextension enabled; timeouts suit your hosting. - The auth endpoint checks the user first and runs only over HTTPS.
- Failures are logged and retried (queue job with backoff).
Troubleshooting
"cannot reach server"
curl https://cloud-zabpush.zabsys.com/healthz. On shared hosting outbound connections may be blocked; ask the host or use a different plan.HTTP 401
Works in CLI but not on the web server
.env.FAQ
Quick answers to the questions that come up most.
General
Do I need a client SDK and a server SDK?
Can the app send messages to other users directly?
What happens if a user is offline when I send?
How many users can connect?
Can I use my own user ids?
userId (user_id in Python). Receipts, the inbox and replay follow that id.Troubleshooting
Nothing arrives
HTTP 401 when connecting
HTTP 401 when publishing
Private channel says “forbidden”
socket_id:channel with the current connection's socket id.HTTP 429 or “connection limit reached”
Works locally, fails in production
wss:// (secure: true) on a domain with a valid certificate, and any proxy of your own in between must forward WebSocket upgrades.{}HTTP & WebSocket API
Everything the SDKs do is plain HTTPS plus WebSocket. Use this page to integrate from any language, or to understand exactly what happens on the wire.
Overview
| Direction | Transport | Credential |
|---|---|---|
| Send (your backend → ZabPush) | POST /api/v1/apps/{appId}/events over HTTPS | App secret, or your customer secret key (zps_…) with X-Access-Key, in Authorization: Bearer …. Ask us for the REST API reference for apps, messages and receipts. |
| Receive (ZabPush → your apps) | wss://host/ws?key=APP_KEY&… WebSocket | The public app key in the URL |
| Health | GET /healthz (process alive) · GET /readyz (database reachable) | none |
Send: publish endpoint
POST /api/v1/apps/{appId}/events
Authorization: Bearer APP_SECRET (or your customer secret key: zps_... plus X-Access-Key: zpk_...)
Content-Type: application/json
{ "channels": ["news", "user-42"], // or "channel": "news"; up to 100
"event": "promo",
"data": { "title": "Hello", "body": "Sale today" },
"ttl": 3600, // optional: seconds replayable (max 30 days)
"fallback": true } // optional: FCM for offline devices (default true){ "results": [
{ "channel": "news", "id": 4127, "delivered": 12, "stored": true },
{ "channel": "user-42", "id": 4128, "delivered": 1, "stored": true } ] }| Field | Meaning |
|---|---|
id | The stored message id (0 if not stored). |
delivered | Live clients that received it right now. |
stored | false means the database was down: delivered live only, not replayable. |
Status codes
| Code | Meaning | What to do |
|---|---|---|
200 | Accepted. | — |
400 | Invalid JSON, channel/event name, missing data, or too many channels. Body limit 64 KB. | Fix the request; do not retry unchanged. |
401 | Wrong secret/token, wrong app id, or revoked token. | Check credentials. |
429 | Rate limit (publish rate per app, or too many failed attempts). Retry-After header may be present. | Back off and retry. |
503 | The server could not look up the app (database unavailable and not cached). | Retry with backoff. |
Channel and event names may contain letters, digits and _ - = @ , . ; : # / (max 190). Errors are JSON: {"error": "message"}.
Send: examples
curl -X POST https://cloud-zabpush.zabsys.com/api/v1/apps/1/events \
-H "Authorization: Bearer APP_SECRET" \
-H "Content-Type: application/json" \
-d '{"channel":"news","event":"promo","data":{"title":"Hello"}}'$body = @{ channel = 'news'; event = 'promo'; data = @{ title = 'Hello' } } | ConvertTo-Json -Depth 5
Invoke-RestMethod -Method Post -Uri 'https://cloud-zabpush.zabsys.com/api/v1/apps/1/events' `
-Headers @{ Authorization = 'Bearer APP_SECRET' } -ContentType 'application/json' -Body $bodyconst res = await fetch('https://cloud-zabpush.zabsys.com/api/v1/apps/1/events', {
method: 'POST',
headers: { Authorization: 'Bearer APP_SECRET', 'Content-Type': 'application/json' },
body: JSON.stringify({ channel: 'news', event: 'promo', data: { title: 'Hello' } }),
});
console.log(await res.json());import requests
r = requests.post("https://cloud-zabpush.zabsys.com/api/v1/apps/1/events",
headers={"Authorization": "Bearer APP_SECRET"},
json={"channel": "news", "event": "promo", "data": {"title": "Hello"}}, timeout=10)
r.raise_for_status()
print(r.json())Ruby, Rust, Swift, Kotlin/JVM, Lua, shell scripts, IoT devices: any HTTPS client works. The first four examples above were run against a live server; port the same request shape to your language.
Receive: connecting
wss://cloud-zabpush.zabsys.com/ws?key=APP_KEY&cid=USER_ID&client=NAME&platform=PLATFORM| Parameter | Required | Meaning |
|---|---|---|
key | yes | The public app key. |
cid | recommended | Your user id (max 64 chars of letters, digits and . _ @ : -). If omitted the server assigns one and returns it. |
client | no | Name shown in your customer panel. |
platform | no | Platform label shown in your customer panel. |
Handshake failures: 401 wrong app key, 429 too many connection attempts from your IP, 503 connection limit or database unavailable.
Receive: frames
<- {"event":"zabpush:connected","data":{"socket_id":"a1b2c3","user_id":"USER_ID"}}
-> {"event":"zabpush:subscribe","channel":"news","since":0}
<- {"event":"zabpush:subscribed","channel":"news"}
<- {"id":4127,"event":"promo","channel":"news","data":{"title":"Hello"},"ts":1760000000}
-> {"event":"zabpush:ack","id":4127,"status":"delivered"}
-> {"event":"zabpush:ack","id":4127,"status":"read"}
-> {"event":"zabpush:inbox","channel":"news","limit":50,"req":"r1"}
<- {"event":"zabpush:inbox","req":"r1","data":{"messages":[{"id":4127,"event":"promo","data":{...},"ts":1760000000,"read":true}],"unread":0}}Frames you send
| Frame | Meaning |
|---|---|
zabpush:subscribe {channel, since?, auth?} | since = last message id you saw (the server also remembers what each user id acknowledged). auth is required for private-*. |
zabpush:unsubscribe {channel} | Stop listening. |
zabpush:unsubscribe_all | Stop listening to every channel at once. The connection stays open. |
zabpush:ack {id, status} | status: delivered, read, clicked. Or {channel, status:"read_all"}. |
zabpush:inbox {channel, limit, req} | The answer carries the same req. |
zabpush:register_device {token, platform} | FCM token for offline pushes. |
zabpush:ping | Answered with zabpush:pong. |
Frames you receive
| Frame | Meaning |
|---|---|
zabpush:connected {socket_id, user_id} | First frame. Subscribe now. The socket_id is needed for private-channel signatures. |
zabpush:subscribed {channel} | Subscription accepted (replayed messages follow). |
zabpush:subscription_error {channel, data} | Rejected: forbidden (bad signature), invalid channel, too many channels. |
{id, event, channel, data, ts} | A push. id: 0 with live: true is a live-only message: do not acknowledge it. |
zabpush:pong · zabpush:inbox | Replies. |
Limits: frames you send may be up to 16 KB; at most about 50 control frames per second per connection (receipts have a separate, larger allowance). Exceeding them closes the connection with code 1008.
Private channel signature
Subscribe frames for private-* channels must include auth = hex( HMAC_SHA256( app_secret, socket_id + ":" + channel ) ), computed by your backend after it has checked the user may join.
printf '%s' "SOCKET_ID:private-user-42" | openssl dgst -sha256 -hmac "APP_SECRET" -hex | sed 's/^.* //'import hmac, hashlib
sig = hmac.new(secret.encode(), f"{socket_id}:{channel}".encode(), hashlib.sha256).hexdigest()const sig = require('crypto').createHmac('sha256', secret).update(`${socketId}:${channel}`).digest('hex');$sig = hash_hmac('sha256', $socketId . ':' . $channel, $secret);All the server SDKs produce identical signatures for the same input (checked between PHP and Node).
Writing your own client: reconnecting
- On any close or error, wait
min(30 s, 0.5 s × 2attempt) × random(0.8–1.2), then connect again. Reset the attempt counter when you receivezabpush:connected. - Send
zabpush:pingevery 15 seconds. If nothing at all arrives for 25 seconds, close the socket yourself and reconnect: it is dead. - After
zabpush:connected, re-send everysubscribe(with a fresh signature for private channels) including your last seen message id assince. The server replays what you missed. - Keep the same
cidon every reconnect so receipts and replay continue. - Acknowledge
deliveredfor every message whoseidis not 0.
Raw WebSocket example
const ws = new WebSocket('wss://cloud-zabpush.zabsys.com/ws?key=APP_KEY&cid=user-42');
ws.onmessage = (e) => {
const f = JSON.parse(e.data);
if (f.event === 'zabpush:connected') ws.send(JSON.stringify({ event: 'zabpush:subscribe', channel: 'news', since: 0 }));
else if (f.id) {
console.log(f.event, f.data);
ws.send(JSON.stringify({ event: 'zabpush:ack', id: f.id, status: 'delivered' }));
}
};npx wscat -c "wss://cloud-zabpush.zabsys.com/ws?key=APP_KEY&cid=me"
> {"event":"zabpush:subscribe","channel":"news"}It already implements reconnecting, replay, heartbeat, receipts and error handling, which is easy to get subtly wrong.
Complete example
Two complete programs that use no SDK at all: a shell script that publishes and signs with only curl and openssl, and a raw WebSocket client that implements connect, subscribe, acknowledge, heartbeat and reconnect by hand. Port either to any language.
#!/usr/bin/env bash
# Publish a push and sign a private channel from the shell, using only curl and openssl.
#
# ZP_URL=https://cloud-zabpush.zabsys.com ZP_ID=1 ZP_SECRET=APP_SECRET ./publish.sh news promo '{"title":"Hello"}'
#
# Private channel signature (what your backend returns to a client):
# ZP_SECRET=APP_SECRET ./publish.sh sign SOCKET_ID private-user-42
set -euo pipefail
if [ "${1:-}" = "sign" ]; then
: "${ZP_SECRET:?set ZP_SECRET}"
# hex( HMAC-SHA256( app_secret, socket_id + ":" + channel ) )
printf '%s' "$2:$3" | openssl dgst -sha256 -hmac "$ZP_SECRET" -hex | sed 's/^.* //'
exit 0
fi
: "${ZP_URL:?set ZP_URL, e.g. https://cloud-zabpush.zabsys.com}" "${ZP_ID:?set ZP_ID}" "${ZP_SECRET:?set ZP_SECRET}"
channel="${1:?usage: publish.sh CHANNEL EVENT JSON_DATA}"; event="${2:?event}"; data="${3:?json data}"
# -w prints the HTTP status after the body so scripts can react to 429 (rate limited) / 503 (try again later)
response=$(curl -sS -X POST "$ZP_URL/api/v1/apps/$ZP_ID/events" \
-H "Authorization: Bearer $ZP_SECRET" \
-H "Content-Type: application/json" \
-d "{\"channel\":\"$channel\",\"event\":\"$event\",\"data\":$data,\"ttl\":3600}" \
-w '\n%{http_code}')
status=${response##*$'\n'}
body=${response%$'\n'*}
case "$status" in
200) echo "$body" ;;
429|503) echo "retry later ($status): $body" >&2; exit 75 ;; # EX_TEMPFAIL
401) echo "wrong secret or app id: $body" >&2; exit 1 ;;
*) echo "failed ($status): $body" >&2; exit 1 ;;
esac// A complete ZabPush client written from the raw protocol, with NO SDK. Node 22+ (global WebSocket) or any browser.
// It shows exactly what an SDK does on the wire, so you can port it to any language that has a WebSocket library:
// connect -> subscribe (with the last seen id) -> acknowledge -> heartbeat -> reconnect with backoff.
//
// ZP_HOST=cloud-zabpush.zabsys.com ZP_SECURE=1 ZP_KEY=APP_KEY ZP_USER=alice node raw-client.js news
const [channel = 'news'] = process.argv.slice(2);
const HOST = process.env.ZP_HOST || 'cloud-zabpush.zabsys.com';
const KEY = process.env.ZP_KEY;
const USER = process.env.ZP_USER || 'raw-client'; // keep the SAME id on every reconnect: replay and receipts follow it
const SCHEME = process.env.ZP_SECURE === '0' ? 'ws' : 'wss';
if (!KEY) { console.error('set ZP_KEY'); process.exit(2); }
let attempt = 0; // reconnect attempts since the last successful connection
let lastId = 0; // highest message id seen on the channel (sent as "since" so the server replays what we missed)
let lastRx = Date.now(); // last time ANYTHING arrived (heartbeat)
let ws, heartbeat;
function connect() {
ws = new WebSocket(`${SCHEME}://${HOST}/ws?key=${encodeURIComponent(KEY)}&cid=${encodeURIComponent(USER)}&client=raw-client&platform=node`);
lastRx = Date.now();
ws.onmessage = (e) => {
lastRx = Date.now();
let f; try { f = JSON.parse(e.data); } catch { return; } // ignore malformed frames
if (f.event === 'zabpush:connected') { // first frame: now it is safe to subscribe
attempt = 0;
console.log('connected as', f.data.user_id, 'socket', f.data.socket_id);
send({ event: 'zabpush:subscribe', channel, since: lastId }); // (private-* channels also need auth: <signature>)
} else if (f.event === 'zabpush:subscribed') {
console.log('subscribed to', f.channel);
} else if (f.event === 'zabpush:subscription_error') {
console.error('subscription refused:', f.data);
} else if (f.id || f.live) { // a push
console.log(`push #${f.id} ${f.event}:`, JSON.stringify(f.data));
if (f.id) { // id 0 = live-only: never acknowledge it
lastId = Math.max(lastId, f.id);
send({ event: 'zabpush:ack', id: f.id, status: 'delivered' }); // delivery receipt (also 'read' / 'clicked')
}
}
};
ws.onclose = () => { clearInterval(heartbeat); retry(); };
ws.onerror = () => {}; // onclose always follows
clearInterval(heartbeat);
heartbeat = setInterval(() => {
if (Date.now() - lastRx > 25000) { try { ws.close(); } catch {} return; } // silent for 25 s: the link is dead
send({ event: 'zabpush:ping' }); // answered with zabpush:pong
}, 15000);
}
function send(o) { if (ws && ws.readyState === 1) ws.send(JSON.stringify(o)); }
function retry() {
const delay = Math.min(30000, 500 * 2 ** attempt++) * (0.8 + Math.random() * 0.4); // exponential backoff + jitter
console.log(`disconnected, retrying in ${Math.round(delay)} ms`);
setTimeout(connect, delay);
}
connect();Run it
# receive (Node 22+ or any browser; no SDK)
ZP_HOST=cloud-zabpush.zabsys.com ZP_SECURE=1 ZP_KEY=APP_KEY ZP_USER=alice node raw-client.js news
# send
ZP_URL=https://cloud-zabpush.zabsys.com ZP_ID=1 ZP_SECRET=... ./publish.sh news promo '{"title":"From curl"}'
# sign a private channel (what your backend returns to a client)
ZP_SECRET=... ./publish.sh sign SOCKET_ID private-user-42What the raw client prints
connected as alice socket 88a14eba0128878b
subscribed to news
push #4127458 promo: {"title":"From curl"}Both run against a live server: the script publishes and reports 401 (exit 1) for a wrong secret, its signature matches an independent HMAC, and the raw client connected, subscribed, received the push and acknowledged it.
Health checks
| Endpoint | 200 means | Use for |
|---|---|---|
GET /healthz | The process is running. | Liveness probes, uptime monitors. |
GET /readyz | The process is running and the database answers (503 otherwise). | Readiness probes, load balancers. Live delivery continues during a database outage even when this reports 503. |
Want ZabPush for your app?
Tell us your platforms and how many users you expect, and we will set up your keys.
