0
0
GraphqlConceptBeginner · 3 min read

Cursor Pagination in GraphQL: What It Is and How It Works

Cursor pagination in GraphQL is a method to fetch data in chunks using a 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.

graphql
query GetUsers($after: String) {
  users(first: 2, after: $after) {
    edges {
      node {
        id
        name
      }
      cursor
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
Output
{ "data": { "users": { "edges": [ {"node": {"id": "1", "name": "Alice"}, "cursor": "cursor1"}, {"node": {"id": "2", "name": "Bob"}, "cursor": "cursor2"} ], "pageInfo": { "endCursor": "cursor2", "hasNextPage": true } } } }
🎯

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 edges with node data and cursor for each item.
  • pageInfo tells if more data is available and provides the cursor for the next page.

Key Takeaways

Cursor pagination uses a unique cursor to mark the position in a list for fetching data.
It handles data changes better than simple page numbers or offsets.
GraphQL returns edges with nodes and cursors to enable smooth pagination.
Use cursor pagination for large or frequently changing datasets to improve performance and user experience.