How to Use Link Headers for Pagination
Implement RFC 8288 Link headers for cursor and page pagination, emit correct rel values, and keep clients from parsing bodies for next links.
On this page
Introduction
Pagination answers the question of how a client walks a large collection. A response returns one page of items, and the client needs to know where the next page lives. The naive approach embeds a next URL in the JSON body, which couples navigation to the payload shape and forces every client to understand a bespoke field. The standardized alternative is the Link header, which carries navigation URLs as first-class HTTP metadata and works the same across resources.
This tutorial implements Link-based pagination for a Node.js API, covering the rel values that matter, how to construct absolute URLs that preserve filters, how the header behaves with cursor and page-number schemes, and how to test a full navigation walk. The examples use JSON but the technique is independent of the body format.
Emit Link headers with the right rel values
The Link header is a comma-separated list of link entries, each with a URL in angle brackets and one or more relationship parameters. The relationships used in pagination are first, prev, next, and last. rel=next is the one clients follow; rel=prev is the one they follow back; first and last are helpful when both ends are cheap to compute. Each entry can also carry a title and other extension parameters.
Emit only the links that exist. On the first page there is no prev; on the last page there is no next. A client decides it has reached the end when the next link is absent, so getting the presence right is what makes the walk terminate. Do not emit a next link that loops back to the same page, because a client that follows it will spin.
function linkHeader(baseUrl: string, page: number, perPage: number, total: number): string {
const lastPage = Math.max(1, Math.ceil(total / perPage));
const url = (p: number) => '<' + baseUrl + '?page=' + p + '&per_page=' + perPage + '>';
const links: string[] = [];
if (page > 1) links.push(url(1) + '; rel="first"', url(page - 1) + '; rel="prev"');
if (page < lastPage) links.push(url(page + 1) + '; rel="next"', url(lastPage) + '; rel="last"');
return links.join(', ');
}
Build absolute URLs and preserve filters
Each link must be an absolute URL, because a relative URL in a Link header is ambiguous and clients must resolve it themselves. Build the base from the original request: reuse the scheme, host, and path, then replace only the pagination parameters. Preserve every other query parameter such as filters, sort order, and search terms, because dropping them changes the result set between pages and produces confusing output.
Construct the URL from a URL object rather than string concatenation. Set the specific pagination parameter, leave the rest of the search parameters untouched, and serialize once. This avoids the classic bugs where a filter containing an ampersand or a space corrupts the URL.
function nextLink(req, cursor) {
const url = new URL(req.url ?? '/', 'https://' + (req.headers.host ?? 'localhost'));
if (cursor) url.searchParams.set('cursor', cursor);
else url.searchParams.delete('cursor');
return url.toString();
}
Cursor versus page-number links
With page-number pagination the links are simple arithmetic on the page index. With cursor pagination the next link embeds an opaque cursor derived from the last row, and there is usually no meaningful last link because computing the total requires a full scan. That is fine: cursor schemes typically emit only next and sometimes prev. The Link header accommodates both, so the client code that walks next is identical whether the server uses pages or cursors.
Keep the cursor opaque and signed where sensitive. A cursor is a client-held value; if it encodes a raw primary key, a client can tamper with it and ask for data it should not see. Encode the last sort key, and validate or sign the value so a modified cursor is rejected rather than silently returning a different slice or an error.
Keep the body independent of navigation
Let the body carry items and any metadata that belongs to the resource, and let the header carry navigation. This separation means the same client walker works for orders, users, and events. If a body field must echo the next link for front-end convenience, treat it as a derived convenience and make the header the source of truth, so the two cannot drift.
Do not put the total count in the header; it belongs in the body if the client needs it. The header is for links. Mixing counts into Link entries with custom rel values is nonstandard and confuses intermediaries.
Test a full navigation walk
Write a test that follows next until the header no longer contains one, counting the pages and asserting the total number of items matches the seeded data. Add a test that copies a filter from the first request and asserts it still appears in the next link, and a test that follows prev from a middle page back to the previous page. These three tests catch off-by-one page math, dropped filters, and missing termination.
curl -sD - -o body.json 'http://localhost:3000/orders?status=paid&page=2&per_page=20' | grep -i '^link:'
# expect rel="next" with the same status filter preserved, and rel="prev" pointing to page 1
Common pitfalls
Emitting a next link on the last page, dropping filters between pages, using relative URLs, exposing raw cursor values that clients can tamper with, and letting body navigation and header navigation disagree are the recurring mistakes. Each is caught by the navigation-walk test if it verifies termination, filter preservation, and cursor integrity.
Conclusion
Link headers make pagination navigation a protocol-level concern instead of a payload field. Emit only the rel entries that exist, build absolute URLs from the original request while preserving filters, keep cursors opaque and validated, and let the body stay about data. Self-check by walking next to termination and asserting the item count and the presence of filters and prev links. Standard navigation means one client walker serves every collection.
Sources: RFC 8288: Web Linking, MDN: Link header, GitHub REST API: pagination.
FAQ
- What is the difference between rel=next and rel=last?
- rel=next points to the following page and is the one clients follow; rel=last points to the final page and is usually only available when the total count is known cheaply. Cursor pagination often cannot provide last without scanning, so it emits next and prev only.
- Should paging links go in the body or the header?
- Either works, but the Link header is standardized by RFC 8288 and keeps the body's shape stable across resources. It also lets generic clients and proxies use navigation without understanding your payload.
Report a problem with this articleOpens a pre-filled issue on GitHub.