0
0
GraphqlDebug / FixBeginner · 3 min read

How to Fix 'Variable is Not Defined' Error in GraphQL

The 'variable is not defined' error in GraphQL happens when you use a variable in your query or mutation without declaring it in the operation's variable list. To fix it, declare the variable with its type in the operation signature and pass the variable value when executing the query or mutation.
🔍

Why This Happens

This error occurs because GraphQL requires all variables used in a query or mutation to be declared explicitly in the operation's parameter list. If you use a variable like $id inside your query but forget to declare it, GraphQL does not know what $id means and throws the error.

graphql
query GetUser {
  user(id: $id) {
    name
  }
}
Output
Variable "$id" is not defined.
🔧

The Fix

To fix this, declare the variable $id with its type (e.g., ID!) in the query signature. Then, when running the query, provide the variable value in the variables object.

graphql
query GetUser($id: ID!) {
  user(id: $id) {
    name
  }
}

// Variables passed when executing the query:
{
  "id": "123"
}
Output
{ "data": { "user": { "name": "Alice" } } }
🛡️

Prevention

Always declare all variables used in your GraphQL operations in the operation's parameter list with their correct types. Use tools like GraphQL IDEs or linters that highlight undeclared variables before running queries. Also, pass variables properly when executing queries or mutations to avoid this error.

⚠️

Related Errors

  • Variable "$id" of required type "ID!" was not provided: This means you declared a variable but forgot to pass its value when running the query.
  • Unknown argument: Happens when you use an argument not defined in the schema.

Key Takeaways

Declare all variables used in GraphQL queries or mutations in the operation signature.
Pass variable values when executing queries or mutations to avoid undefined variable errors.
Use GraphQL tools or linters to catch undeclared variables early.
Check variable types carefully to match schema requirements.
Related errors often involve missing variable values or schema mismatches.