Parse the Link header for pagination
Extract next, prev, first and last page URLs from an RFC 8288 Link header like GitHub's API returns.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function parseLinkHeader(header) {
const links = {};
if (!header) return links;
for (const part of header.split(/,\s*(?=<)/)) {
const match = /^<([^>]+)>\s*;(.*)$/.exec(part.trim());
if (!match) continue;
const rel = /rel="?([^";]+)"?/.exec(match[2]);
if (rel) links[rel[1]] = match[1];
}
return links;
}Example / expected output
parseLinkHeader('<https://api.x.io/items?page=2>; rel="next", <https://api.x.io/items?page=9>; rel="last"')
// { next: "https://api.x.io/items?page=2", last: "https://api.x.io/items?page=9" }How it works
Many APIs (GitHub, GitLab, WordPress) return pagination links in a Link header instead of the body. Following the next URL is more robust than building page numbers yourself. This parser handles multiple comma-separated links and ignores malformed parts.
Related snippets
- Python Tested
Fetch JSON with the standard library
A small GET helper using urllib with a timeout, status check, size limit and JSON decoding errors.
- JavaScript Tested
Conditional GET with ETag and 304
Compute a strong ETag for a response body and answer If-None-Match with 304 Not Modified to save bandwidth.
- JavaScript Tested
Fetch every page of a paginated API with an async generator
Iterate cursor-paginated API results with for await, loading pages lazily and stopping early when needed.
- JavaScript Tested
fetch with a timeout and error handling
Abort slow HTTP requests with AbortSignal.timeout and turn non-2xx responses into real errors.

