GraphQL Directives
# 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
@includedirective to conditionally fetch fields.
-
Use the
@skipdirective 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.
The @skip Directive:
Skips the field *if* the argument is true.
6. Using Directives with Fragments
Directives can be applied to individual fields, but they are incredibly powerful when applied to entire Fragments.7. How the Response Changes
If you pass"showEmail": false to the first example:
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):
*(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 totrueand get the data. Security must be handled on the backend.
11. Mini Exercises
- 1. What character is used to prefix a directive in a query?
-
2.
If
$hideImagesistrue, should you use@skip(if: $hideImages)or@include(if: $hideImages)to prevent images from loading?
12. Coding Challenges
Challenge 1: Write a query calledGetProduct. 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
What character denotes a Directive in GraphQL?
Which two directives are built into the core GraphQL specification for clients?
@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
@includedirective.
- 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.