0
0
GraphqlHow-ToBeginner · 4 min read

How to Use Relay Specification in GraphQL: Syntax and Examples

To use the Relay specification in GraphQL, define your schema with Node interface and use Connection and Edge types for pagination. Implement cursor-based pagination with pageInfo and edges fields to efficiently fetch data in chunks.
📐

Syntax

The Relay specification uses a few key parts in your GraphQL schema:

  • Node Interface: A common interface with an id field for all objects.
  • Connection Type: Wraps a list of items and supports pagination.
  • Edge Type: Represents a single item in the connection with a cursor for pagination.
  • pageInfo: Provides info about pagination state like hasNextPage.
graphql
interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  name: String!
}

type UserEdge {
  cursor: String!
  node: User
}

type UserConnection {
  edges: [UserEdge]
  pageInfo: PageInfo!
}

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

Example

This example shows a query fetching users with Relay-style pagination using first and after arguments. It returns edges with cursors and pageInfo for navigation.

graphql
query GetUsers($first: Int, $after: String) {
  users(first: $first, after: $after) {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}

# Sample variables:
# {
#   "first": 2,
#   "after": "cursor123"
# }
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 when using Relay specification include:

  • Not implementing the Node interface with a global id.
  • Using offset-based pagination instead of cursor-based, which Relay requires.
  • Omitting pageInfo fields, which are essential for clients to know if more data exists.
  • Returning raw lists instead of Connection and Edge types.
graphql
type Query {
  # Wrong: returns a list without cursor info
  users: [User]

  # Right: returns a connection with edges and pageInfo
  users(first: Int, after: String): UserConnection
}
📊

Quick Reference

ConceptDescription
Node InterfaceDefines a global ID for all objects.
ConnectionWraps a list of edges for pagination.
EdgeContains a node and a cursor for pagination.
pageInfoProvides pagination state like hasNextPage.
CursorOpaque string used to paginate after a specific item.

Key Takeaways

Use the Node interface with a global id for all Relay objects.
Implement cursor-based pagination with Connection and Edge types.
Always include pageInfo to inform clients about pagination state.
Avoid offset-based pagination; Relay requires cursor-based.
Structure queries to return edges with cursors, not raw lists.