惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
Recent Announcements
Recent Announcements
C
Check Point Blog
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
爱范儿
爱范儿
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
月光博客
月光博客
AI
AI
美团技术团队
SecWiki News
SecWiki News
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cybersecurity and Infrastructure Security Agency CISA
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
aimingoo的专栏
aimingoo的专栏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Visual Studio Blog
T
The Exploit Database - CXSecurity.com
小众软件
小众软件
N
News | PayPal Newsroom
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
NISL@THU
NISL@THU
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
MongoDB | Blog
MongoDB | Blog
H
Heimdal Security Blog
Schneier on Security
Schneier on Security
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog RSS Feed
D
Docker
Spread Privacy
Spread Privacy
Cloudbric
Cloudbric
www.infosecurity-magazine.com
www.infosecurity-magazine.com
I
Intezer
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
AWS News Blog
AWS News Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build a custom HLS player in React with hls.js (no wrapper libraries)
Mason K · 2026-05-31 · via DEV Community

Mason K

Mason K

Posted on • Edited on

TL;DR

We'll build a custom HLS player on top of hls.js 1.6.x and React 19 with no wrapper library. Play/pause, seek, volume, quality readout, buffer state, and proper error recovery. End result is ~150 lines and bends to whatever UI you want.

📦 Code: github.com/USER/react-hls-player-demo (replace before publishing)

This is the "stop installing video.js for the third time" tutorial. The wrapper libraries are doing two things you need (the MSE shim and the error-recovery loop) and a lot of things you don't (a giant control bar, a plugin model, a CSS skin). The MSE shim is hls.js. The error-recovery loop is fifteen lines. Everything else can be your own React.

0. Versions

node 22.x
react 19.x
hls.js 1.6.16   # latest stable as of 2026-04-13

The 1.7 alpha is interesting (interstitial-ads improvements landed in canary on 2026-05-16) but not yet ready for production. Stick with 1.6 unless you're testing the next major.

1. Setup

npm create vite@latest react-hls-player-demo -- --template react-ts
cd react-hls-player-demo
npm install
npm install hls.js

For test streams, the Apple HLS test page has a few public manifests. The bipbop ad-stitched stream is the classic one:

https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8

2. The bare minimum: a hook that mounts hls.js

// src/useHls.ts
import { useEffect, useRef } from "react";
import Hls from "hls.js";

export function useHls(src: string) {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    // Safari (and iOS) plays HLS natively. Hand the URL to the browser.
    if (video.canPlayType("application/vnd.apple.mpegurl")) {
      video.src = src;
      return;
    }

    if (!Hls.isSupported()) return;

    const hls = new Hls({
      enableWorker: true,
      lowLatencyMode: true,
      backBufferLength: 30,
    });
    hls.loadSource(src);
    hls.attachMedia(video);

    return () => {
      hls.destroy();
    };
  }, [src]);

  return videoRef;
}

The cleanup matters. React 19's StrictMode mounts every effect twice in development. Without the hls.destroy(), you leak one Hls instance per remount and your dev server's memory usage will climb. Ask me how I know.

// src/App.tsx
import { useHls } from "./useHls";

const SRC = "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8";

export default function App() {
  const videoRef = useHls(SRC);
  return <video ref={videoRef} controls className="w-full max-w-4xl" />;
}

That plays HLS in every modern browser. Eight lines. The wrapper libraries' main value-add, "plays HLS in Chrome", is now done. Everything else is product.

3. Wiring real controls

Drop controls from <video> and write your own. Each control is a small piece of state synced to the element.

// src/Player.tsx
import { useEffect, useRef, useState } from "react";
import Hls from "hls.js";

export function Player({ src }: { src: string }) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const hlsRef = useRef<Hls | null>(null);
  const [playing, setPlaying] = useState(false);
  const [time, setTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [level, setLevel] = useState<string>("auto");

  useEffect(() => {
    const v = videoRef.current!;
    if (v.canPlayType("application/vnd.apple.mpegurl")) {
      v.src = src;
    } else if (Hls.isSupported()) {
      const hls = new Hls({ enableWorker: true, lowLatencyMode: true });
      hls.loadSource(src);
      hls.attachMedia(v);
      hls.on(Hls.Events.LEVEL_SWITCHED, (_, d) => {
        const lvl = hls.levels[d.level];
        setLevel(lvl ? `${lvl.height}p` : "auto");
      });
      hlsRef.current = hls;
    }
    return () => { hlsRef.current?.destroy(); hlsRef.current = null; };
  }, [src]);

  return (
    <div className="player">
      <video
        ref={videoRef}
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
        onTimeUpdate={(e) => setTime(e.currentTarget.currentTime)}
        onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
      />
      <div className="controls">
        <button onClick={() => {
          const v = videoRef.current!;
          playing ? v.pause() : v.play();
        }}>{playing ? "Pause" : "Play"}</button>

        <input
          type="range"
          min={0}
          max={duration || 0}
          step={0.1}
          value={time}
          onChange={(e) => {
            const v = videoRef.current!;
            v.currentTime = Number(e.target.value);
          }}
        />

        <span>{fmt(time)} / {fmt(duration)}</span>
        <span className="quality">{level}</span>
      </div>
    </div>
  );
}

function fmt(s: number): string {
  if (!isFinite(s)) return "0:00";
  const m = Math.floor(s / 60);
  const ss = Math.floor(s % 60).toString().padStart(2, "0");
  return `${m}:${ss}`;
}

The quality readout is the part wrappers tend to hide. LEVEL_SWITCHED fires every time hls.js picks a new ABR rendition, and hls.levels[level] has the bitrate, resolution, and codec strings. Surfacing "now playing 720p" in the corner of your player is a five-line feature that meaningfully changes how power users perceive your product.

4. Manual quality picker

Some users will want to force a quality, usually because they don't trust ABR or because they're on a metered connection. Wire it like this:

const [levels, setLevels] = useState<Hls["levels"]>([]);

useEffect(() => {
  const hls = hlsRef.current;
  if (!hls) return;
  hls.on(Hls.Events.MANIFEST_PARSED, () => setLevels(hls.levels));
}, []);

// in JSX:
<select
  value={hls.currentLevel}
  onChange={(e) => { hls.currentLevel = Number(e.target.value); }}
>
  <option value={-1}>Auto</option>
  {levels.map((l, i) => (
    <option key={i} value={i}>{l.height}p ({Math.round(l.bitrate / 1000)} kbps)</option>
  ))}
</select>

-1 means "let ABR pick"; any non-negative index pins the player to that level. After a user pins to 480p, the seek bar still works and the rest of ABR's logic still runs underneath, but the renderer stays at 480p.

5. The error recovery loop (do not skip)

This is the single thing the wrappers were doing that you actually need.

hls.on(Hls.Events.ERROR, (_, data) => {
  if (!data.fatal) return;

  if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
    console.warn("hls: network error, restarting load");
    hls.startLoad();
    return;
  }
  if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
    console.warn("hls: media error, recovering");
    hls.recoverMediaError();
    return;
  }
  console.error("hls: fatal", data);
  hls.destroy();
});

Three rules:

  1. Ignore non-fatal errors. hls.js retries those itself.
  2. Network errors get a fresh startLoad(). This is what saves a viewer who walked into a tunnel.
  3. Media errors get recoverMediaError(). This rebuilds the MSE source buffers, which is the only thing that fixes "the decoder gave up after a corrupt segment."

Add a tiny rate limiter in production. If recoverMediaError fails twice within a few seconds, destroy and recreate the Hls instance with a fresh source. Otherwise you can wedge yourself into an infinite recovery loop.

6. Buffer indicator

Showing "this video is buffering" properly means listening to the right events, not just paused.

const [stalled, setStalled] = useState(false);

const v = videoRef.current!;
v.addEventListener("waiting", () => setStalled(true));
v.addEventListener("playing", () => setStalled(false));

For the YouTube-style "this much of the video is buffered ahead" bar, use videoElement.buffered:

const buffered = videoRef.current?.buffered;
let aheadPct = 0;
if (buffered && buffered.length > 0 && duration > 0) {
  aheadPct = (buffered.end(buffered.length - 1) / duration) * 100;
}

Render a second <progress> underneath the seek bar at that percentage. Total time invested: ten minutes.

7. Subtitles

hls.js parses WebVTT tracks from the manifest into audioTracks and subtitleTracks. Toggle them like:

hls.subtitleDisplay = true;
hls.subtitleTrack = 0;        // -1 to disable

For language selection, hls.subtitleTracks is an array with name, lang, and default flags.

8. Cleanup checklist

Things people forget that bite later:

Mistake Symptom
No hls.destroy() in unmount Memory leak, Chrome devtools shows climbing JS heap
Forgetting Safari native path App works in Chrome dev, breaks on iPhone in QA
Listening to pause instead of waiting for buffering Players show "buffering" when the user manually pauses
Not handling MEDIA_ERROR Random unrecoverable freezes on bad-CDN nights
Hls.isSupported() === false ignored Old browsers show a broken player with no fallback

What's next

There are three places to take this once it's running:

  • Picture-in-Picture. videoRef.current.requestPictureInPicture(). One line, free feature.
  • MediaSession metadata. Set navigator.mediaSession.metadata so the OS lock screen shows the right title and artwork.
  • Player telemetry. Subscribe to Hls.Events.FRAG_LOADED and send the per-segment timings to your analytics. This is gold for debugging "the video stalled, but only for users in Brazil."

If you're playing assets from a managed video API (Mux, FastPix, Cloudflare Stream, api.video), most of them ship their own custom-element player that wires telemetry for you. Use it if you want the analytics for free. Build your own when the player UX is part of the product.

The 1.7 line of hls.js looks promising for interstitial ads and a cleaner LL-HLS toggle. Worth watching the hls.js releases page for the stable 1.7.0 cut later this year.

Happy playing.