Embedding a live sports stream with hls.js
Play a direct .m3u8 sports feed in the browser with hls.js: player setup, buffer configuration tuned for live edge playback, and error recovery that survives a mid-match source drop.
Why hls.js, and when you do not need it
Safari and iOS play HLS natively through the video element, so on those platforms you can assign the .m3u8 URL to video.src and stop there. Chrome, Firefox and Edge cannot, which is what hls.js is for: it parses the playlist in JavaScript and feeds segments to Media Source Extensions.
The practical consequence is that you need both paths. Checking Hls.isSupported() first and falling back to canPlayType covers every current browser without sniffing user agents.
const video = document.getElementById('player');
const src = await resolveStreamUrl(matchId); // see the resolver section
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(src);
hls.attachMedia(video);
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// Safari and iOS: native HLS
video.src = src;
} Buffer settings that matter for live
The hls.js defaults are tuned for video on demand, where buffering ahead generously costs nothing. For live sport the trade is different: every second you buffer is a second further behind the action, and viewers comparing against a television notice.
Three settings carry most of the effect. liveSyncDurationCount sets how many segments back from the live edge playback sits — lower is closer but less tolerant of jitter. maxBufferLength caps how far ahead the player fetches. backBufferLength keeps memory from growing over a two-hour match, which matters on low-end mobile hardware.
The values below sit close to the edge without being brittle. If your audience skews mobile or your telemetry shows frequent rebuffering, raise liveSyncDurationCount to 4 before touching anything else.
const hls = new Hls({
lowLatencyMode: true,
liveSyncDurationCount: 3, // segments behind the live edge
liveMaxLatencyDurationCount: 10,
maxBufferLength: 20, // seconds fetched ahead
backBufferLength: 30, // seconds retained behind playhead
manifestLoadingTimeOut: 8000,
manifestLoadingMaxRetry: 3,
}); Recovering from errors instead of failing
A live sports stream will throw errors during a normal match. A segment arrives late, a token expires at a boundary, a CDN node is swapped mid-session. None of these should end playback, and hls.js distinguishes fatal from non-fatal errors precisely so you can act on that.
Non-fatal errors are already handled internally — logging them is useful, intervening is not. For fatal errors there are three cases. Network errors usually clear with startLoad(). Media errors usually clear with recoverMediaError(). Anything else means this source is finished and you should move to the next one in the array the resolver returned.
let sourceIndex = 0;
hls.on(Hls.Events.ERROR, (_event, data) => {
if (!data.fatal) return; // hls.js handles these itself
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
hls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
hls.recoverMediaError();
break;
default:
// This source is gone. Fail over rather than giving up.
sourceIndex += 1;
if (sourceIndex < sources.length) {
hls.loadSource(sources[sourceIndex].url);
} else {
hls.destroy();
showOfflineMessage();
}
}
}); Resolving the URL at the right moment
Source URLs carry expiring tokens. Resolving at page load and caching the result for the length of a match is the single most common integration bug, and it surfaces as playback that works in testing and fails for real users who opened the tab early.
Resolve when the user presses play, not when the page renders. Keep the full sources array rather than only the first URL, because that array is what makes the failover above possible without a second round trip.
// Issued with your API key at provisioning.
const API_BASE = process.env.XPORTAPI_BASE;
async function resolveSources(sportId, matchId) {
const res = await fetch(
`${API_BASE}/v1/stream/${sportId}/${matchId}`,
{ headers: { 'x-api-key': API_KEY } }
);
if (!res.ok) {
throw new Error(`stream resolve failed: ${res.status}`);
}
const { data } = await res.json();
return data.sources; // keep all of them, not just [0]
}