DEV Community

octave Nkurunziza
octave Nkurunziza

Posted on Originally published at blog.hubfly.space

How to add WebRTC live streaming to your website (under 1 s)

Diagram: a broadcaster sends video over WHIP to a stream server, and your website plays it over WHEP 0.8–0.9 seconds behind live

You want live video on your own website, and you want it live: a viewer asks a question in chat and sees the answer a second later, not half a minute later. Normal HLS players run 15–25 seconds behind. Even low-latency HLS sits at a few seconds. WebRTC live streaming on your website gets that under one second, and since WHIP and WHEP (plain HTTP for WebRTC) arrived, you don't need a signalling server or an SDK.

By the end of this guide you'll have a stream server, a broadcast going out from a browser tab, and a small WebRTC player on your site that reconnects on its own and shows when you're offline. Expect the picture to reach viewers in under a second: 0.8–0.9 s on a connection with a 0.4 s round trip.

Try it on Hubfly space. A 25 Mbps stream server costs nothing to run if it's your only one; viewer bandwidth beyond 50 GB a month is billed (see What it costs).

What you need

  • A Hubfly space account. You'll use Hubfly space Managed Streams for the media server.
  • A Chromium-based browser such as Chrome or Edge (the steps below use Chrome 154).
  • A web page you control. Any static host works; the player is one HTML file.

How WebRTC live streaming on a website works

There are three parts, and each one speaks plain HTTPS to set up a WebRTC connection:

  1. The broadcaster sends video in over WHIP (WebRTC-HTTP Ingestion Protocol). This guide uses the Dashboard's own browser broadcaster.
  2. The stream server receives it, and a channel turns it into player links: WebRTC, LL-HLS, HLS, an embed page and a status file.
  3. Your page pulls video out over WHEP (WebRTC-HTTP Egress Protocol): it POSTs an SDP offer, gets an SDP answer, and the browser does the rest.

Nothing about your page needs a WebSocket, a media library or a build step.

Step 1: Create a stream server

A stream server is the media relay your viewers connect to. You need one before you have any URLs.

  1. In the Dashboard, click Create Project, name it (for example live-site), choose Managed service and click Create Project.
  2. On the project page, find Streams and click Create a stream server.
  3. Pick a speed. 25 Mbps is the free tier and is enough to get started and for about five HD viewers. You can change it later.
  4. Leave Create a push input on and name the input studio-cam.
  5. Enter an instance name such as live-site and click Create stream server.

The server is ready in a few seconds. A dialog shows the input's stream key once. Treat it like a password: anyone who has it can broadcast on your channel. Store it in your password manager, tick the box and click Done.

Your server gets a hostname like live-site-4c06.live.hubfly.app. You'll use it in every URL below.

Step 2: Add a channel set to ultra-low latency

The channel is what viewers watch. Its latency setting decides whether browsers get WebRTC.

  1. Open Channels and click Add channel.
  2. Name it Main. Under Plays, pick studio-cam.
  3. Keep Pass-through under Quality. It sends exactly what the broadcaster sends, and it costs nothing to process.
  4. Under Latency, choose Ultra-low latency. The default is Low latency (LL-HLS, 3–5 s), so don't skip this.
  5. Make sure WebRTC (WHEP) is on, keep Public access for now, and click Add channel.

The Add channel dialog with Pass-through quality and Ultra-low latency selected

Open the channel and scroll to Links and embed. Copy the WebRTC (WHEP) URL. It looks like https://live-site-4c06.live.hubfly.app/whep/sch_0179428b74b2635b. The last part, starting with sch_, is your channel ID.

The channel's Links and embed section showing the embed page, HLS, WebRTC (WHEP) and thumbnail URLs

Step 3: Go live from a browser tab

You don't need OBS to start. The Dashboard can publish your camera or screen over WHIP, and it handles the stream key for you.

  1. Open Studio and scroll to Go live from this browser.
  2. Pick the input (studio-cam), then Camera or Screen, and keep the video bitrate at 2,500 kbps.
  3. Click Go live. Your browser asks for camera (or screen) access the first time.

Within a few seconds the badge reads Publishing with the current bitrate, and the channel switches to Live on its own. The browser sends H.264 video and Opus audio. It may start at a low resolution and step up to 1280×720 once it has measured your upload speed.

Go live from this browser, publishing a clock picture to the studio-cam input

Prefer OBS? The input's page (Inputs → studio-cam) shows the OBS settings, and the OBS and encoders guide covers WHIP from OBS. Keep B-frames off, or browsers can't play the stream over WebRTC.

Step 4: The quickest player: the embed page

If you just want video on a page right now, paste the channel's embed code:

<iframe
  src="https://live-site-4c06.live.hubfly.app/embed/sch_0179428b74b2635b?autoplay=1&muted=1"
  style="width:100%;aspect-ratio:16/9;border:0"
  allow="autoplay; fullscreen; picture-in-picture"
  allowfullscreen></iframe>
Enter fullscreen mode Exit fullscreen mode

The embed page shows a LIVE badge and an Unmute button, and on an ultra-low latency channel it prefers WebRTC. Browsers only autoplay video that starts muted, which is why muted=1 is there.

Use the embed when you're happy with its look. Write your own player (next step) when you want your own controls, your own offline screen, or a viewer count in your page.

Step 5: Write your own WebRTC player with WHEP

This is the whole player. Save it as live.html, replace the two constants at the top with your hostname and channel ID, and open it from any web server.

<video id="live" autoplay muted playsinline controls style="width:100%;max-width:960px;background:#000"></video>
<p id="state">Connecting…</p>

<script type="module">
  const HOST = "https://live-site-4c06.live.hubfly.app";
  const CHANNEL = "sch_0179428b74b2635b";

  const video = document.getElementById("live");
  const label = document.getElementById("state");

  // Wait until the browser has listed its network addresses (2 s at most).
  function iceGatheringDone(pc) {
    if (pc.iceGatheringState === "complete") return Promise.resolve();
    return new Promise((resolve) => {
      const timer = setTimeout(resolve, 2000);
      pc.addEventListener("icegatheringstatechange", () => {
        if (pc.iceGatheringState === "complete") {
          clearTimeout(timer);
          resolve();
        }
      });
    });
  }

  // WHEP: post an offer, get an answer back, keep the session URL.
  async function connect() {
    const pc = new RTCPeerConnection();
    pc.addTransceiver("video", { direction: "recvonly" });
    pc.addTransceiver("audio", { direction: "recvonly" });

    const stream = new MediaStream();
    pc.ontrack = (event) => stream.addTrack(event.track);
    video.srcObject = stream;

    await pc.setLocalDescription(await pc.createOffer());
    await iceGatheringDone(pc);

    const res = await fetch(`${HOST}/whep/${CHANNEL}`, {
      method: "POST",
      headers: { "Content-Type": "application/sdp" },
      body: pc.localDescription.sdp,
    });
    if (res.status !== 201) {
      pc.close();
      throw new Error(`WHEP ${res.status}`);
    }
    const session = new URL(res.headers.get("Location"), HOST).href;
    await pc.setRemoteDescription({ type: "answer", sdp: await res.text() });
    return { pc, session };
  }

  // Hang up cleanly so the server frees the seat and the viewer count stays right.
  function hangUp({ pc, session }) {
    pc.close();
    fetch(session, { method: "DELETE", keepalive: true }).catch(() => {});
  }

  let current = null;

  async function start() {
    try {
      label.textContent = "Connecting…";
      const mine = (current = await connect());
      mine.pc.onconnectionstatechange = () => {
        if (mine.pc.connectionState === "connected") showStatus();
        if (mine.pc.connectionState === "failed") {
          hangUp(mine);
          label.textContent = "Connection lost. Reconnecting…";
          setTimeout(start, 2000);
        }
      };
    } catch (err) {
      label.textContent = `Can't connect (${err.message}). Retrying in 5 seconds…`;
      setTimeout(start, 5000);
    }
  }

  // The status file says whether anyone is broadcasting and how many people watch.
  async function showStatus() {
    try {
      const res = await fetch(`${HOST}/status/${CHANNEL}.json`, { cache: "no-store" });
      const { live, viewers } = await res.json();
      if (current?.pc.connectionState === "connected") {
        label.textContent = live ? `Live · ${viewers} watching` : "Offline. Back soon.";
      }
    } catch {}
  }

  addEventListener("pagehide", () => current && hangUp(current));
  start();
  setInterval(showStatus, 10000);
  showStatus();
</script>
Enter fullscreen mode Exit fullscreen mode

What each part does, and why it's there:

  • recvonly transceivers tell the server this page only watches. Without them the offer has no media sections and the server has nothing to answer.
  • iceGatheringDone waits until the browser has listed its network addresses, so they all go in the one POST. The server's answer already contains its own addresses, so you don't need a second round trip.
  • The Location header is the address of this viewer's session. The server sends a relative path such as /whep/sch_…/8c69bb2f…, so the code resolves it against HOST. It's readable from other origins, so this works from any domain.
  • DELETE on pagehide ends the session when the tab closes. keepalive: true lets the request finish while the page unloads. Skip it and the viewer count stays too high for a while.
  • Reconnect on failed only. A disconnected state often heals by itself. When the server really drops a session, Chrome reports disconnected after about 7 seconds and failed after about 17. The player then reconnects 2 seconds later.
  • The status file (/status/<channel>.json) returns {"live":true,"state":"live","viewers":1,"started_at":"…"}. It's public, it works from any origin, and it's how the label knows you're offline.

You don't need to reconnect when the broadcaster stops

When the broadcast stops, the WebRTC connection stays up: after the channel's failover delay (5 seconds by default) viewers see the server's "This stream is offline" slate, and the status file switches to "live": false. When you go live again, the same connection picks the video back up. Nobody has to refresh.

A WHEP request made while you're offline also succeeds (201) and shows the slate. So you can load the player before the show starts and leave it alone.

Check that it really is under a second

To measure delay yourself, broadcast something that shows a clock with milliseconds (a browser tab with a canvas clock works), and put a clock on the viewer page next to the video. Take a screenshot and subtract.

Two players side by side: WebRTC about 1 second behind the viewer's clock, LL-HLS more than 10 seconds behind

On a connection with about 0.4 s round trip to the media server, the numbers look like this:

Player Delay behind live
WebRTC (WHEP) 0.80–0.90 s across five samples
LL-HLS (hls.js 1.5.20, low-latency mode) about 7 s at start, then 10–20 s after buffer stalls
Time to first picture, WebRTC about 4.7 s from page load

The WebRTC delay held steady for the whole session. LL-HLS didn't: on a slow link each stall pushes it further behind live. On a faster connection it lands closer to its rated 3–5 seconds.

What can go wrong

WebRTC viewers get a lower quality or LL-HLS instead. If you broadcast from an encoder such as OBS or ffmpeg, it's probably sending B-frames, which browsers can't play over WebRTC. The encoder guide explains how the server handles them and how to turn them off. The browser broadcaster in Step 3 doesn't have this problem.

TypeError: Failed to fetch on the WHEP POST, but the status file loads. The channel or server has Allowed websites set, and your page's origin isn't on the list. The request is refused before your code can read a status code, so the browser only says "Failed to fetch". Add your page's exact origin, such as https://www.your-domain.com, or clear the field to allow every site.

WHEP 401. The channel's access is set to Signed tokens, so every viewer needs a playback token from your backend. The playback security guide shows how to sign one and pass it on the WHEP request. Or switch the channel back to Public.

It works at home but stays on "Connecting…" on a locked-down office network. The media server offers WebRTC on port 8189 (UDP, with TCP as the fallback). A firewall that blocks that port blocks WebRTC. Give those viewers a fallback: after a few failed attempts, play the channel's HLS URL with hls.js instead.

New viewers suddenly get a few seconds of delay. The server's WebRTC viewers setting (under Settings) caps sub-second viewers at 200 by default, up to 2,000; the docs say viewers beyond it watch over LL-HLS. Also check the server's speed: once viewers use it all up, delivery slows down for everyone.

Video autoplays muted, or doesn't start at all. Browsers block autoplay with sound. Keep autoplay muted playsinline on the <video> element and show an Unmute button. playsinline stops iPhones from jumping to full screen.

The stream key leaked. Open Inputs, find Keys and click Rotate; the encoder guide says encoders using the old key are disconnected. Never put a stream key in front-end code. The browser broadcast in Step 3 keeps it out of your page.

What it costs

Hubfly space Managed Streams bills three things: the server's speed while it runs, bandwidth sent to viewers, and processing only when it re-encodes. Pass-through channels, like the one above, use no processing. Every account gets the first 25 Mbps of speed, 50 GB of bandwidth and 20 Mbps-hours of processing free each month.

A worked example: a one-hour show every week, 50 people watching a 2.5 Mbps stream.

  • Bandwidth: 2.5 Mbps × 3,600 s ÷ 8 = 1.125 GB per viewer-hour. 50 viewers × 4 shows = 200 viewer-hours = 225 GB. After the free 50 GB, 175 GB × $0.004 = $0.70.
  • Speed: 50 viewers × 2.5 Mbps = 125 Mbps, so raise the server to 130 Mbps for the show. The 105 Mbps above the free 25 cost 105 × $0.000041 = $0.0043 an hour, about $0.02 for four one-hour shows. Drop it back to 25 Mbps afterwards (free), or stop the server.
  • Processing: pass-through, $0.

That's about $0.72 a month. If you leave the server at 130 Mbps all month instead, speed alone is about $3.14. Above 250 Mbps (roughly 100 viewers of a 2.5 Mbps stream), Hubfly space asks for a deposit first.

FAQ

How do I embed a low-latency live stream on my website?
Create a channel with Ultra-low latency and paste its embed <iframe> into your page (Step 4). For your own look, use the WHEP player in Step 5.

What are WHIP and WHEP?
Two small HTTP protocols for WebRTC. WHIP sends video in, WHEP pulls it out. Each is one POST with an SDP offer, one SDP answer back, and a session URL you DELETE when you're done. WHIP is an IETF standard (RFC 9725); WHEP is still an Internet-Draft, but servers and players already use it.

Can I broadcast from OBS instead of a browser?
Yes. OBS Studio added WHIP output in version 30, and the Hubfly space encoder guide lists the settings. Turn B-frames off for WebRTC viewers.

How much latency does WebRTC streaming have?
Under a second in practice. In the table above it was 0.8–0.9 s from broadcaster to viewer with a 0.4 s network round trip, against 3–5 s for LL-HLS at best and 15–25 s for standard HLS.

How many viewers can watch over WebRTC?
200 at once per server by default, and you can raise the limit to 2,000. Above it, the docs say extra viewers get LL-HLS. For bigger audiences, check the server's speed too.

Why is my WebRTC stream black when HLS works?
Usually B-frames from an encoder, or a network that blocks port 8189. Check the input's health panel and try another network.

Do I need my own TURN server?
Not to get started: the media server has a public address that browsers connect to directly. For viewers on networks that block port 8189, an HLS fallback is simpler than running TURN.

Is WebRTC or LL-HLS better for my site?
WebRTC when viewers interact with the stream: auctions, Q&A, classes, sports betting, game shows. LL-HLS or HLS when nobody notices a few seconds and you want the widest device support and CDN-friendly caching.

Go further on Hubfly space

  • Restream the same broadcast to YouTube and Twitch while your site plays the sub-second version: Restreaming.
  • Make the stream members-only with short-lived playback tokens signed by your backend: Playback security.
  • Record every show to Hubfly space Storage and turn highlights into clips: Recording and clips.

Related reading: Live video costs in 2026: Mux, Cloudflare, IVS, Hubfly space compares what an hour of live video costs on each platform.

Try it on Hubfly space: create a 25 Mbps stream server and have sub-second video on your site in about ten minutes.


By Octave · drafted with AI, tested on Hubfly · Last updated 11 November 2026

Top comments (0)