Skip to main content
This dependency-free JavaScript example paginates an already loaded array. It is useful for learning the response contract or displaying a small local collection. It is not an efficient way to paginate a large database: do not load an entire table just to slice it.

A bounded function

The page size is capped and invalid numbers fail explicitly. Empty lists return empty data and no next page. A page beyond the end also returns empty data. Decide whether that behavior suits your interface and document it.

Parse at the boundary

HTTP query parameters arrive as strings. Validate an entire numeric value instead of using a parser that silently accepts trailing text. Translate invalid input into a clear client error; do not expose an internal stack trace. Keep a stable sort order before paginating so repeated reads have a predictable meaning.

When the data grows

For a database, apply filtering, authorization, ordering, and limits inside the query. Offset pagination is easy to understand but can become expensive or unstable as records change. Cursor pagination can help, provided the cursor represents a stable ordering with a tie-breaker. It does not eliminate authorization checks or guarantee a snapshot of changing data.

Verify behavior

Try an empty array, an exact page boundary, the final partial page, an excessive page number, and invalid sizes. Check that a request cannot ask for unlimited rows. The downloadable recipe module includes this function and runnable Node tests. Continue with API debugging and the starter collection.