Skip to content

Pagination

rocambille edited this page Nov 1, 2026 · 4 revisions

Summary: Learn how to implement client and server pagination using standard HTTP Range headers (Range and Content-Range), keeping your API payloads clean and your React UI URL-driven.

What you'll learn:

  • Why returning whole collections in a single response creates performance bottlenecks
  • How pagination trade-offs differ between JSON payload wrappers and HTTP Range headers
  • How to implement HTTP Range semantics in Express with 206 Partial Content and 416 status codes
  • How to configure the React cache layer to handle custom headers and response parsing
  • How to build a URL-driven Pagination component that integrates seamlessly with browser navigation

The challenge of growing collections

When an application starts, returning all items from GET /api/items works well. However, as the database grows from dozens to thousands of records, two problems arise:

  1. Querying, serializing, and transferring thousands of rows slows down network response times and overburdens the browser DOM.
  2. Users need a structured way to navigate through large datasets using pages or infinite scrolling.

To solve this, the application must fetch data in slices while informing the client about the total count of items.

Comparing pagination strategies

There are two primary ways to design a paginated HTTP API.

Strategy 1: Wrapping the response body

Many APIs wrap the returned array inside a JSON object:

{
  "items": [
    { "id": 1, "title": "First item" }
  ],
  "total": 42
}

While simple to understand, this approach changes the root response structure from an array (Item[]) to an object. Existing API clients expecting an array break, and pagination metadata is included in the payload even when clients do not need it. Additionally, the server often hardcodes the page size.

Strategy 2: HTTP Range headers (RFC 9110)

HTTP natively supports partial resource transfers using standard headers. The same mechanism used by video players to request byte ranges can be applied to item collections using a custom items unit:

GET /api/items
Range: items=0-9

HTTP/1.1 206 Partial Content
Accept-Ranges: items
Content-Range: items 0-9/42

[...10 items...]

This approach offers several benefits:

  • The JSON response payload remains a clean Item[] array.
  • Total item count travels in the Content-Range header.
  • The server remains page-agnostic (it processes start/end item offsets, not page numbers).
  • Clients can request whatever slice size fits their UI layout.

Client and server responsibilities

A key architectural design in StartER is the separation of concerns:

  • The Server receives item range requests (items=0-9) and returns the requested slice alongside total count headers. It does not know or care about page numbers or UI page sizes.
  • The Client reads the page number from the URL (?page=2), converts page numbers into item ranges based on a local PAGE_SIZE constant, and issues the fetch call.
URL: /items?page=2
  ↓ (page 2 with PAGE_SIZE 10 → items=10-19)
Request: GET /api/items with Range: items=10-19
  ↓
Response: 206 Partial Content with Content-Range: items 10-19/42

Because page state lives in the URL query string (?page=2), browser back/forward buttons, bookmarks, and Server-Side Rendering (SSR) work out of the box.

Server implementation in Express

1. Repository total count

First, we added a count() method to itemRepository.ts to fetch the total number of non-deleted records:

// src/express/modules/item/itemRepository.ts

count(): number {
  const row = database
    .prepare("select count(*) as total from item where deleted_at is null")
    .get();

  return Number(row?.total);
}

2. Range request handler

In itemActions.ts, the browse handler inspects the Range header, validates requested boundaries, and returns a 206 Partial Content response:

// src/express/modules/item/itemActions.ts

const browse: RequestHandler = (req, res) => {
  res.setHeader("Accept-Ranges", "items");

  // Inspect the Range header
  const match = req.headers.range?.match(/^items=(\d+)-(\d+)$/);

  if (!match) {
    res.sendStatus(400);
    return;
  }

  const [start, end] = [Number(match[1]), Number(match[2])];

  // Validate the range
  const total = itemRepository.count();

  // An empty collection is sent whole: an empty list is not an error
  if (total === 0) {
    res.setHeader("Content-Range", "items */0");
    res.status(200).json([]);
    return;
  }

  if (start < 0 || start > end || start >= total) {
    res.setHeader("Content-Range", `items */${total}`);
    res.sendStatus(416);
    return;
  }

  // Fetch items
  const limit = end - start + 1;
  const items = itemRepository.findAll(limit, start);

  // Send response
  res.setHeader(
    "Content-Range",
    `items ${start}-${Math.min(end, total - 1)}/${total}`,
  );
  res.status(206).json(items);
};

Status codes summary:

Status Code Situation Header Sent
200 OK Empty collection (total = 0), sent whole as [] Content-Range: items */0
206 Partial Content Valid range requested Content-Range: items start-end/total
400 Bad Request Missing or invalid Range header format -
416 Range Not Satisfiable Out of bounds range (start >= total) Content-Range: items */total

Important

The Accept-Ranges: items header is sent in all cases to indicate that the server accepts item range requests.

Frontend implementation in React

1. Extending the cache helper

Because cached requests in React use() rely on Promise identity, fetching different item ranges requires distinct cache entries. The getOrFetch helper accepts an options parameter allowing custom headers and custom response parsing:

// src/react/helpers/cache.ts

export const getOrFetch = <T>(
  url: string,
  options?: {
    parse?: (response: Response) => Promise<T>;
    headers?: Record<string, string>;
    ttl?: number;
  },
): Promise<T>

When options.headers is provided, the cache key combines the URL and serialized headers (url\0headers). A utility helper extracts the total count from Content-Range:

// src/react/helpers/pagination.ts

export const parseContentRangeTotal = (header: string | null): number => {
  const match = /\/(\d+)$/.exec(header ?? "");
  return match ? Number(match[1]) : 0;
};

getOrFetch is imported from cache.ts and parseContentRangeTotal is imported from pagination.ts. Both are used in component ItemList (see below).

2. Displaying paginated items

The ItemList component computes item ranges from the ?page=N URL parameter, passes the Range header to getOrFetch, and extracts both item data and total count:

// src/react/components/item/ItemList.tsx
import { use } from "react";
import { Link, useSearchParams } from "react-router";
import { getOrFetch, useRefresh } from "../../helpers/cache";
import { parseContentRangeTotal } from "../../helpers/pagination";
import { useMe } from "../auth/MeContext";
import Pagination from "../Pagination";

const PAGE_SIZE = 10;

function ItemList() {
  useRefresh("/api/items");

  const { isAuthenticated } = useMe();

  const [searchParams] = useSearchParams();
  const page = Number(searchParams.get("page")) || 1;
  const start = (page - 1) * PAGE_SIZE;
  const end = start + PAGE_SIZE - 1;

  const { items, total } = use(
    getOrFetch<{ items: Item[]; total: number }>("/api/items", {
      headers: { Range: `items=${start}-${end}` },
      parse: async (res) => ({
        items: await res.json(),
        total: parseContentRangeTotal(res.headers.get("Content-Range")),
      }),
    }),
  );

  return (
    <>
      <h1>Items</h1>
      {isAuthenticated && (
        <Link to="/items/new" data-testid="items-new">
          Add
        </Link>
      )}

      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <Link to={`/items/${item.id}`}>{item.title}</Link>
          </li>
        ))}
      </ul>
      <Pagination total={total} pageSize={PAGE_SIZE} currentPage={page} />
    </>
  );
}

export default ItemList;

3. The Pagination component

The Pagination component renders accessible navigation links based on total item count and current page:

// src/react/components/Pagination.tsx

import { Link, useSearchParams } from "react-router";

interface PaginationProps {
  total: number;
  pageSize: number;
  currentPage: number;
}

function Pagination({ total, pageSize, currentPage }: PaginationProps) {
  const [searchParams] = useSearchParams();

  const totalPages = Math.ceil(total / pageSize);

  if (totalPages <= 1) return null;

  // "?q=stuff&page=3": change the page, keep the rest
  const toPage = (page: number) => {
    const next = new URLSearchParams(searchParams);
    next.set("page", String(page));

    return `?${next.toString()}`;
  };

  return (
    <nav aria-label="Pagination">
      {currentPage > 1 && <Link to={toPage(currentPage - 1)}>Previous</Link>}

      {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
        <Link
          key={page}
          to={toPage(page)}
          aria-current={page === currentPage ? "page" : undefined}
        >
          {page}
        </Link>
      ))}

      {currentPage < totalPages && (
        <Link to={toPage(currentPage + 1)}>Next</Link>
      )}
    </nav>
  );
}

export default Pagination;

The parent computes currentPage from the URL and passes it as a prop. Pagination only reads the search params to keep the other ones (search, filters, sort) when changing page.

Cheatsheet: Adding pagination to a new resource

Follow this step-by-step checklist to add pagination to any resource in StartER (let's say products):

  1. Repository (src/express/modules/product/productRepository.ts): Add a count(): number method executing select count(*) as total from product where deleted_at is null.

  2. Actions (src/express/modules/product/productActions.ts): In the browse action:

    • Set header res.setHeader("Accept-Ranges", "products").
    • Parse req.headers.range with /^products=(\d+)-(\d+)$/. Return 400 if missing or invalid.
    • Fetch total = productRepository.count(). If it is 0, send 200 OK with [] and Content-Range: products */0.
    • Return 416 with Content-Range: products */total if start < 0, start > end, or start >= total.
    • Query the slice productRepository.findAll(end - start + 1, start).
    • Send 206 Partial Content with header Content-Range: products start-min(end, total - 1)/total.
  3. React Component (src/react/components/product/ProductList.tsx):

    • Extract page from URL query: const page = Number(searchParams.get("page")) || 1;
    • Compute range bounds: start = (page - 1) * PAGE_SIZE, end = start + PAGE_SIZE - 1.
    • Call getOrFetch with Range header and parse options:
      const { products, total } = use(
        getOrFetch<{ products: Product[]; total: number }>("/api/products", {
          headers: { Range: `products=${start}-${end}` },
          parse: async (res) => ({
            products: await res.json(),
            total: parseContentRangeTotal(res.headers.get("Content-Range")),
          }),
        }),
      );
    • Render <Pagination total={total} pageSize={PAGE_SIZE} currentPage={page} />.
  4. API Contract (tests/contracts/products.ts):

    • Define request: { headers: { Range: "products=0-9" } }.
    • Expect response: { status: 206, headers: { "content-range": "products 0-9/total" } }.

Non-paginated endpoints: the escape hatch

Not every resource in your application requires pagination. For small, bounded collections (such as tags, categories, roles, or dropdown options), you can completely skip Range headers and use standard 200 OK JSON responses.

1. Backend: return a direct array

// src/express/modules/tag/tagActions.ts

const browse: RequestHandler = (_req, res) => {
  const tags = tagRepository.findAll();

  res.json(tags); // 200 OK with Tag[] array
};

2. Frontend: single-line getOrFetch

Without Range headers, the React fetching code simplifies to a single declarative line:

// src/react/components/tag/TagList.tsx

function TagList() {
  const tags = use(getOrFetch<Tag[]>("/api/tags"));

  return (
    <ul>
      {tags.map((tag) => (
        <li key={tag.id}>{tag.name}</li>
      ))}
    </ul>
  );
}

Optional: Hybrid pagination support

If you want an endpoint to support both full collection retrieval by default and partial slicing when requested by a client:

const browse: RequestHandler = (req, res) => {
  res.setHeader("Accept-Ranges", "items");

  // Fallback: if no Range header is sent, return the full list (200 OK)
  if (!req.headers.range) {
    const items = itemRepository.findAll(itemRepository.count(), 0);
    res.json(items);
    return;
  }

  // Otherwise, validate the Range header and return 206 Partial Content
  const match = req.headers.range.match(/^items=(\d+)-(\d+)$/);
  if (!match) {
    res.sendStatus(400);
    return;
  }

  // [Range slicing logic...]
};

Advanced pagination concepts

  • Link response headers (RFC 8288): APIs such as GitHub use Link headers to provide direct URLs for rel="next" and rel="prev". When using client-managed item ranges, offset calculations happen directly on the client side.
  • Cursor-based pagination: for massive or rapidly changing datasets, offset pagination (OFFSET N) can become slow and miss/duplicate items during concurrent inserts. Cursor pagination uses an opaque token (such as an item ID or timestamp) to fetch records after a specific point.

See also

Clone this wiki locally