How to Fix 'Variable is Not Defined' Error in GraphQL
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.
query GetUser {
user(id: $id) {
name
}
}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.
query GetUser($id: ID!) {
user(id: $id) {
name
}
}
// Variables passed when executing the query:
{
"id": "123"
}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.