Created
June 22, 2025 07:18
-
-
Save mittalyashu/d4ab0811a65399c87110542a0dfd7e29 to your computer and use it in GitHub Desktop.
Apollo Graphql server depth limit plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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