0
0
GraphqlHow-ToBeginner · 3 min read

How to Use @include Directive in GraphQL: Syntax and Examples

Use the @include directive in GraphQL to conditionally include a field or fragment only when a specified boolean variable is true. It is written as @include(if: $variable) where $variable is a boolean variable passed with the query.
📐

Syntax

The @include directive is used to conditionally include fields or fragments in a GraphQL query. It takes one argument:

  • if: A boolean variable that controls whether the field or fragment is included.

The syntax looks like this:

graphql
fieldName @include(if: $variable)
💻

Example

This example shows a query that fetches a user's name and conditionally includes their email only if the variable showEmail is true.

graphql
query GetUser($showEmail: Boolean!) {
  user(id: "1") {
    name
    email @include(if: $showEmail)
  }
}
Output
{ "data": { "user": { "name": "Alice", "email": "alice@example.com" } } } // If showEmail is false: { "data": { "user": { "name": "Alice" } } }
⚠️

Common Pitfalls

Common mistakes when using @include include:

  • Not defining the boolean variable in the query variables.
  • Passing a non-boolean value to the if argument.
  • Forgetting to prefix the variable with $ in the directive.
  • Using @include on fields that are required and expecting them to be omitted.

Example of wrong and right usage:

graphql
query WrongUsage {
  user(id: "1") {
    email @include(if: true)  # Wrong: should use variable, not literal
  }
}

query RightUsage($showEmail: Boolean!) {
  user(id: "1") {
    email @include(if: $showEmail)  # Correct usage
  }
}
📊

Quick Reference

DirectiveArgumentDescription
@includeifBoolean variable that determines if the field/fragment is included
Usagefield @include(if: $var)Includes field only if $var is true
Variable Type$varMust be Boolean (true or false)
Common Errorif: true (literal)Incorrect, must use variable with $ prefix

Key Takeaways

Use @include(if: $variable) to conditionally include fields based on a boolean variable.
Always define the boolean variable in your query variables and prefix it with $ in the directive.
Passing a literal true/false directly to @include is incorrect; use variables instead.
Fields with @include can be omitted from the result if the condition is false.
Check your query variables carefully to avoid common mistakes with @include.