Aliases and Fragments

GraphQL aliases allow the same field to appear multiple times under different response names.

For example:

query {
  firstUser: user(id: "1") {
    id
    name
  }
  secondUser: user(id: "2") {
    id
    name
  }
}

The response can contain:

{
  "data": {
    "firstUser": {
      "id": "1",
      "name": "Alice"
    },
    "secondUser": {
      "id": "2",
      "name": "Bob"
    }
  }
}

Without aliases, requesting the same field with different arguments would create a response-name conflict.

Fragments

Fragments allow reusable field selections.

fragment UserFields on User {
  id
  name
  email
}

The fragment can then be reused:

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

Fragments are particularly valuable in large applications because multiple screens may need the same fields.

There are two important fragment forms:

  • Named fragments such as ...UserFields.
  • Inline fragments such as ... on Admin.

Fragments are not simply a frontend convenience. They are part of the GraphQL operation document and participate in validation and execution.

Aliases and Reusable Fragments
fragment UserFields on User {
  id
  name
  email
}

query CompareUsers {
  first: user(id: "1") {
    ...UserFields
  }
  second: user(id: "2") {
    ...UserFields
  }
}
💡 The first and second aliases create unique response keys even though both selections call the user field. The UserFields fragment avoids duplicating the common field selection.
Key Takeaways
  • Aliases give fields custom response names.
  • Aliases are useful when requesting the same field multiple times with different arguments.
  • Fragments make field selections reusable.
  • Named fragments are defined for a specific GraphQL type.
Knowledge Check

What problem does an alias primarily solve when requesting the same field with different arguments?