Express req.range() Method
What you’ll learn
- How
req.range()parses Range headers. - How to handle valid, invalid, and unsatisfiable ranges.
- How to return partial content correctly with status
206. - How to implement resumable file streaming endpoints.
Usage syntax
javascript
req.range(size)
req.range(size, options)1
Parse range and respond with partial bytes
javascript
app.get('/video', function (req, res) {
var size = 1000000; // total bytes (example)
var ranges = req.range(size);
if (ranges === -1) return res.status(416).send('Range Not Satisfiable');
if (ranges === -2) return res.status(400).send('Malformed Range Header');
if (!ranges || !ranges.length) return res.status(200).send('Send full content');
res.status(206).send('Send requested range');
});2
Use combine option for overlapping ranges
javascript
app.get('/file', function (req, res) {
var size = 500000;
var ranges = req.range(size, { combine: true });
res.json({ parsedRanges: ranges });
});❓ FAQ
It parses the incoming HTTP Range header into byte ranges for a known resource size.
Pass the full resource size in bytes, and optionally options for parsing behavior.
It returns an array-like ranges object, -1 for unsatisfiable ranges, or -2 for malformed headers.
Use it when implementing partial downloads, streaming media, or resumable file transfers.
Yes. You must set Content-Range, Accept-Ranges, Content-Length, and status 206 as needed.
Did you know?
req.range(size) parses the Range header and helps build proper 206 Partial Content responses.
4 people found this page helpful
