Apollo Server Query Complexity Plugin
The `apollo-server-plugin-query-complexity` package provides a plugin for `@apollo/server` to enforce query complexity limits, safeguarding against overly resource-intensive queries. It is currently at version 4.0.0, aligning with `@apollo/server` v4.x. This plugin differentiates itself by being fully compatible with GraphQL operation variables, a feature that standard `graphql-js` validation rules cannot directly access when integrated with Apollo Server. It leverages `graphql-query-complexity` for its core estimation logic, supporting various estimators like `directiveEstimator` and `simpleEstimator`, which allow developers to define complexity values directly within their schema or through default calculation rules. This mechanism is crucial for preventing denial-of-service attacks by ensuring server stability and fair resource allocation. The project appears actively maintained, with releases typically synchronized with major `@apollo/server` versions.
Common errors
-
message: "Query is too complex. Requested complexity XXX is greater than maximum allowed YYY."
cause The calculated complexity of a GraphQL query, based on the plugin's estimators, exceeded the `maximumComplexity` defined in the plugin configuration.fixEither optimize the client-side query to reduce its complexity, or adjust the `maximumComplexity` setting in your `ApolloServerPluginQueryComplexity` configuration if the current limit is too strict for intended use cases. Review your complexity estimators for accuracy. -
Error: Cannot find module '@apollo/server' or Error: Cannot find module 'graphql-query-complexity'
cause One or more of the required peer dependencies (`@apollo/server`, `graphql`, or `graphql-query-complexity`) are not installed in the project or are installed with an incompatible version.fixInstall the missing peer dependencies using your package manager, ensuring their versions meet the requirements specified by `apollo-server-plugin-query-complexity@4.x`: `npm install @apollo/server@^4.0.0 graphql@^16.6.0 graphql-query-complexity@^0.12.0`.
Warnings
- breaking Version 4.x of `apollo-server-plugin-query-complexity` is designed exclusively for `@apollo/server` v4.x and `graphql` v16.x. Attempting to use this plugin version with older Apollo Server (e.g., `apollo-server` v3.x or `apollo-server-express` v3.x) will lead to runtime errors due to fundamental changes in Apollo Server's plugin API.
- gotcha The default error message for queries exceeding the complexity limit can be generic. For a better user experience, it's highly recommended to implement a custom `formatError` function in your `ApolloServer` configuration to catch `QueryComplexityError` and provide more descriptive feedback, including the requested and maximum complexity values.
- gotcha Misconfiguring complexity estimators can either render the plugin ineffective (allowing overly complex queries) or too restrictive (rejecting legitimate queries). Ensure all fields in your schema have a valid complexity estimation strategy, combining `directiveEstimator` for annotated fields and `simpleEstimator` or custom estimators for unannotated fields.
- gotcha `apollo-server-plugin-query-complexity` lists `graphql-query-complexity` as a peer dependency, meaning it must be installed separately by the user. Forgetting to install `graphql-query-complexity` will result in runtime errors as the plugin won't find its essential estimation logic.
Install
-
npm install apollo-server-plugin-query-complexity -
yarn add apollo-server-plugin-query-complexity -
pnpm add apollo-server-plugin-query-complexity
Imports
- ApolloServerPluginQueryComplexity
const ApolloServerPluginQueryComplexity = require('apollo-server-plugin-query-complexity');import ApolloServerPluginQueryComplexity from 'apollo-server-plugin-query-complexity';
- QueryComplexityError
import { QueryComplexityError } from 'apollo-server-plugin-query-complexity'; - directiveEstimator, simpleEstimator
import { directiveEstimator, simpleEstimator } from 'apollo-server-plugin-query-complexity';import { directiveEstimator, simpleEstimator } from 'graphql-query-complexity';
Quickstart
import { ApolloServer } from '@apollo/server';
import ApolloServerPluginQueryComplexity from 'apollo-server-plugin-query-complexity';
import { directiveEstimator, simpleEstimator } from 'graphql-query-complexity';
const typeDefs = `#graphql
directive @complexity(
value: Int!
multipliers: [String!]
) on FIELD_DEFINITION
type Query {
a: String! # Complexity of 1
b(n: Int!): String! @complexity(value: 1, multipliers: ["n"]) # Complexity of variable "n"
}
`;
const server = new ApolloServer({
typeDefs,
resolvers: {},
plugins: [
ApolloServerPluginQueryComplexity({
estimators: [directiveEstimator(), simpleEstimator()],
maximumComplexity: 100,
}),
],
});
// Example of starting the server (assuming a basic setup, e.g., for testing)
// This part is illustrative and depends on your Apollo Server integration (e.g., Express, standalone)
async function startApolloServer() {
// In a real application, you'd likely use startStandaloneServer or integrate with a web framework
// For demonstration, let's just log that the server is configured
console.log('Apollo Server configured with Query Complexity Plugin.');
console.log('Maximum complexity set to 100.');
}
startApolloServer();