Docs
Launch GraphOS Studio

GraphQL query best practices

Operation naming, GraphQL variables, and more


When creating queries and s, follow these best practices to get the most out of both GraphQL and Apollo tooling.

Name all operations

These two queries fetch the same data:

# Recommended ✅
query GetBooks {
books {
title
}
}
# Not recommended ❌
query {
books {
title
}
}

The first query is named GetBooks. The second query is anonymous.

You should define a name for every GraphQL in your application. Doing so provides the following benefits:

  • You clarify the purpose of each for both yourself and your teammates.
  • You avoid unexpected errors when combining multiple s in a single query document (an anonymous can only appear alone).
  • You improve debugging output in both client and server code, helping you identify exactly which is causing issues.
  • Apollo Studio provides helpful -level metrics, which require named s.

Use GraphQL variables to provide arguments

These two queries can both fetch a Dog object with ID "5":

# Recommended ✅
query GetDog($dogId: ID!) {
dog(id: $dogId) {
name
breed
}
}
# Not recommended ❌
query GetDog {
dog(id: "5") {
name
breed
}
}

The first query uses a ($dogId) for the value of the dog 's required . This means you can use the query to fetch a Dog object with any ID, making it much more reusable.

You pass values to useQuery (or useMutation) like so:

dog.tsx
const GET_DOG = gql`
query GetDog($dogId: ID!) {
dog(id: $dogId) {
name
breed
}
}
`;
function Dog({ id }) {
const { loading, error, data } = useQuery(GET_DOG, {
variables: {
dogId: id
},
});
// ...render component...
}

Disadvantages of hardcoded GraphQL arguments

Beyond reusability, hardcoded s have other disadvantages relative to s:

Reduced cache effectiveness

If two otherwise identical queries have different hardcoded values, they're considered entirely different operations by your GraphQL server's cache. The cache enables your server to skip parsing and validating s that it's encountered before, improving performance.

The server-side cache also powers features like automatic persisted queries and query plans in a federated gateway. Hardcoded s reduce the performance gains of these features and take up useful space in the cache.

Reduced information privacy

The value of a GraphQL might include sensitive information, such as an access token or a user's personal info. If this information is included in a query string, it's cached with the rest of that query string.

values are not included in query strings. You can also specify which values (if any) are included in metrics reporting to Apollo Studio.

Query only the data you need, where you need it

One of GraphQL's biggest advantages over a traditional REST API is its support for declarative data fetching. Each component can (and should) query exactly the s it requires to render, with no superfluous data sent over the network.

If instead your root component executes a single, enormous query to obtain data for all of its children, it might query on behalf of components that aren't even rendered given the current state. This can result in a delayed response, and it drastically reduces the likelihood that the query's result can be reused by a server-side response cache.

In the large majority of cases, a query such as the following should be divided into multiple queries that are distributed among the appropriate components:

  • If you have collections of components that are always rendered together, you can use s to distribute the structure of a single query between them. See Colocating fragments.
  • If you're querying a list that returns more items than your component needs to render, you should paginate that field.

GraphQL fragments are sets of s you can share across multiple s. Here's an example declaration:

# Recommended ✅
fragment NameParts on Person {
title
firstName
middleName
lastName
}

It's likely that multiple queries in an app require a person's full name. This NameParts helps keep those queries consistent, readable, and short:

# Recommended ✅
query GetAttendees($eventId: ID!) {
attendees(id: $eventId) {
id
rsvp
...NameParts # Include all fields from the NameParts fragment
}
}

Avoid excessive or illogical fragments

If you use too many s, your queries might become less readable:

Additionally, only define s for sets of s that share a logical semantic relationship. Don't create a just because multiple queries happen to share certain s:

# Recommended ✅
fragment NameParts on Person {
title
firstName
middleName
lastName
}
# Not recommended ❌
fragment SharedFields on Country {
population
neighboringCountries {
capital
rivers {
name
}
}
}

Query global data and user-specific data separately

Some s return the exact same data regardless of which user queries them:

# Returns all elements of the periodic table
query GetAllElements {
elements {
atomicNumber
name
symbol
}
}

Other s return different data depending on which user queries them:

# Returns the current user's documents
query GetMyDocuments {
myDocuments {
id
title
url
updatedAt
}
}

To improve the performance of your server-side response cache, fetch these two types of s in separate queries whenever possible. By doing so, your server can cache just a single response for a query like GetAllElements above, while caching separate responses for each user that executes GetMyDocuments.

Set your app's name and version for metrics reporting (paid)

This recommendation is most pertinent to Apollo Studio organizations with a paid plan, however it can be helpful for all apps.

The constructor of ApolloClient accepts the name and version options:

const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache(),
name: 'MarketingSite',
version: '1.2'
});

If you specify these values, Apollo Client automatically adds them to each request as HTTP headers (apollographql-client-name and apollographql-client-version).

Then if you've configured metrics reporting in Apollo Studio, Apollo Server includes your app's name and version in the traces it reports to Studio. This enables you to segment metrics by client.

Previous
Document transforms
Next
Overview
Edit on GitHubEditForumsDiscord