Skip to content

Instantly share code, notes, and snippets.

@mittalyashu
Created June 22, 2025 07:18
Show Gist options
  • Save mittalyashu/d4ab0811a65399c87110542a0dfd7e29 to your computer and use it in GitHub Desktop.
Save mittalyashu/d4ab0811a65399c87110542a0dfd7e29 to your computer and use it in GitHub Desktop.
Apollo Graphql server depth limit plugin
const depthLimitPlugin = (maxDepth: number): ApolloServerPlugin<GraphQLContext> => ({
async requestDidStart() {
return {
async didResolveOperation(requestContext) {
const document = requestContext.document
// Skip depth limit for "IntrospectionQuery" operation
if (requestContext.operationName === 'IntrospectionQuery') return
let depth = 0
let maxDepthReached = 0
visit(document, {
Field: {
enter() {
depth++
if (depth > maxDepthReached) {
maxDepthReached = depth
}
},
leave() {
depth--
}
}
})
if (maxDepthReached > maxDepth) {
throw new GraphQLError(
`Query depth limit exceeded. Max depth: ${maxDepth}, actual depth: ${maxDepthReached}`,
{
extensions: {
operationName: requestContext.operationName,
code: 'DEPTH_LIMIT_EXCEEDED',
maxDepth,
actualDepth: maxDepthReached
}
}
)
}
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment