SDK · Streams
Streams SDKs
@hubfly/streams plays your live channels in the browser, publishes a camera or screen over WHIP, and gives your backend playback tokens and webhook verification. A Go package covers the server side.
These packages talk to your stream server directly: viewers need only the server host and a channel id, and your backend uses a playback key or a webhook secret. They do not use a Hubfly space account token. To create servers, inputs and channels from code, use client.managed.streams or the hubfly stream CLI; to learn the product, start with the Managed Streams guide.
Packages
| Import | Runs on | Use it for |
|---|---|---|
@hubfly/streams | Anywhere | Shared types and the URL helpers playbackURLs and withToken. |
@hubfly/streams/player | Browsers | The <hubfly-player> element and createPlayer(): WebRTC, then LL-HLS, then HLS. About 4.8 KB minified and gzipped. |
@hubfly/streams/publish | Browsers | publish(): send a camera, screen or canvas to a WHIP input. About 1.8 KB gzipped. |
@hubfly/streams/server | Node.js 18+, Bun, Deno, Cloudflare Workers | Signing and verifying playback tokens, and signing and verifying webhooks. Uses only Web Crypto. |
github.com/hubfly/hubfly-sdk/go/streams | Go 1.25+ | Playback tokens and webhooks in Go, standard library only. |
npm install @hubfly/streams hls.js
go get github.com/hubfly/hubfly-sdk/go/streamshls.js is an optional peer dependency. The player imports it only when it needs LL-HLS in a browser without native HLS (Chrome, Firefox, Edge), so install it alongside the player unless you load it from elsewhere.
A stream binding writes these variables into a Cell project. Only the URL may reach the browser.
HUBFLY_STREAM_URL=https://acme-tv.live.hubfly.app
HUBFLY_STREAM_PLAYBACK_KEY_ID=spk_key00001
HUBFLY_STREAM_PLAYBACK_KEY_SECRET=your-playback-key-secret # backend onlyPlayback URLs: @hubfly/streams
import { playbackURLs, withToken } from '@hubfly/streams';
const urls = playbackURLs('acme-tv.live.hubfly.app', 'sch_main0001');
// urls.hls https://acme-tv.live.hubfly.app/hls/sch_main0001/index.m3u8
// urls.whep https://acme-tv.live.hubfly.app/whep/sch_main0001
// urls.embed https://acme-tv.live.hubfly.app/embed/sch_main0001
// urls.status https://acme-tv.live.hubfly.app/status/sch_main0001.json
// urls.thumb https://acme-tv.live.hubfly.app/thumb/sch_main0001.jpg
// urls.audio [{ format: 'mp3', url: … }, { format: 'aac', … }, { format: 'opus', … }]
const signed = withToken(urls.hls, token); // adds ?token=host is the server host, a verified custom playback domain, or a full origin. Outputs that are turned off on the channel answer 404. withToken works for the HLS, audio, thumbnail, status and embed URLs. To embed without any JavaScript, use an iframe of the embed page, https://<host>/embed/<channel>.
Player: @hubfly/streams/player
Importing the entry registers the <hubfly-player> element in browsers (and does nothing during server rendering).
<script type="module">
import '@hubfly/streams/player';
</script>
<hubfly-player host="acme-tv.live.hubfly.app" channel="sch_main0001" autoplay muted></hubfly-player>import { createPlayer } from '@hubfly/streams/player';
const el = document.querySelector<HTMLElement>('#player')!;
const player = createPlayer(el, {
host: 'acme-tv.live.hubfly.app',
channel: 'sch_main0001',
autoplay: true,
muted: true,
});
el.addEventListener('statechange', (event) => {
const { state, reason, transport, message } = (event as CustomEvent).detail;
console.log(state, transport, message); // "live", "webrtc", "Live"
});
// Later, when the page or component goes away:
// player.destroy();| Attribute | Option | Default | Meaning |
|---|---|---|---|
host | host | Server host or verified custom playback domain. | |
channel | channel | Channel id. | |
hls, whep, status | urls | Explicit playback URLs instead of host and channel. | |
token | token | Playback token for token channels. Changing the attribute reconnects with the new token. | |
latency | latency | webrtc | The first transport to try: webrtc, ll-hls or hls. |
autoplay | autoplay | off | Start as soon as media arrives. Browsers allow this only when muted. |
muted | muted | off | Start muted. |
poster | poster | Image shown before the first frame. | |
controls="false" | controls | on | Native media controls. |
audio-only | audioOnly | off | Play the audio outputs (Opus, else MP3) in an <audio> element, for radio. |
hlsConfig | Extra hls.js configuration. | ||
loadHls | import('hls.js') | Load hls.js from elsewhere, such as a CDN. |
latency | Tries | Typical delay |
|---|---|---|
webrtc (default) | WHEP, then LL-HLS, then HLS | Under 1 s |
ll-hls | LL-HLS, then HLS | 3–5 s |
hls | HLS | 15–25 s |
- WebRTC falls back to LL-HLS when the server refuses it (the source has B-frames and the channel does not transcode, the channel's WebRTC session cap is reached, or WebRTC is off on the channel) or when it cannot connect within 10 seconds. A refused token (401 or 403) does not fall back.
- LL-HLS plays natively in Safari and iOS. Elsewhere the player imports
hls.jsat that moment; without it the player showserrorwithreason="unsupported". PassloadHls: () => import('https://esm.sh/hls.js@1')to load it from a CDN. After two LL-HLS failures in a row the player uses plain HLS. createPlayer(el, options)returns{ media, state, reason, transport, play(), reload(), destroy() }, and<hubfly-player>exposes the same object aselement.player.defineHubflyPlayer(name?)registers the element under another tag name.- The player renders a
div.hfpwith the media element, adiv.hfp-statuslabel and abutton.hfp-play, in a 16:9 box; size the host element to change it. Every state has text, the buttons have a visible focus ring, the status is a politearia-liveregion, and the only motion is a 200 ms fade thatprefers-reduced-motionturns off.
Player states and events
The element carries state and reason attributes and dispatches statechange with detail: { state, reason, transport, message }. Style it with selectors such as hubfly-player[state="offline"].
state | reason | What happens |
|---|---|---|
loading | Connecting. | |
live | Media is playing. | |
reconnecting | The connection dropped. The player retries after 1, 2, 4, 8, 16 and then every 30 seconds, and at once when the browser comes back online. | |
offline | not_live | Nothing is live; the server's offline slate plays, and the player switches to live when the channel goes on air. |
offline | stopped, paused | The server is stopped or paused by billing. The player checks the channel status every 5 seconds and connects when it changes. |
error | unauthorized, forbidden, unsupported, … | Playback is refused or impossible. The player shows why and a Try again button; for a refused token, mint a new one and set the token attribute. |
Publish: @hubfly/streams/publish
publish() sends a MediaStream to an input over WHIP. Turn on the whip protocol on the input first, and give its stream key only to the people allowed to go live: the key lets anyone publish to the input. Video prefers H.264, then VP8; audio is Opus.
import { publish } from '@hubfly/streams/publish';
const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 1280, height: 720 }, audio: true });
try {
const broadcast = await publish({
url: 'https://acme-tv.live.hubfly.app/whip/sin_cam1abcd',
token: streamKey, // handed only to the signed-in broadcaster
stream,
maxBitrateKbps: 4500,
});
broadcast.addEventListener('statechange', () => console.log(broadcast.state)); // connecting → live
// later
await broadcast.stop();
} catch (error) {
// error.code: unauthorized, forbidden, conflict, unavailable, network, ice, …
console.error(error.code, error.message);
}state is connecting, live, reconnecting, failed or stopped, and the handle also exposes its peerConnection. For OBS, ffmpeg and hardware encoders, use RTMPS or SRT instead (see OBS and encoders).
Server: @hubfly/streams/server
Channels with token access play only with a token signed by one of the server's playback keys. Check your own session first, then mint a short-lived token per viewer:
// app/api/stream-token/route.ts (Next.js)
import { signPlaybackToken } from '@hubfly/streams/server';
import { getSession } from '@/lib/auth'; // your own session lookup
export async function GET(request: Request) {
const session = await getSession(request);
if (!session) return new Response('sign in first', { status: 401 });
const token = await signPlaybackToken(
{ id: process.env.HUBFLY_STREAM_PLAYBACK_KEY_ID!, secret: process.env.HUBFLY_STREAM_PLAYBACK_KEY_SECRET! },
{ ch: 'sch_main0001', sub: session.user.id },
{ ttlSeconds: 3600 },
);
return Response.json({ token });
}<hubfly-player host="acme-tv.live.hubfly.app" channel="sch_main0001" token="eyJhbGciOi…"></hubfly-player>signPlaybackToken(key, claims, { ttlSeconds, now })refuses a token withoutchand always setsexp: fromclaims.exp, ornow + ttlSeconds(1 hour by default, at most 31 days).ch: '*'covers every channel of the server;ipbinds the token to an IPv4 address or CIDR;sublabels the viewer in statistics. Times are Unix seconds.- A session that has started keeps playing until the token's
exp, so keep tokens short and mint a new one for each page view. verifyPlaybackToken(token, keys, { channel, clientIp?, now? })applies the server's rules if your backend wants to check a token itself. Any refusal throwsPlaybackTokenError, without saying which check failed.
The stream server signs every webhook delivery with the webhook's whsec_ secret, shown once when you create the webhook. Verify the raw body before you parse it:
import { verifyWebhook } from '@hubfly/streams/server';
export async function POST(request: Request) {
const raw = await request.text();
const ok = await verifyWebhook(process.env.HUBFLY_STREAM_WEBHOOK_SECRET!, raw, request.headers.get('Hubfly space-Signature'));
if (!ok) return new Response('invalid signature', { status: 400 });
const event = JSON.parse(raw); // { id: "evt_…", type: "channel.live", at, tenant, data }
if (event.type === 'channel.live') console.log('Live:', event.data.channel);
return new Response(null, { status: 204 });
}Signatures more than 300 seconds old or ahead are refused (toleranceSeconds changes that). Answer with a 2xx within 10 seconds; failed deliveries are retried for about 8 hours. Delivery is at least once, so ignore repeats by Hubfly space-Event-Id. signWebhook(secret, body, timestamp?) signs test deliveries. The server entry uses only Web Crypto, so it runs in Node.js 18+, Bun, Deno and Cloudflare Workers. See playback security and webhooks.
Go streams package
github.com/hubfly/hubfly-sdk/go/streams is a separate Go module (Go 1.25+, standard library only) with the same server features: playback tokens and webhook verification.
key := streams.PlaybackKey{
ID: os.Getenv("HUBFLY_STREAM_PLAYBACK_KEY_ID"),
Secret: os.Getenv("HUBFLY_STREAM_PLAYBACK_KEY_SECRET"),
}
http.HandleFunc("/api/stream-token", func(w http.ResponseWriter, r *http.Request) {
user := currentUser(r) // your own session check
if user == nil {
http.Error(w, "sign in first", http.StatusUnauthorized)
return
}
token, err := streams.SignPlaybackToken(key, streams.PlaybackClaims{
Channel: "sch_main0001",
Expires: time.Now().Add(time.Hour).Unix(),
Subject: user.ID,
})
if err != nil {
http.Error(w, "could not sign", http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]string{"token": token})
})
http.Handle("/hubfly/stream", streams.WebhookHandler(os.Getenv("HUBFLY_STREAM_WEBHOOK_SECRET"), streams.WebhookOptions{},
func(r *http.Request, event streams.WebhookEvent) error {
if event.Type == "channel.live" {
log.Printf("live: %s", event.Data)
}
return nil // an error answers 500 and the delivery is retried
}))| Name | Purpose |
|---|---|
SignPlaybackToken(key, claims) | Signs PlaybackClaims (Channel, Expires, IssuedAt, NotBefore, Subject, IP). A zero Expires means one hour (DefaultTokenTTL); tokens live at most MaxTokenLifetime (31 days). |
VerifyPlaybackToken(token, keys, VerifyOptions{Channel, ClientIP}) | Applies the server's rules. Every refusal is ErrPlaybackTokenRefused. |
WebhookHandler(secret, opts, fn) | An http.Handler that reads at most 1 MB, verifies Hubfly space-Signature over the raw body (within 5 minutes) and answers 204, 400 or 500. |
VerifyWebhook(secret, body, header, opts), SignWebhook(secret, body, t) | Verify yourself (nil or a *WebhookError), or sign test deliveries. The header name is streams.SignatureHeader. |
Manage servers from code
The packages above never create or change anything. To manage stream servers with your Hubfly space token, use client.managed.streams in the Hubfly space SDK(Go: ManagedStreamsService, with the same names capitalised). Every method takes the managed project id and the instance id. Create, change the speed of, stop, start and delete servers with the shared client.managed.instances methods (service: "stream", stream: { speedMbps }).
| Area | Methods |
|---|---|
| Server | getServer, updateSettings, getLive, getStats, getUsage, listEvents, control, createStudioToken, estimatePrice |
| Inputs, channels, mixers, destinations, playlists, schedules | list…, get…, create…, update…, delete… for each, plus revealInputKeys, rotateInputKey, getChannelPlayback, createPlaybackToken, previewSchedule, listScheduleRuns |
| Recordings | listRecordings, createClip, deleteRecording |
| Playback keys | listPlaybackKeys, createPlaybackKey, rotatePlaybackKey, deletePlaybackKey |
| Webhooks | list, create, update and delete, listWebhookDeliveries, testWebhook |
| Graphics, storage links, domains, bindings | list, upload or create, update, delete; listStorageAssets; domain verify |
Methods that create or rotate inputs, playback keys and webhooks, and revealInputKeys, return a secret: keep those responses on your server and out of logs. The Dashboard routes are documented in the Streams API reference.
Errors
| Error | Fields |
|---|---|
MediaError (/publish, re-exported by /player) | code, status (0 for network and ICE failures), reason (the server's short reason, such as input_disabled), optional retryAfter |
PlaybackTokenError (/server) | Message Playback token refused |
TypeError, RangeError (/server) | A missing key id, secret or ch claim, or a ttlSeconds beyond 31 days |
| WHIP status | code | Meaning |
|---|---|---|
| 401 | unauthorized | Bad key, unknown input, or WHIP not enabled on the input |
| 403 | forbidden | Input disabled, server stopped or paused by billing, or address not allowed |
| 409 | conflict | Another encoder is publishing with that key |
| 503 | unavailable | The server is not accepting publishers |
not_found, rate_limited, bad_request, network, ice, failed | The other codes |
Keep keys and secrets on your backend