Back to results for “GraphQL”
Node.js › GraphQL

What is the difference between a GraphQL query variable and hardcoding a value directly inside the query string?

Beginner

Answer

Query variables let you parameterize a GraphQL query with dynamic values passed separately from the query document itself (similar in spirit to a parameterized SQL query), rather than string-interpolating values directly into the query text -- this makes queries reusable across different inputs without needing to construct a new query string each time, and importantly avoids a class of injection-like bugs that could arise from improperly escaping interpolated values directly into the query syntax.
# Using a variable, defined separately from the query string
query GetUser($userId: ID!) {
  user(id: $userId) { name, email }
}

// Sent alongside the query as a separate variables object
{ "userId": "123" }
Real-world example A frontend application defines a single parameterized GetUser query once and reuses it for every different user ID needed throughout the app, simply passing a different variables object each time rather than constructing a brand new query string with the ID interpolated directly for every single request.

Common follow-ups: Why is directly interpolating a value into a GraphQL query string considered a worse practice than using variables, beyond just convenience?;How do query variables interact with GraphQL client libraries' caching mechanisms, like Apollo Client's normalized cache?