Getting Started with hls.js: Tutorial and Examples
What Is hls.js?
hls.js is an open-source JavaScript library that plays HLS in browsers that lack native support. It parses M3U8 playlists, downloads segments, handles ABR and AES-128, and feeds media into an HTML5 <video> element through Media Source Extensions (MSE).
Safari can play HLS natively; everywhere else, hls.js is the standard approach. Concept background: HTML5 M3U8 player internals.
Install
npm install hls.js // 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
video.src = url;
}Useful Configuration Options
| Option | Default | Meaning |
|---|---|---|
maxBufferLength | 30 | Target buffer seconds |
startLevel | -1 | Start quality (-1 = auto) |
capLevelToPlayerSize | false | Limit quality to element size |
debug | false | Verbose logs |
Essential Events
hls.on(Hls.Events.MANIFEST_PARSED, () => { /* levels ready */ });
hls.on(Hls.Events.LEVEL_SWITCHED, (_, data) => {
console.log("level", data.level);
});
hls.on(Hls.Events.ERROR, (_, data) => {
if (data.fatal) {
// recover or destroy — see troubleshooting guide
}
});Debugging help: hls.js not working.
Next Steps
Add quality UI and stats, or follow build your own M3U8 player. To try streams without coding, use our free online player.
Frequently Asked Questions
Does hls.js work in Safari?
You usually use native HLS there instead.
Is hls.js free?
Yes, open source.
Do I need a backend?
No — only a reachable M3U8 URL.
Why is MSE required?
It lets JavaScript append media segments to the video element.