Pagination Patterns in GraphQL
What you'll learn: How to efficiently slice and navigate large datasets in GraphQL using cursor-based and offset pagination with the connections pattern.
Why Pagination Matters in GraphQL
When a client requests a list of thousands of items, returning everything at once wastes bandwidth, slows responses, and overwhelms both server and client. Pagination breaks large datasets into manageable chunks, but GraphQL's flexible query structure demands patterns that work consistently across different data types.
Offset Pagination in GraphQL
The simplest approach mirrors traditional REST pagination. You pass limit and offset arguments:
query {
posts(limit: 10, offset: 20) {
id
title
}
}
This fetches 10 posts starting from position 20. However, offset pagination suffers when data changes between requests—adding or removing items shifts positions, causing duplicate or skipped results.
Cursor-Based Pagination
Cursors solve the instability problem. A cursor is an opaque identifier marking a position in the dataset (often an encoded ID or timestamp). Instead of numeric offsets, you request items after or before a cursor:
query {
posts(first: 10, after: "cursor123") {
id
title
}
}
The Connections Pattern
GraphQL's recommended pattern wraps results in a connection structure:
query {
posts(first: 10, after: "cursor123") {
edges {
cursor
node {
id
title
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
Each edge contains the actual item (node) plus its cursor. The pageInfo tells you whether more pages exist and provides the cursor to fetch the next batch. This standardizes pagination across your entire schema.
Key Takeaway: Use cursor-based pagination with the connections pattern in GraphQL to handle large datasets reliably, providing clients with stable, consistent navigation even when underlying data changes.