Operation Names
At 2 a.m. the bookshop's error dashboard fills with "slow GraphQL request". Every entry says query, and nothing else. Which screen sent it? If every operation had a name, the dashboard would say BookPage or AddReview and you would know where to look.
The rule
Name every operation: required with several, priceless in logs.
An operation name goes right after the operation type:
query BookPage($id: ID!) {
book(id: $id) { title price }
}
mutation AddReview($input: AddReviewInput!) {
addReview(input: $input) { id }
}The rules:
- A document with exactly one operation may leave it anonymous, as in
query { ... }or the shorthand{ ... }. - A document with more than one operation must name all of them.
- Names must be unique within the document.
When a document holds several operations, the request says which to run in the operationName field of the JSON body:
{
"query": "query BookPage($id: ID!) { ... } query AuthorPage($id: ID!) { ... }",
"operationName": "BookPage",
"variables": { "id": "b1" }
}Even when a name is optional, write one. Server logs, tracing tools and client devtools show it, error reports group by it, and some tools use it to look up stored copies of the query. By convention names are PascalCase and describe the purpose or the screen: BookPage, BrowseFantasyShelf, UpdatePrice. A name like Query1 tells the 2 a.m. reader nothing.
The name is only a label for the operation. It does not change which fields run or the shape of data; the response keys still come from the fields and aliases.