How to Use Edges and Nodes in GraphQL for Pagination
In GraphQL,
edges and nodes are used to structure paginated lists where edges contain metadata like cursors, and nodes hold the actual data items. This pattern helps implement efficient cursor-based pagination by separating data from pagination info.Syntax
The edges field is an array where each item contains a node (the actual data) and a cursor (a unique identifier for pagination). The pageInfo field provides info about the pagination state.
edges: List of edge objects.node: The data item inside each edge.cursor: A string used to paginate.pageInfo: ContainshasNextPage,hasPreviousPage,startCursor, andendCursor.
graphql
type Query { users(first: Int, after: String): UserConnection } type UserConnection { edges: [UserEdge] pageInfo: PageInfo } type UserEdge { node: User cursor: String! } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } type User { id: ID! name: String! }
Example
This example shows a GraphQL query requesting the first 2 users after a given cursor, returning edges with nodes and cursors, plus pageInfo for pagination control.
graphql
query {
users(first: 2, after: "cursor123") {
edges {
cursor
node {
id
name
}
}
pageInfo {
hasNextPage
endCursor
}
}
}Output
{
"data": {
"users": {
"edges": [
{
"cursor": "cursor124",
"node": { "id": "2", "name": "Alice" }
},
{
"cursor": "cursor125",
"node": { "id": "3", "name": "Bob" }
}
],
"pageInfo": {
"hasNextPage": true,
"endCursor": "cursor125"
}
}
}
}
Common Pitfalls
Common mistakes include:
- Returning
nodesdirectly withoutedges, losing pagination metadata. - Not providing a
cursorfor each edge, which breaks cursor-based pagination. - Ignoring
pageInfo, making it hard to know if more data exists.
Always include edges with cursor and node, plus pageInfo for a complete pagination response.
graphql
type UserConnection { # Wrong: nodes only, no cursor nodes: [User] } # Correct: type UserConnection { edges: [UserEdge] pageInfo: PageInfo }
Quick Reference
| Term | Description |
|---|---|
| edges | Array of objects containing a node and a cursor for pagination. |
| node | The actual data item inside an edge. |
| cursor | A unique string to identify the position in the list for pagination. |
| pageInfo | Object with pagination info: hasNextPage, hasPreviousPage, startCursor, endCursor. |
Key Takeaways
Use edges to wrap nodes with cursors for cursor-based pagination.
Always include pageInfo to inform clients about pagination state.
Each edge must have a cursor to enable efficient pagination.
Avoid returning nodes alone without edges and cursors.
Edges and nodes help separate data from pagination metadata clearly.