Relay connections

Intermediate · 6 min

The Relay connection pattern: a connection type with edges, a cursor per edge and pageInfo, with a working Yoga resolver over ten posts.

Before thisPagination: offset and cursorObject types and fields

StepZen, an IBM Company · 6 min

Relay connections

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by StepZen, an IBM CompanyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A connection is a standard shape for a paginated list: a `Connection` type with `edges` and `pageInfo`, where each `Edge` has a `cursor` and a `node`.
  • The arguments are `first` and `after` for forward paging, and `last` and `before` for backward; the client takes `pageInfo.endCursor` from one page and passes it as `after` for the next.
  • `pageInfo.hasNextPage` tells the client whether to continue; fetch `first + 1` rows and drop the extra to compute it without a count.
  • The edge exists so data about the relationship, such as the cursor or a role, has somewhere to live separate from the node.
  • You do not need Relay the client to use the pattern; Apollo Client, urql and generated code all understand it, but it adds verbosity for simple lists.

The problem: every team invents its own cursor shape

The last lesson gave you cursor pagination. It left the schema shape open: one team returns { items, nextCursor }, another { results, hasMore, token }. Clients and tools cannot treat those uniformly, so every list needs bespoke code to page through it.

Facebook’s Relay client needed one predictable shape so it could paginate any list automatically. It published the Cursor Connections Specification, and the shape became the standard for GraphQL pagination, whether or not you use Relay.

The shape

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

type PostEdge {
  cursor: String!
  node: Post!
}

type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type Query {
  posts(first: Int = 3, after: String): PostConnection!
}

Four types look like a lot for a list. Each answers a question:

  • The connection is the page: its edges and its pageInfo.
  • The edge is one entry, a node plus the cursor that points at it.
  • The node is your real object, Post.
  • PageInfo says whether there is more and gives the cursors to continue with.

Think of a book with a bookmark on every page. The page is the node, the bookmark is the cursor, and the edge is the page with its bookmark clipped on. The connection is the stack you were handed this time.

totalCount is not in the spec. It is a common extra, and it costs a COUNT(*), so offer it only if clients need it.

The resolver

I built this on Yoga 6.1.0 and SQLite with ten posts and ran it. Cursors are base64 of post:<id>, opaque to the client; ordering is by id descending:

const encodeCursor = (id) => Buffer.from(`post:${id}`).toString('base64url');
const decodeCursor = (c) => Number(Buffer.from(c, 'base64url').toString().split(':')[1]);

Query: {
  posts: (_, { first, after }, { db }) => {
    if (first < 0 || first > 50) throw new GraphQLError('first must be between 0 and 50');
    const start = after ? decodeCursor(after) : Number.MAX_SAFE_INTEGER;
    const rows = db
      .prepare('SELECT * FROM posts WHERE id < ? ORDER BY id DESC LIMIT ?')
      .all(start, first + 1);                          // one extra row
    const edges = rows.slice(0, first).map((row) => ({
      cursor: encodeCursor(row.id),
      node: row,
    }));
    return {
      edges,
      totalCount: db.prepare('SELECT COUNT(*) AS c FROM posts').get().c,
      pageInfo: {
        hasNextPage: rows.length > first,              // the extra row proves it
        hasPreviousPage: false,
        startCursor: edges[0]?.cursor ?? null,
        endCursor: edges.at(-1)?.cursor ?? null,
      },
    };
  },
},

The first + 1 trick is the heart of it. Ask for one more row than the page needs. If you get it, a next page exists; throw the extra away. No count query needed.

Walking the pages

The client query:

query Posts($after: String) {
  posts(first: 3, after: $after) {
    pageInfo { hasNextPage endCursor }
    edges { cursor node { id title } }
  }
}

First call, after: null. Then each call takes endCursor from the last response. I looped until hasNextPage was false:

page 1: Post 10, Post 9, Post 8   hasNextPage: true   endCursor: cG9zdDo4
page 2: Post 7, Post 6, Post 5    hasNextPage: true   endCursor: cG9zdDo1
page 3: Post 4, Post 3, Post 2    hasNextPage: true   endCursor: cG9zdDoy
page 4: Post 1                    hasNextPage: false

Every post, once. With first: 500 the resolver threw its GraphQLError and the response was data: null with the message first must be between 0 and 50, because posts is non-null. With first: 0 the response had empty edges, startCursor: null, and hasNextPage: true.

The backward half

The spec also defines last and before for paging in reverse. I implemented only forward paging here. A server that does only forward paging may return hasPreviousPage: false, as above; the spec allows that when computing it would be costly. If your UI needs “load older messages” scrolling backward, implement the other pair, with the comparison and sort order flipped, and then fix the order of the edges.

Why this shape wins

The shape is verbose by design. Its payoff is tooling: a client that knows the pattern can append pages to a cached list for you, and code generators can type the result. Relay’s @connection directive and Apollo Client’s relayStylePagination helper rely on it. See the Apollo cache for how a client merges pages.

It costs a nesting level in every query: posts { edges { node { title } } }, which people either accept or hide behind a shorthand such as a nodes field alongside edges. If a list is small and bounded, a plain [Post!]! is simpler and fine. Reach for connections when the list can grow.

You can also use the shape without ever touching Relay the client. The pattern is just a convention about types, and any GraphQL client can send those queries.

What the video covers

StepZen’s six-minute “Cursor Pagination For GraphQL APIs Explained” is from November 2022. Its description says pagination in GraphQL is not that different from pagination in REST once you understand edges and nodes, that the presenter demonstrates cursor-based pagination and the edges and nodes concept, and that GraphQL recommends cursor-based pagination. The channel belongs to a vendor and the description pitches StepZen for REST APIs without cursor support, so skip that part. I could not read a transcript, and the video does not show a Yoga resolver, which is why the code above is this lesson’s own.

Where this fits

Connections page through a list of things you already know how to find. A related problem is how a client finds one thing by an id that works across types. Next: global object identification.

Check yourself

  1. 01What are the four types in the connection pattern for posts?

    `PostConnection` with `edges` and `pageInfo`, `PostEdge` with `cursor` and `node`, `Post` as the node, and `PageInfo` with `hasNextPage`, `hasPreviousPage`, `startCursor` and `endCursor`.

  2. 02How does the resolver know whether another page exists without counting all rows?

    It queries `first + 1` rows. If it gets more than `first`, there is another page; it returns only `first` of them.

  3. 03Where does the client get the cursor to send as `after`?

    From `pageInfo.endCursor` of the page it just received, or from the `cursor` of the last edge.

  4. 04Why have an edge at all, rather than a list of nodes with a cursor field on each node?

    The cursor and any relationship data belong to the link between the parent and the node, not to the node itself. The same node can appear in different connections with different cursors.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark