How to Limit Query Depth in GraphQL for Better Security
To limit query depth in
GraphQL, use middleware or validation rules that check the depth of incoming queries before execution. Libraries like graphql-depth-limit help enforce a maximum depth, preventing clients from sending deeply nested queries that can overload your server.Syntax
The main way to limit query depth in GraphQL is by adding a validation rule to your GraphQL server setup. This rule checks the depth of each query and rejects those exceeding the limit.
Key parts:
depthLimit(maxDepth): Sets the maximum allowed depth.validationRules: An array of rules passed to the GraphQL server.graphqlHTTP: Middleware to handle GraphQL requests (for Express.js).
javascript
const depthLimit = require('graphql-depth-limit'); const { graphqlHTTP } = require('express-graphql'); app.use('/graphql', graphqlHTTP({ schema: myGraphQLSchema, validationRules: [depthLimit(5)], // limit query depth to 5 }));
Example
This example shows how to set up a GraphQL server with a depth limit of 3. Queries deeper than 3 levels will be rejected with an error.
javascript
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const depthLimit = require('graphql-depth-limit'); // Simple schema with nested fields const schema = buildSchema(` type Query { user: User } type User { name: String posts: [Post] } type Post { title: String comments: [Comment] } type Comment { text: String } `); // Root resolver const root = { user: () => ({ name: 'Alice', posts: [ { title: 'Hello World', comments: [ { text: 'Nice post!' }, { text: 'Thanks for sharing.' } ] } ] }) }; const app = express(); app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, validationRules: [depthLimit(3)] // limit depth to 3 })); app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));
Output
Server running on http://localhost:4000/graphql
Common Pitfalls
Common mistakes when limiting query depth include:
- Setting the depth limit too low, which blocks valid queries.
- Not applying the depth limit in all environments, leaving production vulnerable.
- Ignoring other query complexity factors like query breadth or cost.
Always test your API with typical queries to find a balanced depth limit.
javascript
/* Wrong: No depth limit applied */ app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true })); /* Right: Apply depth limit to protect server */ app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, validationRules: [depthLimit(3)] }));
Quick Reference
| Concept | Description |
|---|---|
| depthLimit(maxDepth) | Function to set max allowed query depth |
| validationRules | Array of rules to validate queries before execution |
| graphqlHTTP | Express middleware to handle GraphQL requests |
| maxDepth too low | May block valid queries, test carefully |
| maxDepth too high | May allow expensive queries, risk server overload |
Key Takeaways
Use a validation rule like
graphql-depth-limit to restrict query depth in GraphQL servers.Set a reasonable max depth to balance security and functionality.
Always test your API with real queries to find the right depth limit.
Apply depth limiting in all environments, especially production.
Combine depth limiting with other protections like query complexity analysis.