Directives
Directives provide metadata or instructions that can modify how parts of a GraphQL operation or schema are interpreted.
GraphQL includes built-in directives such as @skip and @include.
For example:
query User($includeEmail: Boolean!) {
user(id: "42") {
id
name
email @include(if: $includeEmail)
}
}
If $includeEmail is false, the email field is omitted from the selection during execution.
@skip works in the opposite direction:
email @skip(if: $hideEmail)
Directives can also be used in schema definitions. Frameworks and GraphQL servers may provide custom directives for authentication, deprecation, federation, validation, caching, or other concerns.
However, directives should be used carefully. A custom directive can become a powerful extension mechanism, but excessive directive-based business logic can make schema behavior difficult to understand and test.
GraphQL also supports deprecation metadata:
field: String @deprecated(reason: "Use newField instead")
Deprecation allows an API to evolve while communicating migration guidance to clients.
query GetUser($showEmail: Boolean!) {
user(id: "42") {
id
name
email @include(if: $showEmail)
}
}@include directive controls whether email is included based on the Boolean variable. The schema still defines the field; the directive affects whether the client requests it in this particular operation.- Directives add instructions or metadata to GraphQL operations and schemas.
@includeconditionally includes a field or fragment.@skipconditionally skips a field or fragment.- Deprecation directives help evolve APIs safely.
- Custom directives should be introduced with clear architectural boundaries.
What does the built-in `@include(if: Boolean!)` directive do?