Hubfly spaceDocs
Console

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

ImportRuns onUse it for
@hubfly/streamsAnywhereShared types and the URL helpers playbackURLs and withToken.
@hubfly/streams/playerBrowsersThe <hubfly-player> element and createPlayer(): WebRTC, then LL-HLS, then HLS. About 4.8 KB minified and gzipped.
@hubfly/streams/publishBrowserspublish(): send a camera, screen or canvas to a WHIP input. About 1.8 KB gzipped.
@hubfly/streams/serverNode.js 18+, Bun, Deno, Cloudflare WorkersSigning and verifying playback tokens, and signing and verifying webhooks. Uses only Web Crypto.
github.com/hubfly/hubfly-sdk/go/streamsGo 1.25+Playback tokens and webhooks in Go, standard library only.
Install
npm install @hubfly/streams hls.js
go get github.com/hubfly/hubfly-sdk/go/streams

hls.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.

dotenv
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 only

Playback URLs: @hubfly/streams

TypeScript
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).

html
<script type="module">
  import '@hubfly/streams/player';
</script>

<hubfly-player host="acme-tv.live.hubfly.app" channel="sch_main0001" autoplay muted></hubfly-player>
TypeScript
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();
AttributeOptionDefaultMeaning
hosthostServer host or verified custom playback domain.
channelchannelChannel id.
hls, whep, statusurlsExplicit playback URLs instead of host and channel.
tokentokenPlayback token for token channels. Changing the attribute reconnects with the new token.
latencylatencywebrtcThe first transport to try: webrtc, ll-hls or hls.
autoplayautoplayoffStart as soon as media arrives. Browsers allow this only when muted.
mutedmutedoffStart muted.
posterposterImage shown before the first frame.
controls="false"controlsonNative media controls.
audio-onlyaudioOnlyoffPlay the audio outputs (Opus, else MP3) in an <audio> element, for radio.
hlsConfigExtra hls.js configuration.
loadHlsimport('hls.js')Load hls.js from elsewhere, such as a CDN.
latencyTriesTypical delay
webrtc (default)WHEP, then LL-HLS, then HLSUnder 1 s
ll-hlsLL-HLS, then HLS3–5 s
hlsHLS15–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.js at that moment; without it the player shows error with reason="unsupported". Pass loadHls: () => 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 as element.player. defineHubflyPlayer(name?) registers the element under another tag name.
  • The player renders a div.hfp with the media element, a div.hfp-status label and a button.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 polite aria-live region, and the only motion is a 200 ms fade that prefers-reduced-motion turns 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"].

statereasonWhat happens
loadingConnecting.
liveMedia is playing.
reconnectingThe 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.
offlinenot_liveNothing is live; the server's offline slate plays, and the player switches to live when the channel goes on air.
offlinestopped, pausedThe server is stopped or paused by billing. The player checks the channel status every 5 seconds and connects when it changes.
errorunauthorized, 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.

TypeScript
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:

TypeScript
// 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 });
}
html
<hubfly-player host="acme-tv.live.hubfly.app" channel="sch_main0001" token="eyJhbGciOi…"></hubfly-player>
  • signPlaybackToken(key, claims, { ttlSeconds, now }) refuses a token without ch and always sets exp: from claims.exp, or now + ttlSeconds (1 hour by default, at most 31 days). ch: '*' covers every channel of the server; ip binds the token to an IPv4 address or CIDR; sub labels 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 throws PlaybackTokenError, 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:

TypeScript
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.

Go
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
	}))
NamePurpose
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 }).

AreaMethods
ServergetServer, updateSettings, getLive, getStats, getUsage, listEvents, control, createStudioToken, estimatePrice
Inputs, channels, mixers, destinations, playlists, scheduleslist…, get…, create…, update…, delete… for each, plus revealInputKeys, rotateInputKey, getChannelPlayback, createPlaybackToken, previewSchedule, listScheduleRuns
RecordingslistRecordings, createClip, deleteRecording
Playback keyslistPlaybackKeys, createPlaybackKey, rotatePlaybackKey, deletePlaybackKey
Webhookslist, create, update and delete, listWebhookDeliveries, testWebhook
Graphics, storage links, domains, bindingslist, 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

ErrorFields
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 statuscodeMeaning
401unauthorizedBad key, unknown input, or WHIP not enabled on the input
403forbiddenInput disabled, server stopped or paused by billing, or address not allowed
409conflictAnother encoder is publishing with that key
503unavailableThe server is not accepting publishers
not_found, rate_limited, bad_request, network, ice, failedThe other codes

Keep keys and secrets on your backend

The browser needs only the server host, the channel id and, for token channels, a short-lived token. Never put a playback key secret, a webhook secret or a stream key in frontend code, frontend variables or source control. Sign tokens on your server, and hand a stream key only to the person who is going live.
Something unclear or out of date? Emailsupport@hubfly.spaceBack to top