Skip to main content

Static vs Dynamic Documents

🚫 Dynamic documents​

Typically, dynamic documents are generated at runtime through string concatenation or AST manipulation. For example:

query = "query GetUser { user(id: "
query += userId
query += ") { name"
if (showAvatar) {
query += " avatarUrl"
}
query += " } }"

This technique has a lot of drawbacks:

  • Potentially infinite documents issued to server, which must validate each new document at runtime.
  • Cannot easily analyze/lint with common tooling (e.g. graphql-eslint or gqlcheck).
  • Hard to spot syntax/AST mistakes; needs thorough testing.
  • Vulnerable to GraphQL injection.

✅ Static documents​

With static documents you write reusable documents such as:

query = `
query GetUser(
$userId: Int!
$showAvatar: Boolean! = false
) {
user(id: $userId) {
name
avatarUrl @include(if: $showAvatar)
}
}
`

And then you supply variables at run-time to populate the placeholders:

variables = { userId, showAvatar }

This has a lot of advantages:

  • Syntax highlighting and auto-complete directly in your editor (when supported).
  • Easy to copy/paste into GraphiQL or similar IDE for debugging.
  • Easy to use with standard GraphQL tooling such as linting.
  • Not vulnerable to GraphQL injection.
  • Validate each document once, no need to re-check when the variable values change.
  • Supports "trusted documents" security feature.
  • Can check validity at build time - remove need for runtime validation.
  • Easy to track which fields are in use.
  • Server can optimize known queries.

You should always use static documents unless there's a very good reason not to.

Other terms​

Ad-hoc documents are those written on the fly, generally by a human.