Skip to main content
GraphQL Basics
CHAPTER 14 Beginner

GraphQL Directives

Updated: May 13, 2026
15 min read

# CHAPTER 14

GraphQL Directives

1. Introduction

Sometimes, the data you need from a query depends on conditions at runtime. For example, you might only want to fetch a user's address if a specific toggle switch is activated on the frontend. While you could write two completely separate queries, GraphQL offers a much more elegant solution: Directives. In this chapter, we will learn how to use built-in directives to dynamically alter the shape of our queries based on variables, keeping our code clean and efficient.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what a GraphQL Directive is.
  • Use the @include directive to conditionally fetch fields.
  • Use the @skip directive to conditionally ignore fields.
  • Understand how directives interact with GraphQL Variables.

3. Beginner-Friendly Explanation

Imagine filling out a customized order form for a car. The form has a section for "Sunroof Options." Next to it, there is a checkbox that says: *[ ] Skip this section if you want a convertible.*

In GraphQL, a Directive is that checkbox. It provides instructions to the server *during execution*. Instead of creating two different forms (one for convertibles, one for hardtops), you use one form and attach a Directive.

You tell GraphQL: "Fetch the user's name, and fetch their profile picture, but @skip the profile picture if my $isMobile variable is true." The server reads the directive and adjusts the response on the fly.

4. Real-World Examples

  • Responsive Design: On a desktop UI, you have space to show a user's full biography and recent posts. On a mobile UI, you only have space for their name. You can use @include(if: $isDesktop) to only fetch the heavy data when the app is on a large screen, saving bandwidth on mobile.
  • Feature Flags: If you are testing a new "Rewards Points" feature, you can pass a variable $showRewards. If true, the query includes the rewards data; if false, it skips it.

5. Detailed Code Examples

GraphQL comes with two built-in directives for conditional queries: @include and @skip.

The @include Directive: Includes the field *only if* the argument is true.

graphql
1234567
query GetUser($showEmail: Boolean!) {
  user(id: "1") {
    name
    # Email is only fetched if $showEmail is true
    email @include(if: $showEmail)
  }
}

The @skip Directive: Skips the field *if* the argument is true.

graphql
1234567891011
query GetArticle($isGuest: Boolean!) {
  article(id: "101") {
    title
    content
    # Comments are excluded if the user is a guest
    comments @skip(if: $isGuest) {
      text
      author
    }
  }
}

6. Using Directives with Fragments

Directives can be applied to individual fields, but they are incredibly powerful when applied to entire Fragments.
graphql
1234567
query FetchDashboard($showAdminPanel: Boolean!) {
  me {
    username
    # Include a massive chunk of fields only if the user is an admin
    ...AdminDetails @include(if: $showAdminPanel)
  }
}

7. How the Response Changes

If you pass "showEmail": false to the first example:
json
12345678
{
  "data": {
    "user": {
      "name": "Jane Doe"
      // Notice email is completely missing, not even null!
    }
  }
}

8. Custom Directives (Server-Side)

While @skip and @include are built into the GraphQL specification for the *client*, you can also define Custom Directives on the *server* schema. This is an advanced topic often used for formatting or authorization.

Schema Example (Server-side):

graphql
12345
directive @uppercase on FIELD_DEFINITION

type User {
  name: String @uppercase
}

*(In this scenario, the PHP backend intercepts the resolver and converts the name to uppercase before returning it).*

9. Best Practices

  • Use variables, not hardcoded booleans: Never write @include(if: true). That defeats the purpose. Always link directives to a GraphQL Variable passed from the frontend.
  • Optimize Bandwidth: Use directives heavily in mobile application development to avoid downloading large text fields, high-res image URLs, or deep relationships when on cellular data.

10. Common Mistakes

  • Confusing @skip and @include: They are exact opposites. @skip(if: true) means the data will *not* be returned. @include(if: true) means the data *will* be returned. Think carefully about your logic!
  • Using Directives for Security: Do NOT use client-side directives (@skip) as a security measure to hide data from unauthorized users. The user can simply change the variable to true and get the data. Security must be handled on the backend.

11. Mini Exercises

  1. 1. What character is used to prefix a directive in a query?
  1. 2. If $hideImages is true, should you use @skip(if: $hideImages) or @include(if: $hideImages) to prevent images from loading?

12. Coding Challenges

Challenge 1: Write a query called GetProduct. It takes one variable: $detailedView (Boolean). Query a product with fields name and price. Also query specifications, but only include it if $detailedView is true.

13. MCQs with Answers

Question 1

What character denotes a Directive in GraphQL?

Question 2

Which two directives are built into the core GraphQL specification for clients?

Q3. True or False: You should use @skip to prevent regular users from accessing Admin data. A) True, it stops the data from being fetched B) False, security should never rely on client-side directives *Answer: B*

14. Interview Questions

  • Q: Explain a scenario in frontend development where you would use the @include directive.
  • Q: Can directives be applied to fragments as well as individual fields?
  • Q: What is the difference between a built-in client directive (like @skip) and a custom server-side directive?

15. FAQs

Q: Can I use both @skip and @include on the same field? A: Technically yes, but it creates very confusing logic. It is better to rely on a single boolean variable and one directive.

Q: Do directives affect backend performance? A: Yes! If a field is skipped, the GraphQL engine will not execute the resolver for that field, saving database queries and processing time.

16. Summary

In this chapter, we explored how to make our queries conditionally dynamic using Directives. We learned that by attaching @include(if: $condition) or @skip(if: $condition) to a field or fragment, we can instruct the server to alter the shape of the JSON response. This is a powerful tool for building responsive UIs, toggling feature flags, and conserving network bandwidth without having to maintain multiple separate query strings.

17. Next Chapter Recommendation

Up to this point, our API has been open to everyone. But in the real world, APIs require logins, passwords, and security. Proceed to Chapter 15: Authentication in GraphQL APIs to learn how to identify users and secure your GraphQL endpoint.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·