REST API pagination is more than adding a page number to a URL. The pagination strategy affects whether users see stable results, whether clients miss or duplicate records, and how safely an interface can support retries, live updates, and infinite scroll. This guide compares offset, page-number, cursor, keyset, and time-based approaches, then provides reusable JavaScript and TypeScript workflows for implementing and testing each one.
Overview
Pagination limits the amount of data returned in one response. A client requests a slice of a larger collection, processes it, and follows a link or token to request the next slice. A well-designed integration must answer four questions:
- How does the client request the next page?
- What ordering makes the result set predictable?
- What happens when records are inserted, deleted, or updated while the user is paging?
- How should the client handle retries, rate limits, empty pages, and malformed responses?
The main choice is usually between offset pagination and cursor pagination. Offset pagination is easy to understand and works well for small, relatively stable collections. Cursor and keyset pagination generally provide more consistent traversal when a collection changes during a long request sequence. Time-based pagination is useful for feeds, audit logs, and synchronization jobs that process records by a timestamp or event window.
| Pattern | Typical request | Strength | Trade-off |
|---|---|---|---|
| Page number | ?page=3&pageSize=25 | Simple UI model | Can drift when records change |
| Offset | ?offset=50&limit=25 | Direct access to a position | Later pages can become expensive or shift |
| Cursor | ?limit=25&after=opaque-token | Good continuity across changing data | Usually not suitable for jumping to page 20 |
| Keyset | ?limit=25&afterId=1234 | Efficient ordered traversal | Requires a stable, indexed sort key |
| Time-based | ?since=2026-01-01T00:00:00Z | Useful for feeds and sync | Needs careful timestamp boundaries and tie handling |
Before writing client code, inspect the API contract. Look for fields such as next, nextLink, nextCursor, hasMore, or an RFC-style link relation. Do not assume that a cursor is an integer, that a missing next link means an error, or that the response uses the same envelope for every endpoint.
For related API troubleshooting, the frontend API debugging checklist covers request headers, fetch failures, and network diagnostics. If the paginated records contain geographic data, validate the response shape and coordinate order with the GeoJSON and map data QA checklist.
Checklist by scenario
Scenario 1: A numbered results page
Use page-number or offset pagination when the product needs visible pages, a total count, or a simple “next” and “previous” flow. Define a maximum page size on the server and treat the requested size as a preference rather than an unlimited instruction.
- Choose a deterministic sort, such as
createdAtfollowed by a unique identifier. - Send the sort and filter parameters with every request, not only the first one.
- Keep the page size stable while the user navigates.
- Read the server’s total count or next-page indicator instead of calculating it locally.
- Reset the page to the first page when a search term or filter changes.
A page-number client can be small and explicit:
async function getPage(page, pageSize, signal) {
const params = new URLSearchParams({
page: String(page),
pageSize: String(pageSize),
sort: "createdAt:desc,id:desc"
});
const response = await fetch(`/api/orders?${params}`, { signal });
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
}This approach is convenient for administrative tables, but it can show a record twice or skip one if new records are inserted ahead of the current offset. If that matters, use a cursor or capture a server-side snapshot boundary.
Scenario 2: A continuously changing collection
Use cursor pagination when the API provides an opaque continuation token. The client should store the token exactly as received and send it back without decoding, sorting, or modifying it.
type Page<T> = {
items: T[];
nextCursor?: string | null;
};
async function fetchAllPages<T>(url: string, signal?: AbortSignal) {
const results: T[] = [];
const seen = new Set<string>();
let nextUrl: string | undefined = url;
while (nextUrl) {
const response = await fetch(nextUrl, { signal });
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
const page = await response.json() as Page<T>;
for (const item of page.items) {
const id = (item as { id?: string | number }).id;
const key = id === undefined ? JSON.stringify(item) : String(id);
if (!seen.has(key)) {
seen.add(key);
results.push(item);
}
}
nextUrl = page.nextCursor
? `${url.split("?")[0]}?cursor=${encodeURIComponent(page.nextCursor)}`
: undefined;
}
return results;
}In production code, build the next URL from the API’s documented link or use a URL object that preserves required filters. The example demonstrates the flow, but an API may return an absolute next URL, a cursor in a nested metadata object, or no cursor when the collection is exhausted.
Scenario 3: Keyset pagination for ordered records
Keyset pagination uses the last record’s sort key as the boundary for the next request. A single unique key is simplest:
GET /api/events?limit=50&afterId=1842If records are sorted by a non-unique field such as creation time, use a compound boundary. For descending order, the server might conceptually apply a condition such as (createdAt, id) < (lastCreatedAt, lastId). The exact query syntax belongs to the API, but the principle is important: every record needs an unambiguous position in the order.
- Sort by a stable field and a unique tie-breaker.
- Return the boundary values needed for the next request.
- Do not use a mutable display field as the only cursor.
- Confirm that the database can efficiently seek to the boundary.
Scenario 4: Infinite scroll in a browser
Infinite scroll should be an interaction layer over a reliable pagination method, not a replacement for one. Keep a visible loading state, prevent overlapping requests, expose a keyboard-accessible “Load more” control, and provide a way to reach the footer or continue without scrolling.
let loading = false;
let nextUrl = "/api/products?limit=24";
async function loadMore() {
if (loading || !nextUrl) return;
loading = true;
setLoadingState(true);
try {
const response = await fetch(nextUrl);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
const page = await response.json();
appendItems(page.items);
nextUrl = page.next ?? null;
} catch (error) {
showRetryControl(error);
} finally {
loading = false;
setLoadingState(false);
}
}An IntersectionObserver can trigger loadMore when a sentinel approaches the viewport, while the button remains available as a fallback. Abort an obsolete request when filters change, and clear the existing items before loading the new result set.
Scenario 5: Synchronizing records by time
For exports, audit logs, and incremental synchronization, request a bounded time window rather than repeatedly asking for “everything after now.” Include an overlap when the API or timestamp precision makes boundary behavior uncertain, then deduplicate by a stable record ID. Store the last successfully processed position only after the page has been handled and persisted.
What to double-check
Ordering and consistency
Pagination is only as stable as its ordering. A sort by name alone is not deterministic when many records share the same name. Add a unique tie-breaker and keep the sort direction consistent across every request. If the server cannot provide a stable view, design the client to tolerate changes rather than promising an exact snapshot.
Next-page semantics
Confirm whether an empty page means the collection is finished, a filter produced no matches, or the server temporarily returned no records. Prefer the documented continuation field. If the API supplies a next URL, treat it as authoritative; reconstructing it manually can lose authentication context, filters, or provider-specific parameters.
Deduplication identity
Deduplicate using a durable identifier whenever possible. Comparing serialized objects is fragile because field order, formatting, or harmless metadata can change. If the endpoint has no identifier, establish a documented composite key and understand the risk of false matches.
Retries and rate limits
Retry only failures that are likely to be temporary, and use bounded exponential backoff with jitter. Respect a server-provided retry delay when available. Avoid automatically repeating non-idempotent operations merely because a network request timed out. For GET pagination requests, a retry is usually easier to reason about, but the client should still guard against duplicate rendering.
Response validation
Check that the expected collection is actually an array and that pagination metadata has the expected type. A successful HTTP status does not guarantee a usable application response. Log the endpoint, cursor position, status, and request identifier where available, while excluding credentials and sensitive token contents. For authentication debugging, a JWT decoder guide can help inspect claims safely; decoding a token does not validate its signature or authorization.
API documentation
Document the page size limit, default ordering, cursor lifetime or scope if applicable, empty-page behavior, error format, and whether filters must remain unchanged while traversing pages. OpenAPI descriptions should make continuation fields and response envelopes clear enough for clients to generate reliable types.
Common mistakes
- Assuming page size equals returned item count. The final page is often shorter, and the server may cap the requested size.
- Stopping when a page is short. Some APIs return short pages even when more data exists. Follow the continuation signal instead.
- Dropping filters on the next request. A cursor must usually be used with the same filter and sort context that created it.
- Using an array index as identity. Insertions and deletions make indexes unsuitable for React keys, caching, or deduplication.
- Allowing concurrent page loads. Two responses can arrive out of order and corrupt the displayed sequence. Serialize requests or attach and verify a request generation.
- Retrying forever. Set a maximum retry count, surface a recovery action, and preserve already loaded records.
- Making infinite scroll the only navigation method. Provide a button, loading status, focus management, and an accessible route to additional results.
- Exposing sensitive cursors in logs. Treat opaque cursors as potentially sensitive and redact them where logs are broadly accessible.
When to revisit
Return to this checklist whenever a new endpoint, SDK, data-fetching library, or UI pattern changes how records are loaded. It is especially useful before seasonal planning cycles or high-volume periods, when a previously small collection may expose offset performance or consistency problems.
Before release, run deliberate tests for:
- Records inserted before the current offset.
- Records deleted between two page requests.
- Duplicate sort keys and identical timestamps.
- An empty first page and an empty page after a non-empty page.
- A missing, expired, or malformed cursor.
- Rate-limit responses and delayed retries.
- Two concurrent requests completing in reverse order.
- A filter change while a request is still pending.
- Network interruption after the server has accepted a request.
- A final page that contains fewer items than the requested limit.
Record the endpoint’s actual pagination contract in an integration note, add fixtures for each failure case, and verify the browser experience with keyboard navigation and a slow connection. When a provider changes its response envelope or SDK method names, update the adapter first so the rest of the application continues to use one stable interface. That small separation makes pagination easier to test, replace, and revisit.