SDK · Realtime
Realtime SDKs
@hubfly/realtime connects browsers and apps to a Hubfly space Realtime server and gives your backend signed publishing, authorization, webhooks and end-to-end encryption. A Go package covers the server side.
These packages talk to your Realtime server directly with an app's key and secret. They do not use a Hubfly space account token. To create servers, apps and keys from code, useclient.managed.realtime; to learn the product, start with the Realtime guide. The wire protocol is documented in the Realtime API reference.
Packages
| Import | Runs on | Use it for |
|---|---|---|
@hubfly/realtime | Browsers, React Native, Node.js 18+, Bun, Deno | Connecting, subscribing to channels, presence, client events, user sign-in and receiving direct messages. |
@hubfly/realtime/server | Node.js 18+, Bun, Deno, Cloudflare Workers | Publishing, direct messages, history, receipts, connection status, your channel auth endpoint and webhook verification. |
@hubfly/realtime/e2e | Same as above | Lower-level encryption helpers. Most apps use e2e: true and RealtimeServer.fromEnv() instead. |
github.com/hubfly/hubfly-sdk/go/realtime | Go 1.25+ | The server side in Go: publishing, sending, auth handler, webhooks and encryption. |
npm install @hubfly/realtime
go get github.com/hubfly/hubfly-sdk/go/realtimeYour backend reads four variables, which an app binding can write into a Cell project for you. Only the URL and the public key may reach the browser.
HUBFLY_REALTIME_URL=https://your-server.rt.hubfly.app
HUBFLY_REALTIME_APP_ID=your-app-id
HUBFLY_REALTIME_KEY=your-app-key
HUBFLY_REALTIME_SECRET=your-app-secret # backend onlyBrowser and app client
import { Realtime } from '@hubfly/realtime';
const realtime = new Realtime({
url: 'https://your-server.rt.hubfly.app', // https:// or wss://
key: 'your-app-key', // the public app key
});
const chat = realtime.subscribe('chat');
chat.bind('message.created', (message) => console.log(message.text));
chat.bind('pusher:subscription_succeeded', () => console.log('ready'));
realtime.on('state', ({ current }) => console.log(current));
realtime.on('error', (error) => console.error(error));
await realtime.connect();
// Later, when the page or component goes away:
// realtime.disconnect();connect()resolves with{ id, socketId }once connected; channels can be subscribed before or after.stateisinitialized,connecting,connected,reconnectingordisconnected.- The client reconnects on its own with backoff (1 s to 30 s by default). Against a Hubfly space server it resumes the session within the server's detach window: it keeps its connection id and subscriptions and receives the messages buffered meanwhile. When a session cannot be resumed it resubscribes from the last channel positions it saw, using channel history; listen for
recovery:failedon a channel to reload your state when history cannot fill the gap. transportis'auto'by default: the client uses the Hubfly space protocol and falls back to plain Pusher protocol when it is unavailable.- Handlers receive
(data, meta). If a handler returns a promise, an acknowledged message is only markedackedafter that promise finishes.
Private channels, presence and users
Public channels need no authorization. private- and presence- channels call an endpoint on your backend, which checks your own session and signs access with the app secret. authHandler takes a Fetch Request and returns aResponse, so it works in Next.js route handlers, Bun, Deno and Workers.
// app/api/realtime/auth/route.ts (Next.js)
import { RealtimeServer } from '@hubfly/realtime/server';
import { getSession } from '@/lib/auth'; // your own session lookup
export async function POST(request: Request) {
const realtime = RealtimeServer.fromEnv();
return realtime.authHandler({
getUser: async (request) => {
const session = await getSession(request);
return session ? { id: session.user.id, info: { name: session.user.name } } : null;
},
canAccess: (user, channel) => user !== null && channel === `private-user-${user.id}`,
})(request);
}const realtime = new Realtime({
url, key,
authEndpoint: '/api/realtime/auth', // private and presence channels
userAuthEndpoint: '/api/realtime/auth', // signin()
});
// Presence: who is in the room
const room = realtime.subscribe('presence-room-42');
room.bind('pusher:subscription_succeeded', (members) => console.log(members.count, 'online'));
room.bind('pusher:member_added', ({ id }) => console.log('joined', id));
// Messages addressed to the signed-in user, on every tab
realtime.on('notification', (data) => console.log(data));
await realtime.connect();
await realtime.signin();Without canAccess, any signed-in user may join any private or presence channel, so set your own rule. Never take the user id from the browser as proof of identity. Client events (channel.trigger('client-typing', …)) work on private and presence channels once you enable them in the app's settings.
Server: @hubfly/realtime/server
RealtimeServer.fromEnv() reads HUBFLY_REALTIME_URL, _APP_ID,_KEY, _SECRET and the optional _E2E_KEYS, and falls back to the Laravel-style PUSHER_APP_ID, PUSHER_APP_KEY,PUSHER_APP_SECRET, PUSHER_HOST, PUSHER_PORT andPUSHER_SCHEME. In Workers and Deno, pass the environment explicitly (RealtimeServer.fromEnv(env)). You can also constructnew RealtimeServer({ url, appId, key, secret }).
import { RealtimeServer } from '@hubfly/realtime/server';
const realtime = RealtimeServer.fromEnv();
// A channel, after your database commit. Reusing a messageId within five minutes
// prevents duplicate delivery when you retry.
await realtime.channel('orders').publish('order.created', { id: 42 }, { messageId: 'order-42-created' });
// One connection (the id the browser got from connect()), with a delivery receipt
const sent = await realtime.send(connectionId, 'export.ready', { url }, { ack: true });
// Every connection of a signed-in user
await realtime.toUser('42').send('notification', { text: 'Your export is ready' });
// Pusher-compatible calls work too
await realtime.trigger(['orders'], 'order.updated', { id: 42 });| Method | Result |
|---|---|
publish(channels, event, data, options?), channel(name).publish(…) | The message id and each channel's position. socketId excludes the sender. |
send(connectionIds, …), sendToUsers(userIds, …), toUser(id).send(…) | Per-target status: delivered, buffered (session detached, delivered on resume), queued (offline queue) or offline. |
trigger, triggerBatch | The Pusher Channels REST calls. |
history(channel, { since?, epoch?, limit? }) | Stored messages of a channel. Turn on history in the app's settings first. |
messageReceipt(messageId) | Per-target status including acked, expired and dropped, or null. |
connectionStatus, isOnline, userStatus | Whether a connection or user is online, and a user's connections. |
terminate(id, { mode? }), terminateUserConnections(userId) | Close a connection (terminate stops it reconnecting, disconnect asks it to reconnect) or all of a user's connections. |
channels, channelInfo, channelUsers | Occupied channels, occupancy and presence users. |
authorizeChannel, authenticateUser | Lower-level signing if you do not use authHandler. |
Publish and send retry once on network errors and on 502, 503 and 504 responses; their message ids make the retry safe. Requests time out after 10 seconds by default (timeoutMs).
Verify webhooks
Verify every webhook before you act on it. Pass the untouched request: verification uses the raw body, the Hubfly space signature and the timestamp (up to 300 seconds old, at most 60 seconds in the future). Delivery is at least once, so deduplicate on the delivery id.
export async function POST(request: Request) {
const { events } = await realtime.verifyWebhook(request); // throws WebhookError
const deliveryId = request.headers.get('X-Hubfly space-Delivery-Id');
// ...skip deliveryId if already handled, then process events
return new Response(null, { status: 204 });
}End-to-end encryption
With end-to-end encryption, your backend encrypts and authorized clients decrypt. Hubfly space relays and stores ciphertext and never holds the keys; it still sees channel names, users, connections, message sizes and timing.
- Generate a 32-byte master key on your own machine, with
hubfly realtime keygenoropenssl rand -base64 32, and store it on your backend only asHUBFLY_REALTIME_E2E_KEYS=k1:<base64 key>. - Create the client with
e2e: trueand anauthEndpoint; the auth endpoint hands keys to the clients it authorizes. - Publish from
RealtimeServer.fromEnv()as usual.private-encrypted-*channels, user messages and direct messages to end-to-end connection ids are encrypted automatically.fullE2E: truealso encrypts other private and presence channels.
const realtime = new Realtime({ url, key, authEndpoint: '/api/realtime/auth', e2e: true });
realtime.subscribe('private-encrypted-chat').bind('message.created', (m) => console.log(m.text));
realtime.on('e2e:error', (error) => console.error(error.reason));
await realtime.connect();To rotate, put the new key first and keep the old one until stored history has expired (k2:<new>,k1:<old>). With encryption on, the connection id returned byconnect() contains a client key: send it only to your own backend. TheRealtime guide explains the trust model and the app'srequired encryption policy.
Go server package
github.com/hubfly/hubfly-sdk/go/realtime is a separate Go module (Go 1.25+, one dependency: golang.org/x/crypto) with the same server features: publish, direct messages, Pusher trigger calls, history, receipts, connection and user status, anhttp.Handler for your auth endpoint, webhook verification and end-to-end encryption.
rt, err := realtime.FromEnv() // HUBFLY_REALTIME_* (or PUSHER_*) and optional _E2E_KEYS
if err != nil {
log.Fatal(err)
}
http.Handle("/api/realtime/auth", rt.AuthHandler(realtime.AuthHandlerOptions{
GetUser: func(r *http.Request) (*realtime.User, error) {
u := currentUser(r) // your session lookup; nil when nobody is signed in
if u == nil {
return nil, nil
}
return &realtime.User{ID: u.ID, Info: map[string]string{"name": u.Name}}, nil
},
CanAccess: func(u *realtime.User, channel string, r *http.Request) bool {
return u != nil && mayRead(u.ID, channel)
},
}))
ctx := context.Background()
_, err = rt.Publish(ctx, []string{"private-orders"}, "order.created", map[string]int{"id": 42},
&realtime.PublishOptions{MessageID: "order-42-created"})
_, err = rt.SendToUser(ctx, "u_42", "notification", map[string]string{"title": "Hi"}, nil)| Method | Purpose |
|---|---|
Publish, SendToConnection(s), SendToUser(s) | Hubfly space publish and direct messages, with MessageID, Ack and Encrypt options. |
Trigger, TriggerBatch | Pusher-compatible events. |
History, MessageReceipt | Channel history and delivery receipts. |
ConnectionStatus, IsOnline, UserStatus, TerminateConnection, DisconnectConnection, TerminateUserConnections | Connections and users. |
Channels, ChannelInfo, ChannelUsers | Channel state. |
AuthHandler, AuthorizeChannel, AuthenticateUser | Your auth endpoint. |
VerifyWebhook, VerifyWebhookBody, Decrypt | Webhooks, including encrypted payloads. |
Errors are *realtime.APIError (Status, Reason,RetryAfter), *realtime.WebhookError and *realtime.E2EError. Printing a *Client with fmt hides its secret and keys.
Pusher clients and Laravel Echo
Hubfly space Realtime speaks Pusher Channels protocol 7, so pusher-js, Laravel Echo, Laravel Broadcasting and the Pusher server SDKs connect to it after you change the host, app id, key and secret:
import Pusher from 'pusher-js';
const pusher = new Pusher('your-app-key', {
wsHost: 'your-server.rt.hubfly.app',
wssPort: 443,
forceTLS: true,
enabledTransports: ['ws', 'wss'],
cluster: 'mt1', // required by pusher-js; the explicit host is what counts
channelAuthorization: { endpoint: '/api/realtime/auth', transport: 'ajax' },
});Pusher clients get the standard channel features. Session resume, direct messages, delivery receipts and full end-to-end encryption need the Hubfly space client.
Errors
| Error | Fields |
|---|---|
RealtimeApiError (/server) | status, body, optional reason and retryAfter |
WebhookError (/server) | reason |
E2EError (/server, /e2e) | reason |
TypeError | Invalid channel, event, user or message id |
Keep the secret and master keys on your backend
HUBFLY_REALTIME_SECRETsigns requests and authorizes channels, and HUBFLY_REALTIME_E2E_KEYS decrypts your messages: never put either in frontend variables or source control.