Skip to main content
GraphQL Basics
CHAPTER 12 Beginner

GraphQL Fragments

Updated: May 13, 2026
15 min read

# CHAPTER 12

GraphQL Fragments

1. Introduction

As your application grows, your GraphQL queries will become larger and more complex. You will likely find yourself requesting the exact same set of fields in multiple different queries across your application. In software engineering, we follow the DRY principle (Don't Repeat Yourself). In this chapter, we will introduce Fragments, a powerful feature of GraphQL that allows you to create reusable pieces of query logic, making your frontend code cleaner, more maintainable, and less prone to errors.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what a GraphQL Fragment is.
  • Understand the syntax for creating and spreading fragments in queries.
  • Apply fragments to keep frontend queries DRY.
  • Utilize Inline Fragments for working with interfaces or union types.

3. Beginner-Friendly Explanation

Imagine you are a frequent traveler. You have a specific list of essentials you pack every time: passport, toothbrush, and phone charger. Instead of writing out that entire list every time you plan a trip to a new city, you create a sticky note called "Travel Essentials."

When you plan a trip to Paris, your packing list just says: "Clothes, Camera, + *[Travel Essentials]*". When you go to Tokyo, your list says: "Business Suit, Laptop, + *[Travel Essentials]*".

A Fragment is that sticky note. It is a reusable list of fields that you can insert (or "spread") into any query that needs them, rather than typing out id, name, email, avatarUrl every single time you query a User.

4. Real-World Examples

  • UI Components: In modern frameworks like React, you build a UserProfileCard component. You define a fragment containing the exact fields that card needs. Whenever a parent component queries data, it just includes the UserProfileCard fragment, ensuring the component always gets the data it requires.
  • Standardized Responses: If you have multiple mutations (e.g., updateUser, changePassword, updateAvatar), they all likely return the updated User object. Instead of writing the same 10 fields in every mutation response, you use a UserDetails fragment.

5. Detailed Code Examples

Let's see how fragments are created and used.

The Problem (Repetitive Code):

graphql
123456789101112131415161718
query GetUserA {
  user(id: "1") {
    id
    username
    email
    profilePic
  }
}

query GetUserB {
  user(id: "2") {
    id
    username
    email
    profilePic
    role
  }
}

The Solution (Using a Fragment): We define a fragment using the fragment keyword, give it a name, and specify which Type it belongs to using the on keyword.

graphql
123456789101112131415161718192021
# 1. Define the fragment
fragment CoreUserInfo on User {
  id
  username
  email
  profilePic
}

# 2. Use (spread) the fragment in queries using three dots (...)
query GetUserA {
  user(id: "1") {
    ...CoreUserInfo
  }
}

query GetUserB {
  user(id: "2") {
    ...CoreUserInfo
    role # You can still add specific fields alongside the fragment!
  }
}

6. Mutation Examples with Fragments

Fragments are incredibly useful in mutation responses to ensure consistency.
graphql
12345
mutation UpdateEmail($id: ID!, $email: String!) {
  changeEmail(id: $id, newEmail: $email) {
    ...CoreUserInfo
  }
}

7. Inline Fragments (Advanced)

Sometimes a GraphQL API returns a list that contains different *types* of objects (like a feed containing both Photos and Articles). How do you query specific fields when you don't know what type will be returned? You use an Inline Fragment.
graphql
123456789101112131415161718
query GetFeed {
  feedItems {
    id
    createdAt
    
    # If the item is a Photo, fetch the url
    ... on Photo {
      imageUrl
      resolution
    }
    
    # If the item is an Article, fetch the text
    ... on Article {
      headline
      content
    }
  }
}

8. Schema Requirements for Fragments

You do not define fragments in your server's Schema SDL! Fragments are purely a client-side construct. The server understands them as long as the type specified after the on keyword exists in the schema.

9. Best Practices

  • Name Fragments Clearly: A fragment name should describe its purpose or the UI component it fuels, e.g., AuthorCardDetails or NavMenuUser.
  • Co-locate Fragments: If you are using a component-based frontend framework (Vue/React), define the fragment in the exact same file as the component that uses it.
  • Don't Over-Fragment: If a fragment is only used once, there is no need to create it. Only extract fields into a fragment if they are reused in multiple places.

10. Common Mistakes

  • Forgetting the on keyword: A fragment *must* declare what Schema Type it belongs to (e.g., fragment Details on Product).
  • Spreading on the wrong type: You cannot use ...CoreUserInfo (which is on User) inside a query that returns a Product. GraphQL will throw a validation error.

11. Mini Exercises

  1. 1. What three characters are used to "spread" a fragment into a query?
  1. 2. Look at this definition: fragment ItemDetails on Product { price }. What does Product represent?

12. Coding Challenges

Challenge 1:
  1. 1. Create a fragment called BookSummary on the Book type that includes title and isbn.
  1. 2. Write a query called GetLibrary that fetches allBooks, and spread your BookSummary fragment inside the selection set.

13. MCQs with Answers

Question 1

What is the primary purpose of a GraphQL Fragment?

Question 2

Which symbol is used to include (spread) a fragment within a query?

Question 3

When querying an array that contains multiple different object types (like a timeline), what feature must you use?

14. Interview Questions

  • Q: Explain the concept of DRY code and how GraphQL Fragments help achieve it.
  • Q: Where are fragments defined: on the server's Schema or by the frontend client?
  • Q: What is an Inline Fragment and in what specific scenario is it used?

15. FAQs

Q: Can a fragment include another fragment inside it? A: Yes! This is called nesting fragments. It is highly encouraged when building complex UI components that are made up of smaller sub-components.

Q: Are fragments sent to the server? A: Yes. When the client makes the HTTP request, the fragment definitions are sent alongside the query string so the server can parse and expand them before executing.

16. Summary

In this chapter, we tackled query optimization and code cleanliness by introducing Fragments. We learned how to define reusable blocks of fields using the fragment and on keywords, and how to inject them into Queries and Mutations using the spread operator (...). We also touched on Inline Fragments, a powerful tool for querying mixed-type arrays like social media feeds.

17. Next Chapter Recommendation

What happens if you need to fetch two different Users in the exact same query? The JSON response keys would conflict! To solve this, proceed to Chapter 13: GraphQL Aliases to learn how to rename fields on the fly.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·