0
0
GraphQLquery~5 mins

Depth limiting in GraphQL

Choose your learning style9 modes available
Introduction

Depth limiting helps stop queries from asking for too much nested data. This keeps the system fast and safe.

When you want to prevent very deep queries that slow down your server.
When users might accidentally or purposely ask for too much nested information.
When you want to keep your API response times quick and predictable.
When you want to protect your database from heavy loads caused by complex queries.
Syntax
GraphQL
const depthLimit = require('graphql-depth-limit');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(3)]
});

This example uses the graphql-depth-limit package with Apollo Server.

The number 3 means queries can only go 3 levels deep.

Examples
Limits queries to 2 levels deep.
GraphQL
validationRules: [depthLimit(2)]
Allows deeper queries up to 5 levels.
GraphQL
validationRules: [depthLimit(5)]
Only allows very shallow queries, just 1 level deep.
GraphQL
validationRules: [depthLimit(1)]
Sample Program

This sets up a GraphQL server that limits queries to 2 levels deep. Queries asking for more nested data will be rejected.

GraphQL
const { ApolloServer, gql } = require('apollo-server');
const depthLimit = require('graphql-depth-limit');

const typeDefs = gql`
  type Query {
    user: User
  }
  type User {
    id: ID
    name: String
    posts: [Post]
  }
  type Post {
    id: ID
    title: String
    comments: [Comment]
  }
  type Comment {
    id: ID
    content: String
  }
`;

const resolvers = {
  Query: {
    user: () => ({
      id: '1',
      name: 'Alice',
      posts: [
        {
          id: '101',
          title: 'Hello World',
          comments: [
            { id: '1001', content: 'Nice post!' },
            { id: '1002', content: 'Thanks for sharing.' }
          ]
        }
      ]
    })
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(2)]
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
OutputSuccess
Important Notes

Depth limiting helps protect your server from very complex queries.

Choose the depth limit based on how much nested data your app needs.

Too low a limit might block useful queries; too high might allow heavy loads.

Summary

Depth limiting stops queries from going too deep.

It keeps your server safe and fast.

Use it by adding validation rules in your GraphQL server setup.