Go to content
Web development

Cursor Pagination with TypeScript Fetch

When your TypeScript client needs every record from an API that splits results into pages, it must request each page in turn and use the API’s continuation information in the next request. A cursor is a value the server returns to show where to continue. Some APIs return a URL for the next page instead. Your client follows that instruction, adds each page’s items to an array, and stops only when the API signals that no page follows.

This is client-side pagination: your code sends a series of API requests and collects their results. The server handles database pagination by dividing query results into pages. The API’s contract, or documented rules, tells your client how to request the next page, how to detect the end, and what to do if a request fails.

Follow the API’s continuation contract

Read the endpoint’s pagination documentation before writing the loop. APIs use different conventions. One might return nextCursor and expect a cursor query parameter, a value in the request URL, on the next request. Another might return a nextPageToken; GitHub’s REST API can provide a next-page URL in the response’s Link header. Even one provider can use different pagination methods for different endpoints. Close, for example, documents cursors for some endpoints and offsets for most list endpoints.

For an endpoint that uses cursors, keep the other query settings the same and send the returned cursor as the endpoint specifies. An opaque cursor is a value whose meaning the client does not interpret; pass it back as received rather than constructing or changing it. The Tempo API, for example, says to omit the cursor on the first request, then pass each response’s nextCursor back as cursor; nextCursor: null marks the end. Cursor field names and request locations vary, so adapt the code to the endpoint rather than assuming every API uses this shape.

Here is a TypeScript pattern for an API that returns items and nextCursor, then expects the client to send a cursor query parameter in the next request:

type CursorPage<T> = {
  items: T[];
  nextCursor: string | null;
};

type PaginationFailure<T> = {
  items: T[];
  cursorForFailedPage: string | null;
  cause: unknown;
};

class PageRequestError<T> extends Error {
  constructor(public readonly failure: PaginationFailure<T>) {
    super("A page request failed");
    this.name = "PageRequestError";
  }
}

async function fetchAll<T>(baseUrl: string): Promise<T[]> {
  const items: T[] = [];
  const seenCursors = new Set<string>();
  let cursor: string | null = null;

  while (true) {
    const cursorForThisPage = cursor;
    const url = new URL(baseUrl);

    if (cursorForThisPage !== null) {
      url.searchParams.set("cursor", cursorForThisPage);
    }

    let page: CursorPage<T>;

    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`Page request returned ${response.status}`);
      }
      page = (await response.json()) as CursorPage<T>;
    } catch (cause) {
      throw new PageRequestError<T>({
        items,
        cursorForFailedPage: cursorForThisPage,
        cause,
      });
    }

    items.push(...page.items);

    if (page.nextCursor === null) {
      return items;
    }

    if (
      page.nextCursor === cursorForThisPage ||
      seenCursors.has(page.nextCursor)
    ) {
      throw new Error("The API returned a repeated cursor");
    }

    seenCursors.add(page.nextCursor);
    cursor = page.nextCursor;
  }
}

The example assumes the endpoint uses a query parameter named cursor and returns the JSON fields shown above. Change both to match the API. URLSearchParams encodes values for the query string, but the client should still pass the cursor back unchanged. The cast on response.json() tells TypeScript what shape to expect. It does not check the data while the code runs.

When an API returns a URL for the next page, follow that URL rather than adding a cursor parameter yourself. GitHub’s REST API documents a Link header with a URL labeled rel="next"; the client follows that URL until no next link appears. The meaning of the Link header’s parameters varies by endpoint. Use a parser or client library that understands that endpoint’s format instead of guessing which query parameters to add.

Stop only when the API signals the end

Use the endpoint’s documented signal that there are no more pages. The API might indicate this with a missing nextPageToken, a null cursor, or no next link. Moralis documents stopping when no cursor is returned, while GitHub’s REST API uses the absence of a rel="next" link.

Do not stop just because a page has fewer items than requested or has no items, unless the endpoint says that means there are no more pages. Some APIs return a short or empty page before the final page. The Google AIP-158 guidance summarized in cursor-pagination testing advice makes the same distinction: the API’s end signal, not the page length, determines whether more results remain.

Check for repeated cursors too. If the server returns a cursor the client already used, the loop would fetch the same page again. The example detects this and stops with an error.

Keep collected results when a page fails

The client should add each successful page to the results before requesting the next one. Then earlier results remain available if a later request fails. The example throws a PageRequestError that contains the items collected so far and the cursor for the failed page. The calling code can report those items as incomplete, or retry that page if the endpoint allows the client to reuse its cursor.

After an error, do not present the collected array as complete. If you retry, request the same failed page and add its items only after the request succeeds. If the endpoint does not support cursor reuse or the cursor has expired, restarting from the first page is simpler. The API defines how long a cursor remains valid and whether results stay consistent between requests. Check the endpoint’s contract before saving a cursor for later use. A cursor alone does not guarantee that every page reflects the same snapshot of the data.

More in Web development Back to top ↑