Sub topic 16
Serving media: MIME types and range requests
This chapter assumes you can write <video> and <source> markup, and that you know basic HTTP: request and response headers, status codes, and what a web server does with a static file. The markup can be perfect and playback can still fail because of how the server delivers the file. Two things matter most: the Content-Type header and support for byte ranges.
What the browser needs from the server
When a media element loads a file, the browser sends an ordinary GET request. It then relies on the response for three things:
- A correct
Content-Type. This is the MIME type, such asvideo/mp4. Browsers use it to decide whether they can play the resource. - Range support. The server must be able to send part of a file when asked.
- A reliable length.
Content-LengthorContent-Rangetells the browser how big the file is, so it can show a duration and a seek bar.
MIME types for media
A MIME type names the format of a response body. For media files, these are the values you will use most:
| File | Content-Type |
|---|---|
| `.mp4` (video) | `video/mp4` |
| `.m4a` (audio) | `audio/mp4` |
| `.webm` | `video/webm` or `audio/webm` |
| `.ogg`, `.oga` | `audio/ogg` |
| `.mp3` | `audio/mpeg` |
| `.wav` | `audio/wav` |
| `.vtt` (captions) | `text/vtt` |
Most servers map file extensions to types from a built-in table. Newer or uncommon extensions are often missing from that table, and the server then falls back to application/octet-stream. A browser may refuse to play a file served that way, especially when the server also sends X-Content-Type-Options: nosniff, which forbids the browser from guessing the type.
.vtt is the usual culprit for captions. Browsers expect text/vtt, and a <track> can fail silently when the server sends something else.
The type attribute on <source> is a separate mechanism. It is a hint the browser reads before downloading anything, so it can skip formats it cannot play. It does not replace the server header. Keep the two consistent.
Why range requests matter
A video can be hundreds of megabytes. If the server could only send whole files, a user who drags the seek bar to the middle would wait for everything before that point.
HTTP solves this with range requests. The browser asks for a byte span, and the server answers with only that span:
The headers involved are:
Accept-Ranges: bytesin a response tells the client that the server supports ranges.Range: bytes=START-ENDin a request asks for a span.ENDmay be omitted to mean "to the end of the file".206 Partial Contentis the status for a successful range response.Content-Range: bytes START-END/TOTALsays which span the body holds and the full file size.416 Range Not Satisfiableis the status when the requested start lies beyond the end of the file.
Some browsers require range support for seeking, and some will not play certain files at all without it. Safari is the strictest. A server that ignores Range and always returns 200 with the whole file can seem to work in Chrome but fail in Safari.
Checking your server with curl
Request the first bytes and print only the headers:
curl -s -D - -o /dev/null -H "Range: bytes=0-99" https://example.com/media/clip.mp4A healthy response looks like this:
HTTP/2 206
content-type: video/mp4
accept-ranges: bytes
content-range: bytes 0-99/80000000
content-length: 100If you see 200 and a content-length equal to the whole file, the server ignored the range. If content-type is application/octet-stream, fix the type mapping.
Static servers and CDNs
Mature web servers handle ranges for static files without any configuration. In nginx you mainly make sure the type table covers your files and avoid compressing media:
http {
include mime.types;
default_type application/octet-stream;
types {
text/vtt vtt;
}
server {
listen 80;
root /var/www/site;
location /media/ {
gzip off;
expires 30d;
}
}
}The types block here sits in the http context and is merged with the included file, so .vtt is added to the standard list. If you instead put types inside a location, it replaces the whole table for that location, and .mp4 would then be unmapped.
Compression breaks the model because byte offsets then refer to the compressed stream, not the file. MP4, WebM and MP3 are already compressed, so gzip gains almost nothing.
Behind a CDN, check that the CDN forwards or serves Range requests and does not strip Accept-Ranges. Also check that its cache key does not treat each range as a separate object without caching it.
Writing your own range handler
Dynamic servers, such as an application that streams files from private storage, must implement ranges themselves. This Node.js example (save it as server.mjs, with a clip.mp4 beside it) shows the logic:
import { createServer } from 'node:http';
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
const FILE = './clip.mp4';
createServer(async (req, res) => {
if (req.url !== '/clip.mp4') {
res.writeHead(404).end();
return;
}
let size;
try {
({ size } = await stat(FILE));
} catch {
res.writeHead(404).end();
return;
}
const base = { 'Content-Type': 'video/mp4', 'Accept-Ranges': 'bytes' };
const header = req.headers.range;
if (!header) {
res.writeHead(200, { ...base, 'Content-Length': size });
createReadStream(FILE).pipe(res);
return;
}
const match = /^bytes=(\d*)-(\d*)$/.exec(header);
if (!match || (match[1] === '' && match[2] === '')) {
res.writeHead(416, { ...base, 'Content-Range': `bytes */${size}` }).end();
return;
}
let start;
let end;
if (match[1] === '') {
// Suffix form: "bytes=-500" means the last 500 bytes.
start = Math.max(size - Number(match[2]), 0);
end = size - 1;
} else {
start = Number(match[1]);
end = match[2] === '' ? size - 1 : Math.min(Number(match[2]), size - 1);
}
if (start >= size || start > end) {
res.writeHead(416, { ...base, 'Content-Range': `bytes */${size}` }).end();
return;
}
res.writeHead(206, {
...base,
'Content-Range': `bytes ${start}-${end}/${size}`,
'Content-Length': end - start + 1,
});
createReadStream(FILE, { start, end }).pipe(res);
}).listen(8080, () => console.log('Listening on http://localhost:8080'));Note that end is inclusive, so the body length is end - start + 1. Off-by-one errors here are the most common reason a hand-written handler produces corrupt or stalled playback.
Common errors
- Wrong
Content-Type. The file downloads but will not play. Check the response header, not the file extension. - Ranges ignored. The video plays but seeking restarts from the beginning, or Safari refuses to play. Test with the
curlcommand above. - Wrong
Content-Lengthon a206. It must be the length of the slice, not the whole file. - Compressed media. Turn off gzip and Brotli for media paths.
- Authentication on range requests. If a cookie or token protects the file, every range request must pass the same check. Short-lived signed URLs can expire during a long session.
- Missing CORS headers. Cross-origin media and captions have extra requirements, covered in the next chapter.
Exercise
A video plays from the start in every browser, but dragging the seek bar to the end makes it restart in Safari. In the Network panel, the response to the video request has status 200 and no Accept-Ranges header. What is wrong, and how do you confirm and fix it?
Show answer
The server is ignoring the Range header and sending the whole file with 200. Confirm with curl -s -D - -o /dev/null -H "Range: bytes=0-99" URL; a correct server answers 206 with a Content-Range header. Fix it by enabling range support in the static server or CDN, or by adding range handling to the application endpoint so that it returns 206, Content-Range, a slice-sized Content-Length, and Accept-Ranges: bytes.
Exercise
A <track kind="captions" src="clip.en.vtt"> shows no captions. The file is valid WebVTT and the path is correct. Name one server-side cause to check.
Show answer
The server may be sending the wrong Content-Type for .vtt, such as application/octet-stream. It should be text/vtt. Add the mapping to the server's type table.