GraphQL Formatter & Prettifier

Frontend engineers working with Apollo, Relay, urql, or graphql-request paste auto-generated or network-captured queries into this tool to make them readable again. Backend developers use it to clean up schema SDL files produced by codegen before committing them to the repository. It also works in reverse: switch to minified mode to compress a query before embedding it in a mobile client or URL. The formatter runs a local tokenizer over your input — it never sends the query to a server, so internal API structures and business-logic fragments stay on your machine.

0 characters 1 line

How the Formatter Tokenizes and Lays Out GraphQL

The formatter does not use regular expressions to reformat your text. It runs a small hand-written lexer that walks the input character by character and classifies every token as a name, punctuation mark, string literal, number, or comment. The lexer tracks line and column positions so each token can be re-emitted in the correct order. Strings are consumed atomically — the scanner reads from the opening quote to the closing quote (handling backslash escapes) and never breaks or re-indents their contents.

After tokenization, the layout engine walks the token stream and decides line breaks based on punctuation context. Opening braces and brackets push an indent level; closing braces pop it. Commas act as soft break points inside selection sets, so each field lands on its own line. Directors (@include, @skip) stay attached to the field they annotate. Variable definitions inside operation parentheses stay on one line unless the group is long, matching the output style of Prettier's GraphQL plugin.

Minified mode takes a different path: it walks the same token stream but joins tokens with the minimum legal whitespace. Comments are dropped entirely in minified output since they carry no semantic meaning. The joining logic checks adjacent token types — a name next to another name needs a space, while a name next to an opening parenthesis does not — to avoid producing invalid syntax like query GetUser($id.

Everything executes synchronously in the main thread. For queries under 100 KB the operation completes in under a millisecond, so no web worker or async scheduling is needed. No code is eval'd, no dynamic imports run, and no data leaves the page.

Before and After Formatting Examples

Example 1 — Minified query from a network panel

Before:

query GetUser($id: ID!) { user(id: $id) { id name email role posts(first: 10) { edges { node { id title } } } } }

After (2-space indent):

query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    email
    role
    posts(first: 10) {
      edges {
        node {
          id
          title
        }
      }
    }
  }
}

Example 2 — Mutation with directives and variables

Before:

mutation($input: CreateUserInput!){createUser(input:$input){id name email @include(if:$showEmail) createdAt}}

After (2-space indent):

mutation($input: CreateUserInput!) {
  createUser(input: $input) {
    id
    name @include(if: $showEmail)
    createdAt
  }
}

Example 3 — Schema SDL and minify output

Schema SDL before:

type User{id:ID!name:String!email:String!role:Role!}enum Role{ADMIN EDITOR VIEWER}

After formatting:

type User {
  id: ID!
  name: String!
  email: String!
  role: Role!
}

enum Role {
  ADMIN
  EDITOR
  VIEWER
}

Example 1 minified:

query GetUser($id: ID!) { user(id: $id) { id name email role posts(first: 10) { edges { node { id title } } } } }

Where Teams Use This Formatter

Developer
  • Pretty-print a query copied from the browser Network tab before pasting it into your codebase.
  • Clean up codegen output when the GraphQL code generator emits everything on one line.
  • Format a teammate's fragment definitions during pull request review so field differences are visible.
  • Minify a large query before embedding it in a mobile bundle to shave bytes off the payload.
Production
  • Run the formatter as a pre-commit hook so every .graphql file in the repo follows one style.
  • Minify persisted queries in your gateway configuration to reduce network overhead.
  • Format schema SDL before publishing it to an internal developer portal.
  • Generate readable query diffs in CI logs when a persisted query changes.
Workflow
  • Paste a query from Slack, format it, then share the readable version with the team.
  • Pair with a JSON formatter: format the GraphQL, then validate the response payload against a schema.
  • Convert a minified playground query into documentation-friendly indented form for your wiki.
  • Keep a minified and a pretty version of every hot query — pretty for the repo, minified for the client.

Common Mistakes and Troubleshooting

Pasting a JSON response instead of a query

The tool expects GraphQL syntax, not JSON. If you paste a JSON response body, the tokenizer will treat braces and colons as GraphQL punctuation and produce output that looks indented but is not a valid query. Check your input starts with a keyword like query, mutation, subscription, fragment, type, or schema.

Unclosed braces or parens

If the input has an unmatched { or (, the layout engine will keep indenting until the end of the file, producing deeply nested output that looks wrong. Count your braces before formatting, or paste the query into your IDE's GraphQL extension first to locate the syntax error. The formatter preserves the error rather than guessing where a closing token was intended.

Smart quotes break string literals

Pasting from Google Docs or Slack can convert straight quotes (") into curly quotes (“ ”). GraphQL only recognizes straight double quotes for string values. The tokenizer treats a curly quote as a regular character, so the string never terminates and the rest of the query is swallowed into it. Replace curly quotes before formatting.

Comments disappear in minified mode

Minification drops all # comments because they add bytes with no semantic value. If your query depends on comments for documentation (rare but possible in shared SDL files), use the pretty format instead. Always keep the commented source in version control and only ship the minified version to clients.

Block strings with triple quotes

GraphQL block strings use triple double-quotes ("""..."""). The tokenizer handles these as single string tokens and does not reformat their interior. If you see the block string broken across lines in the output, it means the closing triple-quote was missing or an interpolation ${...} pattern confused the scanner. Verify the block string is properly closed.

Mixing tabs and spaces in input

GraphQL ignores whitespace, so mixed indentation in your input does not cause errors — but it can cause inconsistent-looking output before you click Format. The formatter normalizes everything to the indent style you select (2-space, 4-space, or tab). Always click Format after changing the indent setting to re-apply the new style.

Formatting Best Practices

  • ✓ One field per line: keep each leaf field on its own line in the repository. This makes git diffs show exactly which field was added or removed.
  • ✓ Align with your team's Prettier config: if your project uses 4-space indentation everywhere, set the indent dropdown to 4 so pasted queries match your codebase.
  • ✓ Minify only at the boundary: keep source queries pretty, then minify in the build step or at the CDN layer rather than committing minified files.
  • ✓ Strip before sharing: run minified mode before pasting a query into a public issue or Stack Overflow post to reduce its visual footprint.

Workflow and Security Tips

  • ✓ Format before code review: auto-format incoming query diffs so reviewers see structural changes rather than whitespace noise.
  • ✓ Nothing leaves the browser: the tokenizer runs locally, so proprietary queries, internal field names, and business rules are never transmitted.
  • ✓ Pair with API tools: after formatting, validate the API contract with the OpenAPI Formatter or inspect the response with the JSON Formatter.
  • ✓ Automate in CI: use the same indentation rules in a Prettier CI check so files stay formatted after every commit.

Frequently Asked Questions

What parts of GraphQL syntax does this formatter understand? ▼

The formatter tokenizes queries, mutations, subscriptions, fragments, directives, variable definitions, and full schema SDL (type, interface, enum, union, input, scalar, schema blocks). It handles string literals, block strings, numbers, comments, and all punctuation tokens including parentheses, brackets, and curly braces. It places each new selection set on its own indented line, which matches the conventions used by most GraphQL style guides.

Can this tool minify a GraphQL query for production use? ▼

Yes. Switch to minify mode and the tool strips every comment, line break, and redundant space while keeping the semantic tokens intact. Minified queries reduce the bytes sent over the wire, which matters for mobile clients and polling operations. A minified query still passes syntax validation at the server because GraphQL ignores whitespace outside of string literals.

Does formatting change the meaning of my query? ▼

No. GraphQL ignores whitespace and comments outside string literals, so reformatting is always semantically safe. The one rule to watch: text inside a quoted string or block string is preserved exactly as typed — the formatter never inserts breaks or alters content within quotes. Field order also stays the same, since field order does not affect results but does affect response key order in some clients.

Why do my directives lose their spacing after minification? ▼

Minified output places directives directly against the field they annotate, like user @include(if: $withEmail)name. This is valid GraphQL because @ and ( are delimiter tokens. The pretty-printer restores spaces for readability. If your client library has a parsing quirk with tightly packed directives, use the pretty format instead of minified output.

Can I format a GraphQL schema definition (SDL)? ▼

Yes. Paste type definitions, interfaces, enums, unions, inputs, or custom scalars and the formatter indents their fields and directives correctly. Schema SDL uses the same lexical grammar as queries, so the tokenizer treats both. This is useful when you receive a generated .graphql schema file from a codegen tool and want to read it side by side with your resolvers.

Is my GraphQL code sent to a server for processing? ▼

No. Tokenization and pretty-printing run entirely in your browser with a local JavaScript module. The tool issues no network requests carrying your query text. You can safely format internal API queries, proprietary business logic encoded in fragments, or pre-release schema files without exposing them.

How does this compare to running Prettier locally? ▼

Prettier is the gold standard for project-wide formatting but requires Node, a config file, and a CLI invocation per file. This tool gives you the same core result — consistent indentation and spacing — in one paste-click step with no setup. It is ideal for quick checks, chat pastes from teammates, or environments where you cannot install packages. For committed repositories, still run Prettier in CI as the source of truth.