0
0
GraphQLquery~5 mins

Connection pattern (edges, nodes, pageInfo) in GraphQL

Choose your learning style9 modes available
Introduction

The connection pattern helps you get lists of items in small parts, making it easy to load and show data step-by-step.

When showing a list of friends on a social media app, but only a few at a time.
When loading search results page by page to avoid waiting for all results at once.
When displaying messages in a chat app, loading older messages as you scroll up.
When showing products in an online store with many items, loading more as the user scrolls.
When you want to know if there are more items to load after the current list.
Syntax
GraphQL
type Connection {
  edges: [Edge]
  nodes: [Node]
  pageInfo: PageInfo!
}

type Edge {
  cursor: String!
  node: Node
}

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

edges hold the items with cursors to track position.

nodes is a shortcut list of items without cursors.

Examples
This query gets the first 3 users with their cursors and info if more users exist.
GraphQL
query {
  users(first: 3) {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
This query fetches 5 posts using nodes and checks if there are previous pages.
GraphQL
query {
  posts(first: 5) {
    nodes {
      id
      title
    }
    pageInfo {
      hasPreviousPage
      startCursor
    }
  }
}
Sample Program

This query asks for the first 2 books, their ids and titles, and if there are more books after them.

GraphQL
query {
  books(first: 2) {
    edges {
      cursor
      node {
        id
        title
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
OutputSuccess
Important Notes

Use edges when you need the cursor for each item to load more data later.

pageInfo tells you if you can load more items before or after the current list.

nodes is simpler but does not give cursor info for pagination.

Summary

The connection pattern helps load lists in small parts for better performance.

It uses edges with cursors and pageInfo to manage pagination.

You can also use nodes for a simpler list without pagination details.