The Bookshop has only three books, so { books { title } } is still fine. A real shop has thousands, and a customer's phone doesn't need all of them at once. Pagination fixes that: the list is fetched a little at a time, one page per request.
There are two ways to say "carry on from where". Offset: "skip the first 2 rows". Cursor: "carry on after book number 2". It's like reading a thick catalogue. An offset is remembering "I've read 2 lines", even though someone crossed out a line above. A cursor is a bookmark slipped in right after the last book you read.
Offset: easy, but it can shift
For this lesson the books field in the Bookshop schema gets two arguments: books(status: StockStatus, offset: Int = 0, limit: Int): [Book!]!. One page holds 2 books:
{
books(offset: 0, limit: 2) {
id
title
}
}
Page 1 answers books 1 and 2. Page 2 (offset: 2) answers book 3, Beauty Is a Wound. The trouble starts when the data changes between two requests:
| What happened | The table holds | Page 2 with offset: 2, limit: 2 |
|---|---|---|
| Nothing changed | 1, 2, 3 | Beauty Is a Wound |
| The Rainbow Troops deleted after page 1 loaded | 2, 3 | [], empty |
Page 2 is empty, so Beauty Is a Wound never shows on screen even though it's still in the shop. The opposite happens too: a new book arriving at the front of the list pushes everything along, and one book shows twice. Besides, offset: 100000 still makes the database read and throw away 100,000 rows.
Cursor: carry on after the last item
With a cursor, the client doesn't say "skip 2", it says "after book number 2". Once The Rainbow Troops is deleted, the book with an id greater than 2 is still Beauty Is a Wound. Nothing skipped, nothing doubled.
Connections: the standard shape from Relay
The GraphQL specification itself says nothing about pagination. The shape in wide use, and the one graphql.org's pagination page describes, comes from Relay's GraphQL Cursor Connections Specification. GitHub and Shopify use it. The Bookshop schema gets this field:
type Query {
# ...the fields it already has
booksConnection(first: Int = 10, after: String): BookConnection!
}
type BookConnection {
edges: [BookEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type BookEdge {
cursor: String!
node: Book!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
- A connection (
BookConnection) is one page:edgesandpageInfo. - An edge wraps one item:
nodeis the book,cursoris its position in the list. - PageInfo:
hasNextPagesays there's another page,endCursoris the cursor of this page's last item.startCursorandendCursorarenullwhen the page is empty. firstandaftermove forward: "takefirstitems after the cursorafter". To move back, the specification useslastandbefore.totalCountisn't part of the specification, but it's often added.
One page of 2 books
query BookPage($first: Int, $after: String) {
booksConnection(first: $first, after: $after) {
edges {
cursor
node {
id
title
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}
Variables { "first": 2 }:
{
"data": {
"booksConnection": {
"edges": [
{ "cursor": "Ym9vazox", "node": { "id": "1", "title": "The Rainbow Troops" } },
{ "cursor": "Ym9vazoy", "node": { "id": "2", "title": "This Earth of Mankind" } }
],
"pageInfo": { "hasNextPage": true, "endCursor": "Ym9vazoy" },
"totalCount": 3
}
}
}
hasNextPage is true, so the client sends the same query with { "first": 2, "after": "Ym9vazoy" }, the endCursor from before. The answer is one edge, Beauty Is a Wound with the cursor "Ym9vazoz", and hasNextPage: false. The client stops there. The query text is the same for every page; only the variables change.
Opaque cursors: base64 of what?
"Ym9vazoy" is the base64 of the text "book:2". In JavaScript, btoa("book:2") gives "Ym9vazoy", and atob("Ym9vazoy") turns it back. Opaque means the client must not read or build a cursor itself. It just hands endCursor back as it is. The reason: the server is free to change what's inside, say to a price plus an id for an order by price, without breaking the apps already out there.
Base64 isn't encryption: anyone can open it, so never keep secrets in a cursor, and the server must check it. A random cursor like "abc" gets Invalid cursor, and because booksConnection is typed BookConnection!, the whole of data becomes null. Watch out for libraries too: graphql-relay's connectionFromArray makes its cursors from the base64 of "arrayconnection:" plus an offset, so it still has the shifting problem above.
The order must be stable
The cursor book:2 means "after id 2" only when the list is ordered by id, a unique column. This is the resolver on the Bookshop server:
booksConnection: (_, { first, after }) => {
const sorted = [...books].sort((a, b) => a.id - b.id);
const afterId = after == null ? 0 : fromCursor(after); // "Ym9vazoy" → 2
const rest = sorted.filter((b) => b.id > afterId);
const edges = rest.slice(0, first).map((book) => ({ cursor: toCursor(book.id), node: book }));
return {
edges,
pageInfo: {
hasNextPage: rest.length > first,
hasPreviousPage: rest.length < sorted.length,
startCursor: edges.length > 0 ? edges[0].cursor : null,
endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : null,
},
totalCount: books.length,
};
},
fromCursoropens the base64 and takes the number afterbook:;toCursor(id)does the reverse.rest.length > firstchecks whether anything is left after this page.- In a real database it looks like
WHERE id > 2 ORDER BY id LIMIT 3: take one more thanfirst, and if that third row exists,hasNextPageistrue.
When ordering by a column that can repeat, like the price, add the id as a second sort key and keep both in the cursor. Without it, two books with the same price can be skipped or shown twice.
⚠️ Pages with gaps, repeats, or no size limit
- Offsets for data that keeps changing. A feed, a chat, a catalogue with items added and removed all the time: items get skipped or doubled. Use a cursor.
- The client building cursors itself.
btoa("book:5")on the client breaks the moment the server changes what a cursor holds. SendendCursorback as it is. - Ordering by a column that isn't unique. Add the id as a second sort key.
firstwith no limit.first: 1000000is the same as no pagination at all. Cap it on the server, at 100 for instance.
TL;DR: Pagination fetches a list page by page. An offset (offset, limit) is easy and can jump to any page, but it shifts when the data changes: after The Rainbow Troops is deleted, page 2 with offset 2 is empty and Beauty Is a Wound is skipped. A cursor says "after this item", so it stays right. The standard shape is the connection from Relay's GraphQL Cursor Connections Specification (not from the GraphQL specification): edges holding node and cursor, pageInfo holding hasNextPage and endCursor, forward with first and after, back with last and before. A cursor is opaque: in the Bookshop it's the base64 of "book:2", and the client just hands endCursor back as it is. The order must be stable, on a unique column.
⚡ An offset can shift
Guess first: page 1 (books 1 and 2) has loaded, then The Rainbow Troops is deleted. What does page 2 with offset: 2, limit: 2 hold?
Nothing, []. The table only holds books 2 and 3 now, so skipping 2 rows leaves nothing. Beauty Is a Wound never shows, even though it's still in the shop.
Meaning: A cursor says "after book number 2", not "skip 2 rows". Once The Rainbow Troops is deleted, the book with an id greater than 2 is still Beauty Is a Wound.
⚡ Connections: forward with first and after
Write:
query BookPage($first: Int, $after: String) {
booksConnection(first: $first, after: $after) {
edges {
cursor
node {
id
title
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
Meaning: first and after mean "take first items after the cursor after". While hasNextPage is still true, send the same query with the last endCursor as after. Only the variables change.
⚡ A cursor is opaque
Meaning: "Ym9vazoy" is just the base64 of "book:2", but the client must not read or build one itself: hand endCursor back as it is. The order must be stable too, on a unique column like the id.