javascript
55 lines · 8 steps
Streaming video with HTTP range requests in Express
An Express route that serves video files with byte-range support so players can seek and stream instead of downloading everything.
Explained by
highlit
1const fs = require('fs');
2const path = require('path');
3const express = require('express');
4
5const router = express.Router();
6const VIDEO_ROOT = path.join(__dirname, '..', 'media');
7
8router.get('/videos/:name', (req, res) => {
9 const filePath = path.join(VIDEO_ROOT, path.basename(req.params.name));
10
11 fs.stat(filePath, (err, stats) => {
12 if (err || !stats.isFile()) {
13 return res.sendStatus(404);
14 }
15
16 const fileSize = stats.size;
17 const range = req.headers.range;
18
19 if (!range) {
20 res.writeHead(200, {
21 'Content-Length': fileSize,
22 'Content-Type': 'video/mp4',
23 'Accept-Ranges': 'bytes',
24 });
25 return fs.createReadStream(filePath).pipe(res);
26 }
27
28 const match = /^bytes=(\d*)-(\d*)$/.exec(range);
29 if (!match) {
30 return res.sendStatus(416);
31 }
32
33 const start = match[1] ? parseInt(match[1], 10) : 0;
34 const end = match[2] ? parseInt(match[2], 10) : fileSize - 1;
35
36 if (start > end || start >= fileSize || end >= fileSize) {
37 res.set('Content-Range', `bytes */${fileSize}`);
38 return res.sendStatus(416);
39 }
40
41 const chunkSize = end - start + 1;
42 res.writeHead(206, {
43 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
44 'Accept-Ranges': 'bytes',
45 'Content-Length': chunkSize,
46 'Content-Type': 'video/mp4',
47 });
48
49 const stream = fs.createReadStream(filePath, { start, end });
50 stream.on('error', () => res.destroy());
51 stream.pipe(res);
52 });
53});
54
55module.exports = router;
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1HTTP 206 partial responses with Content-Range let clients request byte slices, enabling video seeking without downloading the whole file.
- 2Sanitizing user-supplied filenames with path.basename prevents path-traversal attacks on the served directory.
- 3Piping a read stream to the response streams data lazily, keeping memory flat regardless of file size.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-video-with-http-range-requests-in-express-explained-javascript-045c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.