How to Serve HTTP Range Requests and Partial Content
Parse Range headers, answer with 206 and Content-Range, support multi-range responses, and handle invalid or unsatisfiable ranges correctly.
On this page
Introduction
Range requests are the mechanism that makes resumable downloads, video seeking, and parallel chunk fetching possible. Instead of asking for an entire resource, a client asks for a byte slice and the server replies with exactly that slice. The feature looks small, but a naive implementation produces corrupt downloads: the browser resumes from the wrong offset, a player stalls on a seek, and the bug only appears on large files over flaky networks. Getting the status code, the byte math, and the boundary cases right is the difference between a working download and a silently truncated one.
This tutorial implements byte-range serving for a Node.js static file handler. It covers the Accept-Ranges advertisement, the four syntactic forms of a Range header, the 206 and 416 responses, how ranges interact with conditional requests, and the tests that catch off-by-one errors. The examples use a file-backed handler, but the same rules apply to object storage, databases, and streamed responses.
Advertise support and parse the header
A server signals support by sending Accept-Ranges: bytes on responses. The header is optional but recommended, because a client that does not see it may fall back to fetching the whole file. A response without Accept-Ranges is not a promise either way, but an explicit bytes value removes ambiguity for download managers and players.
The Range header names one or more ranges. A byte-range spec is either first-last, where first is a zero-based offset, a start- offset that runs to the end of the file, or a -suffix offset counting back from the end. A malformed Range header should be ignored and the full representation served, because the specification treats an unparsable range as if no range were requested. Only syntactically valid ranges that fall outside the resource trigger a 416.
function parseRange(header, size) {
const m = /^bytes=(.+)$/.exec(header.trim());
if (!m) return null; // malformed -> ignore, serve 200
const first = m[1].split(',')[0].trim();
let start, end;
if (first.startsWith('-')) {
const suffix = Number(first.slice(1));
if (!Number.isInteger(suffix) || suffix <= 0) return null;
start = Math.max(0, size - suffix);
end = size - 1;
} else {
const [a, b] = first.split('-');
start = Number(a);
end = b === '' || b === undefined ? size - 1 : Number(b);
}
if (!Number.isInteger(start) || !Number.isInteger(end)) return null;
if (start > end || start >= size) return { unsatisfiable: true, size };
end = Math.min(end, size - 1);
return { start, end, size };
}
Return 206 with the right headers
When a valid range is present, respond with 206 Partial Content. The Content-Range header states the inclusive byte range and the total size in the form bytes start-end/total, and Content-Length must equal end minus start plus one, not the full resource size. Sending the full Content-Length with a partial body is one of the classic corruption bugs: the client waits for bytes that never arrive.
Open the underlying stream at the resolved offset and end it after the computed length. For files, read with a bounded stream rather than reading the whole file into memory and slicing it. For object storage, most SDKs accept a byte range directly, which avoids transferring the whole object to the application.
import { createReadStream, statSync } from 'node:fs';
function respondRange(req, res, filePath) {
const size = statSync(filePath).size;
const header = req.headers.range;
if (!header) {
res.writeHead(200, { 'content-length': size, 'accept-ranges': 'bytes' });
createReadStream(filePath).pipe(res);
return;
}
const parsed = parseRange(header, size);
if (!parsed) {
res.writeHead(200, { 'content-length': size, 'accept-ranges': 'bytes' });
createReadStream(filePath).pipe(res);
return;
}
if (parsed.unsatisfiable) {
res.writeHead(416, { 'content-range': 'bytes */' + size, 'accept-ranges': 'bytes' });
res.end();
return;
}
const { start, end } = parsed;
res.writeHead(206, {
'content-range': 'bytes ' + start + '-' + end + '/' + size,
'content-length': end - start + 1,
'accept-ranges': 'bytes',
});
createReadStream(filePath, { start, end }).pipe(res);
}
Handle unsatisfiable and multi-range requests
A syntactically valid range whose start is at or beyond the end of the resource cannot be satisfied. Answer 416 Range Not Satisfiable with Content-Range: bytes */total, where the asterisk replaces the range because no slice exists. This is the correct response for a stale download manager that resumes past a now-shorter file, and it lets the client restart cleanly instead of hanging.
Multi-range requests, where a client lists several ranges separated by commas, allow a single request to fetch disjoint slices. The specification offers a simple escape hatch: a server may ignore the range set and answer with a full 200. That is often the pragmatic choice. If you implement multi-part responses, use Content-Type: multipart/byteranges with a boundary and one part per range, each carrying its own Content-Range. This adds significant complexity, so only implement it if your metrics show multi-range use.
Ranges and conditional requests
A download that resumes across sessions often combines a Range header with an If-Range precondition. If-Range carries a validator, an ETag or a date. When the validator still matches, the server sends the partial slice; when it does not, the server ignores the range and returns the full 200 body. This prevents the client from stitching together bytes from two different versions of a file, which produces a corrupt result. Implement If-Range by comparing the validator before applying the range.
Static files that never change should be served with an ETag and a long max-age. The ETag lets If-Range work, and the immutable caching means subsequent requests are answered from the client cache without any range logic. When a range request does reach the origin, keep the ETag stable across restarts by hashing the file bytes rather than relying on file metadata that a deploy tool might touch.
Test edge cases that break downloads
Range bugs are almost always off-by-one or boundary mistakes. Write tests that assert exact status codes and byte counts for each syntactic form: a closed range, an open-ended range, a suffix range, a range ending past the file end, and a range starting past the file end. Then add a resume test that fetches the first half, requests the second half with If-Range, and concatenates the two to compare against the original bytes.
# first 100 bytes
curl -s -o part1.bin -D - -H 'Range: bytes=0-99' http://localhost:3000/big.bin
# last 100 bytes via suffix
curl -s -o part2.bin -D - -H 'Range: bytes=-100' http://localhost:3000/big.bin
# unsatisfiable
curl -s -o /dev/null -w 'status=%{http_code}\n' -H 'Range: bytes=99999999-' http://localhost:3000/big.bin
# resume with conditional range
curl -s -o tail.bin -H 'Range: bytes=100-' -H 'If-Range: "etag-from-first-response"' http://localhost:3000/big.bin
Conclusion
Range serving is small in code and large in consequence. Advertise Accept-Ranges, parse all three byte-range forms, ignore malformed headers, answer unsatisfiable ranges with 416 and a Content-Range of bytes */total, and never mix a partial body with a full Content-Length. Support If-Range so resumed downloads cannot stitch incompatible versions. Test each boundary explicitly, and verify a client-side resume by concatenating halves and comparing to the original file. Self-check by diffing the reassembled bytes against the source; any difference means an offset, a length, or a status code is wrong.
Keep the byte math in one small, unit-tested function. Range handling scattered across handlers is where off-by-one errors hide, and a single tested parser makes the behavior predictable across static files, object storage, and streamed responses alike.
Sources: MDN: HTTP range requests, RFC 9110: Range and Content-Range, MDN: Content-Range header.
FAQ
- What status should an unsatisfiable range return?
- Return 416 Range Not Satisfiable with a Content-Range header of bytes */total. This tells the client the requested slice does not exist, for example a start offset past the end of the file.
- Do I need multi-range support?
- Not always. If a client sends several ranges in one header you may answer with a single 200 full body, which the specification permits. Multi-part responses with multipart/byteranges are only worth implementing when resume and parallel download patterns dominate your traffic.
Report a problem with this articleOpens a pre-filled issue on GitHub.