Getting Started with hls.js: Tutorial & Examples
Learn how to use hls.js to play HLS streams in any browser. Complete tutorial with code examples for developers.
What Is hls.js?
hls.js is an open-source JavaScript library that implements the HLS protocol in the browser. It enables playback of HLS streams on any modern browser by converting the streaming format into something the HTML5 video element can play via the Media Source Extensions (MSE) API.
The library handles playlist parsing, segment downloading, adaptive bitrate switching, AES-128 decryption, and buffer management — all automatically.
Basic Setup
Install hls.js via npm or include it from a CDN:
npm install hls.js
// Or via CDN
// <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
Minimal Working Example
import Hls from 'hls.js';
const video = document.getElementById('video');
const url = 'https://example.com/stream.m3u8';
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(url);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
video.play();
});
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// Safari native HLS support
video.src = url;
}
Key Configuration Options
| Option | Default | Description |
|---|---|---|
maxBufferLength | 30 | Maximum buffer length in seconds |
maxMaxBufferLength | 600 | Maximum buffer length for ABR |
startLevel | -1 | Starting quality level (-1 = auto) |
abrEwmaFastVoD | 4 | ABR fast estimate seconds (VOD) |
abrEwmaFastLive | 5 | ABR fast estimate seconds (live) |
debug | false | Enable debug logging |
Event Handling
Key events to handle:
// Manifest loaded
hls.on(Hls.Events.MANIFEST_PARSED, () => { /* levels available */ });
// Quality level switched
hls.on(Hls.Events.LEVEL_SWITCHED, (event, data) => {
console.log('Switched to level', data.level);
});
// Error handling
hls.on(Hls.Events.ERROR, (event, data) => {
if (data.fatal) {
hls.destroy();
}
});
Related Articles
HTML5 M3U8 Player: How Modern Browsers Play HLS Streams
Technical deep-dive into how HTML5 M3U8 players work using hls.js and MSE.
Build Your Own M3U8 Player with JavaScript
Step-by-step guide to building a custom M3U8/HLS video player using hls.js. Full source code and implementation walkthrough.
Hls.js Not Working? Debugging Tips & Solutions
Developer guide to debugging hls.js issues. Fix common JavaScript errors, configuration problems, and browser compatibility issues.