0
0
GraphqlHow-ToBeginner · 3 min read

How to Use @skip Directive in GraphQL Queries

Use the @skip directive in GraphQL to conditionally exclude fields from the query result based on a boolean variable. It takes an if argument; when true, the field is skipped and not returned in the response.
📐

Syntax

The @skip directive is used on fields or fragments in a GraphQL query. It requires an if argument that must be a boolean variable or expression. When if is true, the field is omitted from the result; when false, the field is included.

Example parts:

  • @skip(if: $variable): skips the field if $variable is true.
  • $variable: a boolean variable defined in the query variables.
graphql
query GetUser($skipEmail: Boolean!) {
  user(id: "1") {
    id
    name
    email @skip(if: $skipEmail)
  }
}
💻

Example

This example shows how to skip the email field when the variable skipEmail is true. If skipEmail is false, the email is included in the response.

graphql
query GetUser($skipEmail: Boolean!) {
  user(id: "1") {
    id
    name
    email @skip(if: $skipEmail)
  }
}

# Variables:
# { "skipEmail": true }

# Response when skipEmail is true:
# {
#   "data": {
#     "user": {
#       "id": "1",
#       "name": "Alice"
#     }
#   }
# }

# Variables:
# { "skipEmail": false }

# Response when skipEmail is false:
# {
#   "data": {
#     "user": {
#       "id": "1",
#       "name": "Alice",
#       "email": "alice@example.com"
#     }
#   }
# }
Output
{ "data": { "user": { "id": "1", "name": "Alice" } } }
⚠️

Common Pitfalls

Common mistakes when using @skip include:

  • Not defining the boolean variable in the query variables, causing errors.
  • Using a non-boolean value for the if argument, which is invalid.
  • Confusing @skip with @include, which works oppositely.

Always ensure the variable controlling @skip is properly declared and passed as a boolean.

graphql
query GetUser($skipEmail: String!) {
  user(id: "1") {
    id
    name
    email @skip(if: $skipEmail)  # Wrong: $skipEmail should be Boolean, not String
  }
}

# Correct version:
query GetUser($skipEmail: Boolean!) {
  user(id: "1") {
    id
    name
    email @skip(if: $skipEmail)
  }
}
📊

Quick Reference

DirectiveArgumentEffect
@skipif: BooleanSkips the field if true
@includeif: BooleanIncludes the field if true

Key Takeaways

Use @skip(if: Boolean) to exclude fields conditionally in GraphQL queries.
The if argument must be a boolean variable defined in query variables.
When if is true, the field is omitted from the response.
Do not confuse @skip with @include; they have opposite logic.
Always pass the correct boolean type to avoid query errors.