GraphQL Directives
Directives in GraphQL are special annotations that allow you to dynamically change the behavior of a query or schema. They act like conditionals in your query logic, giving you control over which fields are included or how execution is handled.
Built-in Directives
GraphQL comes with two built-in directives:
@include(if: Boolean)
Includes a field only if the if
condition evaluates to true
.
Example:
@skip(if: Boolean)
Skips a field if the if
condition is true
.
Example:
Use Cases
- Conditionally showing sensitive data (e.g., email, roles).
- Toggling verbose vs. minimal responses.
- Building reusable components with toggled fields.
Custom Directives
GraphQL also supports custom directives, which are defined in the schema and implemented on the server.
Defining a Directive
Using a Directive
Note: Custom directives require server-side support and are not natively processed by the GraphQL execution engine.
Directive Locations
Directives can be applied to various parts of a GraphQL document:
FIELD
FRAGMENT_SPREAD
INLINE_FRAGMENT
FIELD_DEFINITION
QUERY
MUTATION
- and more…
Refer to the GraphQL specification for the full list of directive locations.
Example: Toggle Fields with Directives
query GetProduct($withReviews: Boolean!) {
product(id: "1") {
name
price
reviews @include(if: $withReviews) {
rating
comment
}
}
}
Best Practices
- Use directives for client-side flexibility, especially in dynamic UIs.
- Avoid logic-heavy queries — keep server responsibilities clear.
- Keep custom directives simple and well-documented.