How to Use pageInfo in GraphQL for Pagination
In GraphQL,
pageInfo is used to provide information about pagination such as whether there are more pages available and cursors for navigation. It is typically included in connection types to help clients fetch data page by page efficiently.Syntax
The pageInfo object usually contains these fields:
hasNextPage: Boolean indicating if more pages exist after the current one.hasPreviousPage: Boolean indicating if pages exist before the current one.startCursor: Cursor string for the first item in the current page.endCursor: Cursor string for the last item in the current page.
This object is part of a connection type that wraps a list of edges (items with cursors).
graphql
type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } type Edge { cursor: String! node: ItemType! } type Connection { edges: [Edge!]! pageInfo: PageInfo! }
Example
This example shows a GraphQL query requesting a paginated list of users with pageInfo to navigate pages.
graphql
query GetUsers($first: Int, $after: String) {
users(first: $first, after: $after) {
edges {
cursor
node {
id
name
}
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
}Output
{
"data": {
"users": {
"edges": [
{
"cursor": "cursor1",
"node": { "id": "1", "name": "Alice" }
},
{
"cursor": "cursor2",
"node": { "id": "2", "name": "Bob" }
}
],
"pageInfo": {
"hasNextPage": true,
"hasPreviousPage": false,
"startCursor": "cursor1",
"endCursor": "cursor2"
}
}
}
}
Common Pitfalls
Common mistakes when using pageInfo include:
- Not returning
pageInfoin the query, so clients can't know if more pages exist. - Incorrectly setting
hasNextPageorhasPreviousPage, causing infinite or missing pagination. - Not using cursors properly, which breaks cursor-based pagination.
Always ensure your resolver returns accurate pageInfo data matching the current page.
graphql
Wrong example:
{
users {
edges {
node {
id
}
}
# Missing pageInfo
}
}
Right example:
{
users {
edges {
node {
id
}
}
pageInfo {
hasNextPage
endCursor
}
}
}Quick Reference
| Field | Description | Type |
|---|---|---|
| hasNextPage | True if more pages exist after current | Boolean! |
| hasPreviousPage | True if pages exist before current | Boolean! |
| startCursor | Cursor for first item on current page | String |
| endCursor | Cursor for last item on current page | String |
Key Takeaways
Use
pageInfo to provide pagination state like next/previous page availability.Always include
pageInfo in your connection queries for effective cursor-based pagination.Ensure your server resolvers return accurate
pageInfo fields to avoid pagination errors.Use cursors from
startCursor and endCursor to fetch next or previous pages.Missing or incorrect
pageInfo leads to broken or infinite pagination loops.