0
0
GraphQLquery~5 mins

Cursor-based pagination in GraphQL

Choose your learning style9 modes available
Introduction

Cursor-based pagination helps you get small parts of a big list step by step. It is faster and avoids missing or repeating items when the list changes.

Showing posts on a social media feed little by little as you scroll.
Loading search results page by page without skipping or repeating items.
Displaying messages in a chat app where new messages arrive often.
Browsing a large product catalog in an online store smoothly.
Fetching user comments on an article in small chunks.
Syntax
GraphQL
query GetItems($first: Int, $after: String) {
  items(first: $first, after: $after) {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}

$first tells how many items to get.

$after is the cursor pointing to where to start fetching next items.

Examples
Get the first 5 items from the list.
GraphQL
query {
  items(first: 5) {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
Get 5 items after the cursor "YXJyYXljb25uZWN0aW9uOjQ=" (which points to the 5th item).
GraphQL
query {
  items(first: 5, after: "YXJyYXljb25uZWN0aW9uOjQ=") {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
Sample Program

This query fetches the first 2 items from the list with their cursors and info if more items exist.

GraphQL
query GetFirstTwoItems {
  items(first: 2) {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      endCursor
      hasNextPage
    }
  }
}
OutputSuccess
Important Notes

Cursor values are usually encoded strings that point to a specific item position.

Cursor-based pagination is better than offset pagination when data changes often.

Always check hasNextPage to know if more items can be fetched.

Summary

Cursor-based pagination fetches data in small parts using a cursor to mark position.

It helps avoid missing or repeating items when the list changes.

Use first and after arguments to control pagination.