# Variables and Directives — GraphQL

Source: https://www.skillbyai.com/en/graphql/q-variables

> Dynamic, safe queries.

## Never build queries from strings

**Variables** pass dynamic values separately from the query text: declare them in the operation signature (`$id: ID!`) and send values in the `variables` JSON. This keeps queries static (good for caching, persisted queries and security) and lets the server validate types. Built-in **directives** `@include(if:)` and `@skip(if:)` conditionally include fields; `@deprecated` marks schema elements as deprecated. Name every operation for easier logging and debugging.

## A parameterised query

Variables and a conditional field.

```graphql
query OrderHistory($first: Int = 10, $after: String, $withItems: Boolean!) {
  me {
    orders(first: $first, after: $after) {
      edges {
        node {
          id
          total { amount currency }
          items @include(if: $withItems) { quantity product { name } }
        }
      }
      pageInfo { hasNextPage endCursor }
    }
  }
}

# variables: { "first": 5, "withItems": true }
```

## Treat string-built queries as a smell

Concatenating user input into query text invites injection-like bugs and defeats persisted queries.

**Quiz:** Where are variable values sent?

- [ ] In the HTTP path
- [ ] Inside the field names
- [x] In a separate variables JSON object alongside the query
- [ ] In a cookie

*Answer:* In a separate variables JSON object alongside the query. Static query text, dynamic variables.
