Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free

GraphQL query best practices

Operation naming, GraphQL variables, and more


When creating queries and , follow these best practices to get the most out of both 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 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 operation for both yourself and your teammates.
  • You avoid unexpected errors when combining multiple in a single query (an anonymous operation can only appear alone).
  • You improve debugging output in both client and server code, helping you identify exactly which operation is causing issues.
  • Apollo Studio provides helpful operation-level metrics, which require named operations.

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 variable 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 have other disadvantages relative to :

Reduced cache effectiveness

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

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

Reduced information privacy

The value of a GraphQL argument 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 variable 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 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 to distribute the structure of a single query between them. See Colocating fragments.
  • If you're a list field that returns more items than your component needs to render, you should paginate that field.

Query global data and user-specific data separately

Some fields 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 fields 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 fields 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)

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, automatically adds them to each operation request as HTTP headers (apollographql-client-name and apollographql-client-version).

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

Previous
Document transforms
Next
Overview
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc., d/b/a Apollo GraphQL.

Privacy Policy

Company