Connect clients
Clients connect over WebSockets to your server's host with the app's public key. They never need the secret: private and presence channels are approved by an auth endpoint on your backend, which Hubfly space never calls.
Choose a client
| Client | Use it when |
|---|---|
@hubfly/realtime | New apps, or when you want session resume, catch-up from channel history, direct messages to a connection, acknowledgements or full end-to-end encryption. Falls back to the Pusher protocol when the Hubfly space path is unavailable. |
| pusher-js (and libraries built on it, such as Laravel Echo) | Existing Pusher apps. Public, private, presence and encrypted channels, client events, user sign-in and user messages work unchanged. |
| Other Pusher Channels clients | They speak the same protocol 7; set the host, port 443 and TLS. Hubfly space tests pusher-js and Laravel Echo. |
Connect with @hubfly/realtime
npm install @hubfly/realtimeimport { Realtime } from "@hubfly/realtime";
const realtime = new Realtime({
url: "https://chat-1a2b.rt.hubfly.app",
key: "your-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));
await realtime.connect();
// When leaving the page or unmounting a component:
// realtime.disconnect();Public channels need no authorization: anyone with the app key can subscribe. connect() resolves with the connection id; the client reconnects on its own. The package works in browsers, Bun, Deno and Node.js (pass a WebSocket implementation such as ws where there is no global one). See the SDK page for every option.
Connect with pusher-js
import Pusher from "pusher-js";
const pusher = new Pusher("your-app-key", {
wsHost: "chat-1a2b.rt.hubfly.app",
wssPort: 443,
forceTLS: true,
enabledTransports: ["ws", "wss"],
cluster: "mt1", // required by pusher-js; Hubfly space uses the host above
channelAuthorization: { endpoint: "/api/realtime/auth", transport: "ajax" },
});
pusher.subscribe("orders").bind("order.updated", (data) => console.log(data));Set enabledTransports to WebSockets only: Hubfly space has no HTTP fallback transports. For encrypted channels use the pusher-js/with-encryption build.
Private channels and the auth endpoint
When a client subscribes to a private-, presence- or private-encrypted- channel, it asks your auth endpoint, which checks your app's own session and signs access with the app secret. Decide access from the authenticated session, never from a user id the browser sends.
import { RealtimeServer } from "@hubfly/realtime/server";
import { getSession } from "@/lib/auth"; // your 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);
}The handler takes a Fetch Request and returns a Response, so it works in Next.js, Bun, Deno and Workers. It accepts the form-encoded requests that pusher-js and the Hubfly space client send. Without canAccess, any signed-in user may join any private or presence channel. Point the client at it:
const realtime = new Realtime({
url: "https://chat-1a2b.rt.hubfly.app",
key: "your-app-key",
authEndpoint: "/api/realtime/auth",
});
realtime.subscribe("private-user-42").bind("notification", (data) => console.log(data));Existing Pusher backends keep working: an endpoint built with a Pusher server library's authorizeChannel (or Laravel's broadcast auth route) signs the same way. A refused subscription answers pusher:subscription_error on that channel with a type and status (AuthError 401, Forbidden 403, LimitReached 429); the connection stays open.
Presence and client events
const room = realtime.subscribe("presence-room-42");
room.bind("pusher:subscription_succeeded", (members) => {
console.log(`${members.count} people online`);
});
room.bind("pusher:member_added", ({ id, info }) => console.log("Joined:", id, info));
room.bind("pusher:member_removed", ({ id }) => console.log("Left:", id));
// With client events enabled in the app settings:
room.trigger("client-typing", { typing: true });- Presence always needs a signed-in user from your auth endpoint. Keep
infounder 1 KiB. A channel holds up to 100 members by default (up to 1,000 in the app settings). - Client events must start with
client-, work on private and presence channels the sender has joined, are not echoed to the sender, and are limited per connection (10 per second by default). Turn on Client events in the app settings first.
Sign in users
Signing in ties a connection to a user, so your server can message every tab and device of that user. Set userAuthEndpoint (it can be the same auth endpoint) and sign in after connecting:
const realtime = new Realtime({
url: "https://chat-1a2b.rt.hubfly.app",
key: "your-app-key",
authEndpoint: "/api/realtime/auth",
userAuthEndpoint: "/api/realtime/auth",
});
realtime.on("notification", (data) => console.log(data));
await realtime.connect();
await realtime.signin();With pusher-js, configure userAuthentication and call pusher.signin(); user messages arrive through pusher.user.bind(event, handler). Your server then sends with toUser(id).send() or a Pusher library's sendToUser.
Browser environment variables
Browsers need only the URL and the public key. A connected project with a client prefix writes these for you:
| Framework | Variables |
|---|---|
| Next.js | NEXT_PUBLIC_HUBFLY_REALTIME_URL, NEXT_PUBLIC_HUBFLY_REALTIME_KEY |
| Vite | VITE_HUBFLY_REALTIME_URL, VITE_HUBFLY_REALTIME_KEY |
| SvelteKit, Astro | PUBLIC_HUBFLY_REALTIME_URL, PUBLIC_HUBFLY_REALTIME_KEY |
Keep secrets on the server
HUBFLY_REALTIME_SECRET or HUBFLY_REALTIME_E2E_KEYS to the browser. The secret lets anyone publish to and authorize any channel of the app.Reconnects and close codes
Both clients reconnect automatically. The Hubfly space client resumes its session when it comes back within the app's session time (60 seconds by default): it keeps its connection id and subscriptions and replays messages it missed. If it cannot resume, it gets a new id, resubscribes and catches up from channel history; listen for recovery:failed on a channel to reload your app state when history cannot fill the gap.
| Close code | Client action | Meaning |
|---|---|---|
| 4001 | Stops | Unknown key or app, app deleted, or key revoked |
| 4003 | Stops | App disabled |
| 4009 | Stops | Origin not allowed, user authentication failed or timed out, or connection terminated by you |
| 4100 | Backs off and retries | Over capacity (server or app connection limit), a slow client, or the bandwidth budget used up |
| 4200, 4201 | Reconnects at once | Planned restart or disconnect; ping not answered |
The full wire contract is in the Realtime protocol reference.