Ctrl + K
GraphQL14 min read

GraphQL Fragments Explained

A practical guide to GraphQL fragments covering reusable field selections, named and inline fragments, fragments on interfaces and unions, variables, nesting, and best practices.

Published: 2026-10-05

GraphQL fragments are reusable selections of fields that can be included in queries, mutations, and other GraphQL operations. They help prevent repeated field selections and make large operations easier to organize.

Fragments become particularly useful when the same fields are needed in multiple places or when an application works with interfaces and unions that can return different object types.

This guide explains named fragments, inline fragments, fragment type conditions, nested fragments, variables, fragments on interfaces and unions, fragment reuse in mutations, common errors, and practical best practices.

What Is a GraphQL Fragment?

A GraphQL fragment is a reusable set of fields defined for a particular GraphQL object, interface, or union type. Instead of writing the same selection set repeatedly, a client can define it once and spread the fragment wherever it is needed.

fragment UserFields on User {
  id
  name
  email
}

The fragment is named UserFields and has a type condition of User. It contains the fields that should be selected whenever the fragment is used.

Why Use GraphQL Fragments?

Without fragments, the same fields may need to be repeated throughout a large GraphQL operation.

query {
  user(id: "1") {
    id
    name
    email
  }

  administrator(id: "2") {
    id
    name
    email
  }
}

If the same fields are required in many places, a fragment can centralize that selection.

fragment UserFields on User {
  id
  name
  email
}

query {
  user(id: "1") {
    ...UserFields
  }

  administrator(id: "2") {
    ...UserFields
  }
}
  • Reuse common field selections.
  • Reduce duplicated GraphQL operation code.
  • Keep large queries and mutations easier to read.
  • Centralize commonly requested fields.
  • Make nested selections easier to organize.
  • Handle interfaces and unions with type-specific selections.

GraphQL Fragment Syntax

A named fragment uses the fragment keyword, a fragment name, the on keyword, and a type condition.

fragment ProductFields on Product {
  id
  name
  price
}

The fragment name is ProductFields, and the type condition is Product. The fields inside the fragment must be valid for the specified type.

Using the Fragment Spread Operator

A fragment is included in an operation with the spread syntax: three dots followed by the fragment name.

fragment ProductFields on Product {
  id
  name
  price
}

query {
  product(id: "42") {
    ...ProductFields
  }
}

The ...ProductFields expression tells GraphQL to include the fields defined by the fragment at that location.

Fragments Can Be Used in Queries

Queries are one of the most common places to use fragments. A fragment can be reused across multiple selections of compatible types.

fragment ProductSummary on Product {
  id
  name
  price
}

query {
  featuredProducts {
    ...ProductSummary
  }

  latestProducts {
    ...ProductSummary
  }
}

Both selections reuse the same ProductSummary fragment. The server executes the resulting selection according to the GraphQL operation, while the client avoids duplicating the field list.

Fragments Can Be Used in Mutations

Fragments are not limited to queries. They can also be used to select fields returned by mutation payloads or mutation result objects.

fragment UserFields on User {
  id
  name
  email
}

mutation {
  updateUser(
    id: "42"
    name: "Anna"
  ) {
    ...UserFields
  }
}

The fragment controls which User fields are requested from the mutation result.

Fragments on Nested Objects

Fragments can be used inside nested selections as long as the fragment's type condition is compatible with the object at that location.

fragment AuthorFields on User {
  id
  name
}

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

query {
  posts {
    ...PostFields
  }
}

Here, PostFields selects fields from Post and then uses AuthorFields for the nested User object returned by author.

Nested GraphQL Fragments

A fragment can spread another fragment. This allows large selections to be composed from smaller reusable pieces.

fragment UserBasic on User {
  id
  name
}

fragment UserContact on User {
  email
}

fragment UserProfile on User {
  ...UserBasic
  ...UserContact
  avatarUrl
}

query {
  user(id: "42") {
    ...UserProfile
  }
}

UserProfile combines UserBasic and UserContact with its own avatarUrl field. This composition approach can be useful when different parts of an application need overlapping groups of fields.

Inline Fragments

An inline fragment is a fragment written directly inside a selection set instead of being declared separately with a fragment definition. Inline fragments are particularly useful for interfaces and unions.

query {
  search {
    __typename

    ... on User {
      id
      name
    }

    ... on Product {
      id
      name
      price
    }
  }
}

The ... on User and ... on Product selections apply only when the returned object has the corresponding concrete type.

Named Fragments vs Inline Fragments

FeatureNamed FragmentInline Fragment
Declared separatelyYesNo
ReusableYesNo
Requires fragment nameYesNo
Can specify a type conditionYesYes
Useful with interfaces and unionsYesYes

Use named fragments when a selection needs to be reused or organized independently. Inline fragments are convenient when a type-specific selection is needed only at one location.

Fragments on Interfaces

Interfaces define common fields that can be implemented by multiple object types. A fragment can target an interface to select fields shared by its implementations.

interface Node {
  id: ID!
}

fragment NodeFields on Node {
  id
}

query {
  nodes {
    ...NodeFields
  }
}

A fragment on an interface can be useful when the application needs fields common to all compatible implementations.

Fragments on Unions

Union types can represent one of several object types. Since a union does not itself define a shared field set in the same way an interface does, clients commonly use inline or named fragments for each concrete member type.

union SearchResult = User | Product

fragment UserResult on User {
  id
  name
}

fragment ProductResult on Product {
  id
  name
  price
}

query Search($term: String!) {
  search(term: $term) {
    __typename

    ...UserResult
    ...ProductResult
  }
}

The UserResult fragment applies to User objects and ProductResult applies to Product objects. GraphQL validates whether each fragment can apply to the location where it is spread.

Using __typename with Fragments

The __typename meta-field returns the concrete GraphQL object type of the current result. It is particularly useful when fragments are used with interfaces and unions.

query {
  search {
    __typename

    ... on User {
      id
      name
    }

    ... on Product {
      id
      name
      price
    }
  }
}

A response might contain values such as User or Product in the __typename field, allowing client code to distinguish between different result types.

Fragments and Variables

Fragments themselves do not define operation variables, but fragment selections can contain fields that use directives whose arguments come from variables declared by the operation.

fragment UserFields on User {
  id
  name
  email @include(if: $includeEmail)
}

query GetUser(
  $id: ID!
  $includeEmail: Boolean!
) {
  user(id: $id) {
    ...UserFields
  }
}

The variable belongs to the operation. The fragment uses that variable through the @include directive, and the operation must provide a compatible variable definition.

Fragment Type Conditions

The type condition determines where a fragment can be used. For example, a fragment defined on User can be spread at locations where User is a valid possible type.

fragment UserFields on User {
  id
  name
}

The server schema determines which types are compatible. A fragment cannot arbitrarily select fields from an unrelated type.

query {
  product(id: "42") {
    ...UserFields
  }
}

If Product and User are unrelated types in the schema, this fragment spread is invalid because the UserFields type condition cannot apply to Product.

Fragment Field Validation

Fields inside a fragment must be valid for the fragment's type condition.

fragment UserFields on User {
  id
  name
  price
}

If User does not define a price field, the fragment is invalid. GraphQL-aware development tools can detect this from the schema.

Fragment Name Rules

Fragment names identify reusable fragment definitions and must follow GraphQL naming rules. They should also be unique within the relevant GraphQL document.

fragment UserSummary on User {
  id
  name
}

Names such as UserSummary, ProductCard, and OrderDetails make the intended purpose easier to understand than generic names such as Data or Fields.

Fragment Composition

Fragments can be composed into larger selections. This is useful when different parts of an application have reusable data requirements.

fragment ProductIdentity on Product {
  id
  name
}

fragment ProductPricing on Product {
  price
  currency
}

fragment ProductCard on Product {
  ...ProductIdentity
  ...ProductPricing
  imageUrl
}

query {
  products {
    ...ProductCard
  }
}

This structure separates product identity, pricing, and presentation-related fields into smaller fragments and then combines them into ProductCard.

Fragments and GraphQL Client Caches

GraphQL clients can use fragments as a way to describe the fields required by a component or part of an application. Some GraphQL client libraries also provide fragment-related APIs for interacting with normalized caches.

The exact cache behavior depends on the client library. A fragment does not automatically change how data is cached; it primarily defines a reusable GraphQL selection. Client-specific fragment APIs may add additional cache functionality.

Component-Based GraphQL Fragments

Fragments can fit naturally into component-based frontend applications. A component can define the fields it needs and a larger query can compose those fragments into a complete operation.

fragment UserCard on User {
  id
  name
  avatarUrl
}

fragment UserDetails on User {
  id
  name
  email
  createdAt
}

query {
  user(id: "42") {
    ...UserCard
    ...UserDetails
  }
}

This pattern can make component data requirements more explicit. The exact fragment organization depends on the application's GraphQL tooling and architecture.

Fragments in Large GraphQL Operations

Large GraphQL applications can contain many reusable fragments. Organizing them around domain entities or UI components can reduce duplication, but excessive fragmentation can also make an operation harder to follow.

  • Use descriptive fragment names.
  • Keep fragments focused on a coherent set of fields.
  • Compose smaller fragments when that improves reuse.
  • Avoid creating fragments for every tiny field selection.
  • Keep fragment type conditions accurate.
  • Remove unused fragments.
  • Use formatting consistently.
  • Keep component-specific fragments close to their relevant application code when the project structure supports it.

Unused GraphQL Fragments

A fragment that is declared but never referenced adds unnecessary complexity to the operation document. Depending on the GraphQL validation rules and document structure, unused fragments can cause validation errors.

fragment UserFields on User {
  id
  name
}

query {
  product(id: "42") {
    id
    name
  }
}

UserFields is not used by the query. Removing unused fragment definitions keeps the operation smaller and avoids validation issues.

Cyclic Fragment References

Fragments should not form circular references. For example, if FragmentA spreads FragmentB and FragmentB eventually spreads FragmentA, the operation contains a fragment cycle.

fragment FragmentA on User {
  id
  ...FragmentB
}

fragment FragmentB on User {
  name
  ...FragmentA
}

Such a cycle is invalid. GraphQL validation rules prevent fragment cycles because they could create an endlessly expanding selection.

Fragments vs Repeating Fields

ApproachAdvantageTrade-off
Repeat fieldsSimple for small operationsDuplicates selections
Named fragmentReusable and organizedAdds a separate definition
Inline fragmentConvenient for type-specific fieldsNot reusable

For a small operation, repeating a few fields may be clearer. Fragments become more valuable when the same selection appears repeatedly or when the schema contains interfaces and unions.

Common GraphQL Fragment Mistakes

  • Using a fragment on a type that is incompatible with the current selection.
  • Requesting fields that do not exist on the fragment's type condition.
  • Declaring a fragment but never using it.
  • Creating circular fragment references.
  • Using duplicate fragment names in the same document.
  • Creating too many tiny fragments that make operations difficult to follow.
  • Forgetting to include a fragment definition when sending a standalone operation.
  • Assuming a fragment automatically changes client cache behavior.
  • Using inline fragments when a reusable named fragment would be clearer.
  • Ignoring schema changes that make existing fragment fields invalid.

How to Debug GraphQL Fragment Errors

When a GraphQL operation involving fragments fails validation, inspect the fragment definitions and their spread locations separately.

  • Check that every fragment has a valid type condition.
  • Verify that every field exists on the fragment type.
  • Check that the fragment is used at a compatible location.
  • Look for duplicate fragment names.
  • Check for circular fragment references.
  • Remove unused fragments.
  • Make sure all referenced fragment definitions are included in the request document.
  • Verify variables used through directives are declared by the operation.
  • Inspect the GraphQL server's validation errors.
  • Compare the fragment against the current schema if the API has changed.

A Complete GraphQL Fragment Example

The following example combines reusable fragments, nested fragments, a variable, and a query returning related objects.

fragment UserSummary on User {
  id
  name
  avatarUrl
}

fragment ProductSummary on Product {
  id
  name
  price
}

fragment OrderItemFields on OrderItem {
  id
  quantity
  product {
    ...ProductSummary
  }
}

fragment OrderDetails on Order {
  id
  status
  customer {
    ...UserSummary
  }
  items {
    ...OrderItemFields
  }
}

query GetOrder($id: ID!) {
  order(id: $id) {
    ...OrderDetails
  }
}
{
  "id": "100"
}

The query itself remains relatively small because the detailed selections are composed through fragments. This approach becomes increasingly useful as related objects contain larger selections.

Best Practices for GraphQL Fragments

  • Give fragments descriptive names based on their purpose.
  • Use fragments to remove meaningful duplication rather than splitting every selection into a fragment.
  • Keep each fragment focused on one logical data requirement.
  • Use type-specific fragments when working with interfaces and unions.
  • Compose fragments when several reusable selections naturally belong together.
  • Avoid fragment cycles.
  • Remove unused fragments.
  • Keep fragment definitions synchronized with the schema.
  • Use a consistent naming convention across the project.
  • Format large operations so fragment spreads and nested selections are easy to read.
  • Use schema-aware validation during development.
  • Review fragment dependencies when changing or removing fields from the schema.
💡 A useful rule is to create a fragment when a group of fields represents a reusable data requirement. If a fragment exists only to wrap one or two fields that are never reused, it may add more complexity than value.

Frequently Asked Questions

What is a GraphQL fragment?

A GraphQL fragment is a reusable selection of fields defined for a specific object, interface, or union type. It can be spread into compatible selections in queries, mutations, and other operations.

How do you use a GraphQL fragment?

Define a fragment with the fragment keyword and then include it with the spread syntax, such as ...UserFields, wherever the fragment's type condition is compatible.

What is the difference between a named and inline fragment?

A named fragment is declared separately and can be reused. An inline fragment is written directly inside a selection set and is generally used for a one-time type-specific selection.

Can GraphQL fragments be used in mutations?

Yes. Fragments can be used to select reusable fields from mutation results and mutation payloads, just as they can be used with query results.

Can fragments be used with GraphQL unions?

Yes. Named or inline fragments can target the concrete object types that are members of a union. This allows clients to request different fields depending on the returned type.

Can GraphQL fragments use variables?

Fragments do not declare operation variables themselves, but their selections can use variables declared by the surrounding operation, for example through directives such as @include or @skip.

Why is my GraphQL fragment invalid?

Common causes include an incompatible type condition, an unknown field, an unused fragment, duplicate names, a fragment cycle, a missing fragment definition, or a variable used by a directive that is not declared by the operation.

Helpful GraphQL Tools

GraphQL query formatters can make large operations and fragment definitions easier to read, while query minifiers can reduce a document when compact output is needed. Schema viewers help verify fragment type conditions and available fields, endpoint testers can execute complete operations containing fragments, and variable formatters can help inspect the variables supplied alongside those operations.

Conclusion

GraphQL fragments provide a practical way to organize and reuse field selections. Named fragments are especially useful when the same fields appear in multiple places, while inline fragments are valuable for type-specific selections on interfaces and unions.

The key concepts are fragment definitions, type conditions, fragment spreads, inline fragments, nested fragments, and fragment composition. Understanding these features makes large GraphQL operations easier to maintain and helps avoid duplicated selections.

Fragments are most effective when they represent meaningful reusable data requirements. Combined with schema validation and consistent organization, they can make complex GraphQL queries and mutations substantially easier to understand and evolve.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.