how-to-set-limit-of-query-graphql

In this tutorial, I’ll explain to you how to set limit of query complexity and depth of graphql in magento 2.

GraphQL was introduced in Magento 2.3 as a new API technology alongside the existing REST and SOAP APIs. It provides a more flexible and efficient way to interact with a Magento 2 store’s data. You can gain a deeper understanding about security configuration of GraphQL here.

Here’s an overview of GraphQL in Magento 2:

  • Flexible Data Retrieval: Unlike REST, where you typically retrieve fixed data structures, GraphQL allows clients to request only the needed data. Clients can specify which fields they want to retrieve in a single request.
  • Efficient Data Fetching: With GraphQL, clients can fetch multiple resources in a single request, reducing the number of round trips between the client and the server. This can improve the performance of web applications, especially on slow networks.
  • Strong Typing and Schema Definition: GraphQL uses a strongly typed schema to define the capabilities of the API. Clients can introspect this schema to discover available data and operations. This makes it easier to understand and consume the API.
  •  Real-time Updates: GraphQL supports subscriptions, allowing clients to receive real-time updates when data changes on the server. This is useful for building applications that require live data, such as chat applications or real-time analytics dashboards. In contrast, REST requires additional calls to ensure whether data has been updated or not.
  • Batching and Caching: GraphQL enables batching of requests, allowing multiple queries to be executed in a single HTTP request. This can help reduce network overhead. Additionally, GraphQL responses can be cached at the edge, further improving performance.

The di.xml files in both the Framework and GraphQL module define several security-related configuration values. It’s crucial to review these configurations to ensure they align with the types of mutations and queries you intend to execute.

How to Set Limit of Query Complexity and Depth of GraphQL in Magento 2

Let’s assume you have created a simple module. Now you need to create di.xml file at app/code/Vendor/Module/etc directory and paste the below code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
       <type name="Magento\Framework\GraphQl\Query\QueryComplexityLimiter">
        <arguments>
            <argument name="queryDepth" xsi:type="number">15</argument>
            <argument name="queryComplexity" xsi:type="number">200</argument>
        </arguments>
    </type>
</config>

In the di.xml file  there are two arguments I have passed queryDepth and queryComplexity

  1.  queryDepth: Defines the maximum depth of nodes that the query can return. The default value is 20.
    The queryDepth attribute determines the maximum depth a query can return. This may pose a concern for queries returning objects with hierarchical structures, like CategoryTree, or those fetching detailed data on complex products. While the default value of 20 accommodates deep hierarchies and products, you might consider lowering this number if you’re certain that legitimate queries won’t reach such depths.
  2. queryComplexity: Defines the maximum number of fields, objects, and fragments that a query can contain. The default value is 300.
    A complex GraphQL query, such as the cart or products query, can potentially generate a heavy workload on the server. Complex queries can potentially be used to create distributed denial of service (DDoS) attacks by overloading the server with specious requests.

Now, You just need to clean the cache and execute graphQl query to check the result.

php bin/magento c:c

If depth and complexity are higher than the set limit. Then, it will return an error

{
  "errors": [
    {
      "message": "Max query depth should be 15 but got 25.",
      "extensions": {
        "category": "graphql"
      }
    }
  ]
}

The following query has a maximum depth of 5.

{
  categories(
    filters: {
      parent_id: {in: ["2"]}
    }
  ) {
    total_count
    items {
      uid
      level
      name
      path
      children_count
      children {
        uid
        level
        name
        path
        children_count
        children {
          uid
          level
          name
          path
          children_count
          children {
            uid
            level
            name
            path
          }
        }
      }
    }
    page_info {
      current_page
      page_size
      total_pages
    }
  }
}

I trust this blog has provided clear guidance on configuring query complexity and depth limits for GraphQL in Magento 2. If I overlooked any details or if you have additional information to contribute, please don’t hesitate to leave a comment below. I’ll be sure to address any queries and provide the necessary solutions.

Rate this post