TExcelTAD
Home › GraphQL › Cursor Pagination & Connections

Cursor Pagination & Connections

Cursor pagination fixes the problems of offsets. Instead of "skip 20 items", the client says "give me 10 items after this one". The position marker is a cursor: an opaque string the server hands out with each item. New or deleted items elsewhere in the list don't affect where the next page starts.

The connection pattern

The most widely used convention is the Relay Connection specification. A paginated field returns a …Connection type:

graphql
type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
  totalCount: Int        # optional extra
}

type PostEdge {
  cursor: String!        # position of this node
  node: Post!            # the actual item
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

type Query {
  posts(first: Int, after: String, last: Int, before: String): PostConnection!
}

first/after page forward; last/before page backward. Edges exist so data about the relationship (a cursor, the date a friend was added, a role in a team) has a place next to the node.

Implementing it

Cursors should be opaque: clients must not build or parse them. A common trick is base64-encoding the sort key. Our posts are sorted by id, so the cursor encodes the id:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Post { id: ID!, title: String! }
  type PostEdge { cursor: String!, node: Post! }
  type PageInfo { hasNextPage: Boolean!, endCursor: String }
  type PostConnection { edges: [PostEdge!]!, pageInfo: PageInfo!, totalCount: Int! }
  type Query { posts(first: Int = 2, after: String): PostConnection! }
`);

const posts = [10, 11, 12, 13, 14].map((id) => ({ id, title: `Post ${id}` }));

const encode = (id) => btoa(`post:${id}`);
const decode = (cursor) => Number(atob(cursor).split(':')[1]);

const rootValue = {
  posts: ({ first, after }) => {
    const afterId = after ? decode(after) : -Infinity;
    const rest = posts.filter((p) => p.id > afterId);   // WHERE id > :afterId ORDER BY id
    const page = rest.slice(0, first);                  // LIMIT :first
    const edges = page.map((p) => ({ cursor: encode(p.id), node: p }));
    return {
      edges,
      totalCount: posts.length,
      pageInfo: { hasNextPage: rest.length > first, endCursor: edges.at(-1)?.cursor ?? null },
    };
  },
};

const query = `query Feed($after: String) {
  posts(first: 2, after: $after) {
    edges { cursor node { id title } }
    pageInfo { hasNextPage endCursor }
  }
}`;

let after = null;
let pageNumber = 1;
do {
  const result = await graphql({ schema, source: query, rootValue, variableValues: { after } });
  const { edges, pageInfo } = result.data.posts;
  console.log(`page ${pageNumber++}:`, edges.map((e) => `${e.node.title} [${e.cursor}]`).join(', '));
  after = pageInfo.hasNextPage ? pageInfo.endCursor : null;
} while (after);
page 1: Post 10 [cG9zdDoxMA==], Post 11 [cG9zdDoxMQ==]
page 2: Post 12 [cG9zdDoxMg==], Post 13 [cG9zdDoxMw==]
page 3: Post 14 [cG9zdDoxNA==]

The client loop is generic: request a page, read pageInfo.endCursor, repeat while hasNextPage is true. Infinite-scroll UIs do exactly this.

Stable under inserts

Let's replay the "new post while paging" scenario from the previous lesson, with a newest-first feed and cursors based on the id:

js · try it yourself
const feed = [5, 4, 3, 2, 1];                      // ids, newest first

const pageAfter = (cursorId, first = 2) => {
  const rest = cursorId === null ? feed : feed.filter((id) => id < cursorId);
  return rest.slice(0, first);
};

const page1 = pageAfter(null);
console.log('page 1:', page1);
feed.unshift(6);                                   // a new post arrives
console.log('page 2:', pageAfter(page1.at(-1)));   // after id 4
page 1: [ 5, 4 ]
page 2: [ 3, 2 ]

No duplicates: page 2 starts right after the last item the client saw, however the list changed in front of it.

Backward pagination with last and before

A chat window loads the latest messages first, then older ones as you scroll up. That's last: N, before: cursor:

js · try it yourself
const messages = ['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7'];

function paginate({ first, after, last, before }) {
  let start = 0;
  let end = messages.length;
  if (after) start = messages.indexOf(after) + 1;
  if (before) end = messages.indexOf(before);
  let slice = messages.slice(start, end);
  if (first != null) slice = slice.slice(0, first);
  if (last != null) slice = slice.slice(-last);
  return {
    nodes: slice,
    hasPreviousPage: last != null && messages.indexOf(slice[0]) > start,
    startCursor: slice[0],
  };
}

const newest = paginate({ last: 3 });
console.log(newest);
const older = paginate({ last: 3, before: newest.startCursor });
console.log(older);
{
  nodes: [ 'm5', 'm6', 'm7' ],
  hasPreviousPage: true,
  startCursor: 'm5'
}
{
  nodes: [ 'm2', 'm3', 'm4' ],
  hasPreviousPage: true,
  startCursor: 'm2'
}

To keep the example short, the cursors here are simply the message ids; in a real API you'd encode them.

Tips

  • Cursors are opaque. Base64 doesn't hide anything, but it signals "don't parse this", which lets you change the format later.
  • The cursor must encode the sort key. Sorting by createdAt needs createdAt (plus id as a tie-breaker) in the cursor.
  • Cap first/last just like limit.
  • totalCount can be expensive (COUNT(*) on a big table). Make it a separate field so only clients that select it pay for it.
  • Libraries such as graphql-relay (connectionFromArray, connectionDefinitions) generate these types for you.

Test yourself

In a Relay connection, where is the actual item stored?

  1. edges.cursor
  2. edges.node
  3. pageInfo.node
  4. items

How does the client fetch the next page?

  1. Increase an offset by the page size
  2. Pass pageInfo.endCursor as the after argument
  3. Pass the page number
  4. Re-run the same query

Why is cursor pagination stable when items are inserted at the top?

  1. Cursors are random
  2. The next page is defined relative to the last seen item, not to a position
  3. The server locks the table
  4. It isn't stable