Apollo Server Query Complexity Plugin

raw JSON →
4.0.0 verified Tue Apr 21 auth: no javascript

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.

error 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.
fix
Either 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 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.
fix
Install 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.
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.
fix Ensure your project's `@apollo/server` and `graphql` dependencies are upgraded to their respective v4 and v16 versions, respectively, before installing `apollo-server-plugin-query-complexity@4.x`.
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.
fix Add a `formatError` option to your `ApolloServer` constructor that checks if `error instanceof QueryComplexityError` and returns a custom formatted error object.
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.
fix Carefully review your `estimators` array in the `ApolloServerPluginQueryComplexity` configuration. Ensure `directiveEstimator()` is included if using `@complexity` directives, and consider `simpleEstimator()` as a fallback or default for fields without explicit directives.
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.
fix Always install `graphql-query-complexity` alongside `apollo-server-plugin-query-complexity`: `npm install graphql-query-complexity` or `yarn add graphql-query-complexity`.
npm install apollo-server-plugin-query-complexity
yarn add apollo-server-plugin-query-complexity
pnpm add apollo-server-plugin-query-complexity

Demonstrates how to integrate the query complexity plugin into an Apollo Server instance with directive-based and simple complexity estimators, setting a maximum complexity limit.

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();