Cursor Pagination in GraphQL: What It Is and How It Works
cursor that marks a specific position in a list. It allows clients to request the next set of items after a given cursor, making pagination efficient and reliable even when data changes.How It Works
Cursor pagination works like a bookmark in a book. Imagine you are reading a long list of items, but you only want to see a few at a time. Instead of counting pages, you use a bookmark (the cursor) to remember where you left off. When you want more items, you tell the server to start from that bookmark.
In GraphQL, each item in a list has a unique cursor that points to its position. When you request data, you get a set of items plus the cursor of the last item. To get the next set, you send that cursor back to the server, which returns the following items. This method is more reliable than simple page numbers because it handles data changes gracefully.
Example
This example shows a GraphQL query using cursor pagination to fetch a list of users in chunks of 2.
query GetUsers($after: String) {
users(first: 2, after: $after) {
edges {
node {
id
name
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}When to Use
Use cursor pagination when you need to load large lists of data efficiently and want to avoid problems caused by data changing between requests. It is ideal for social media feeds, product catalogs, or any list where items can be added or removed frequently.
This method improves user experience by providing smooth scrolling or loading more items on demand without skipping or repeating entries.
Key Points
- Cursor pagination uses a unique marker (
cursor) to track position in a list. - It is more reliable than offset-based pagination when data changes.
- GraphQL returns
edgeswithnodedata andcursorfor each item. pageInfotells if more data is available and provides the cursor for the next page.