Aliases and Fragments
What you'll learn: How to avoid naming collisions and reduce repetition in GraphQL queries using aliases and fragments.
The Problem GraphQL Aliases Solve
Sometimes you need to query the same field multiple times with different arguments. For example, fetching two different users by ID in a single query. Without aliases, GraphQL wouldn't know how to distinguish the results—both would try to use the same field name.
Aliases let you rename fields in the response. You write an alias before the field name with a colon:
query {
firstUser: user(id: "1") {
name
email
}
secondUser: user(id: "2") {
name
email
}
}
The response object now has firstUser and secondUser keys instead of conflicting user keys.
Fragments: Reusable Field Selections
Notice how both users request name and email? Fragments let you define a reusable set of fields, like a template:
fragment UserFields on User {
name
email
}
query {
firstUser: user(id: "1") {
...UserFields
}
secondUser: user(id: "2") {
...UserFields
}
}
The ...UserFields syntax spreads those fields into the query. Think of fragments like variables for field selections—define once, use everywhere. This keeps queries DRY and easier to maintain.
Fragments are especially valuable in complex queries where multiple places need the same detailed object structure.
When to Use Each
Use aliases when you need the same field with different arguments in one query. Use fragments when multiple parts of your query need identical field selections.
Key Takeaway: Aliases prevent naming conflicts when querying the same field multiple times; fragments eliminate repetition by packaging reusable field selections you can spread throughout your queries.