Skip to content

Fragments in GraphQL

Fragments in GraphQL allow you to reuse parts of queries across multiple operations or within complex nested queries. This helps avoid repetition and keeps your queries clean and maintainable.


Why Use Fragments?

  • Reusability: Avoid duplicating field selections.
  • Maintainability: Make updates in one place rather than multiple queries.
  • Readability: Separate complex logic into understandable blocks.

Basic Syntax

fragment UserFields on User {
  id
  name
  email
}

You can then use this fragment in any query or mutation where the User type appears:

query GetUsers {
  users {
    ...UserFields
  }
}

fragment UserFields on User {
  id
  name
  email
}

Example Use Case

Assume you often query the same fields of a Post:

fragment PostFields on Post {
  id
  title
  content
  author {
    name
  }
}

query GetRecentPosts {
  recentPosts {
    ...PostFields
  }
}

query GetPopularPosts {
  popularPosts {
    ...PostFields
  }
}

Nested Fragments

Fragments can also contain other fragments:

fragment AuthorFields on Author {
  id
  name
}

fragment PostFields on Post {
  id
  title
  author {
    ...AuthorFields
  }
}

query GetPosts {
  posts {
    ...PostFields
  }
}

Limitations

  • Fragments must be defined on a specific type.
  • You cannot use fragments across incompatible types.
  • Circular fragment references will cause errors.

Best Practices

  • Name fragments clearly based on the data they return.
  • Group fragment definitions logically in your codebase or documentation.
  • Avoid fragment overuse — use them when they bring real benefit to code clarity or reuse.

Resources