Build Pagination Link Headers (RFC 8288)

Build RFC 8288 Link headers for paginated APIs with self, first, previous, next and last relations and validated page bounds.

TypescriptData Fetching

Code

typescriptsnippet
32 lines
export function buildPaginationLinkHeader(
  baseUrl: string,
  options: { page: number; perPage: number; total: number },
): string {
  if (typeof baseUrl !== "string" || baseUrl.length === 0) {
    throw new TypeError("baseUrl must be a non-empty string");
  }
  const { page, perPage, total } = options;
  if (!Number.isInteger(page) || page < 1) {
    throw new RangeError("page must be a positive integer");
  }
  if (!Number.isInteger(perPage) || perPage < 1) {
    throw new RangeError("perPage must be a positive integer");
  }
  if (!Number.isInteger(total) || total < 0) {
    throw new RangeError("total must be a non-negative integer");
  }
  const lastPage = Math.max(1, Math.ceil(total / perPage));
  if (page > lastPage) throw new RangeError("page must not exceed the last page");
  const base = new URL(baseUrl);
  const link = (target: number, rel: string): string => {
    const url = new URL(base);
    url.searchParams.set("page", String(target));
    url.searchParams.set("limit", String(perPage));
    return "<" + url.toString() + '>; rel="' + rel + '"';
  };
  const parts = [link(page, "self"), link(1, "first")];
  if (page > 1) parts.push(link(page - 1, "prev"));
  if (page < lastPage) parts.push(link(page + 1, "next"));
  parts.push(link(lastPage, "last"));
  return parts.join(", ");
}

How the snippet works

The working surface is the functions link and buildPaginationLinkHeader — everything else is wiring.

The code refuses to proceed on bad state and throws TypeError and RangeError at its guard.

What to watch for

  • The guard typeof baseUrl !== "string" || baseUrl.length === 0 short-circuits the flow with an early throw when its condition holds.

Applying it

The main signature reads export function buildPaginationLinkHeader( baseUrl: string, options: { page: number; perPage: number; total…

buildPaginationLinkHeader is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

if (page > lastPage) throw new RangeError("page must not exceed the last page");
throw new RangeError("total must be a non-negative integer");
throw new RangeError("perPage must be a positive integer");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
Validation comes first — `TypeError` and `RangeError` marks the failure at `typeof baseUrl !== "string" || baseUrl.length === 0`, before any partial work happens.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `link`, `buildPaginationLinkHeader` at load time.