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$variableis 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
ifargument, which is invalid. - Confusing
@skipwith@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
| Directive | Argument | Effect |
|---|---|---|
| @skip | if: Boolean | Skips the field if true |
| @include | if: Boolean | Includes 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.