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

Walkthrough

Space play step click any line
Three takeaways
  1. 1HTTP 206 partial responses with Content-Range let clients request byte slices, enabling video seeking without downloading the whole file.
  2. 2Sanitizing user-supplied filenames with path.basename prevents path-traversal attacks on the served directory.
  3. 3Piping a read stream to the response streams data lazily, keeping memory flat regardless of file size.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Streaming video with HTTP range requests in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code