Overview
Thegraphql middleware provides GraphQL query validation and security features including depth limiting, complexity analysis, introspection control, and field blocking.
Use it when you need:
- Query depth and complexity validation
- Introspection query control
- Field-level access control
- Operation allowlisting
- Protection against malicious queries
Installation
Quick Start
Configuration
Options
Examples
Basic Setup
Custom Depth and Complexity Limits
Production Configuration
Disable Introspection
Block Sensitive Fields
Allowlist Operations
Custom Error Handler
API Reference
Functions
Error Types
Technical Details
Query Validation Process
The middleware validates GraphQL queries through the following process:- Request Filtering: Only processes POST requests with
application/jsoncontent type - Query Parsing: Parses the request body into a
Querystructure containing:query: The GraphQL query stringoperationName: Named operation identifiervariables: Query variables map
- Validation Chain: Applies validations in order:
- Introspection check (if enabled)
- Operation allowlist check (if configured)
- Depth calculation and validation
- Complexity calculation and validation
- Blocked fields check (if configured)
- Body Restoration: Restores the request body for downstream handlers
Depth Calculation
Query depth is calculated by counting the maximum nesting level of braces{}:
- Tracks current depth using a counter
- Increments on
{, decrements on} - Records the maximum depth reached
Complexity Calculation
Query complexity is estimated using:- Count of field selections with braces:
\w+\s*(?:\([^)]*\))?\s*{ - Plus total count of opening braces
{
Introspection Detection
Introspection queries are detected using regex pattern matching for:__schema- Schema introspection__type- Type introspection
Implementation Notes
- The middleware preserves the request body after validation for downstream handlers
- Non-POST requests and non-JSON requests bypass validation
- Failed JSON parsing allows the request to pass through (handled by GraphQL server)
- Default limits provide reasonable protection for most applications
Best Practices
- Disable introspection in production
- Set appropriate depth limits based on your schema
- Use complexity limits to prevent resource exhaustion
- Block sensitive fields at the middleware level
- Implement custom error handlers for better user experience
- Combine with rate limiting for additional protection
Testing
Test Coverage
Security Considerations
Query Depth Attacks
Deep nested queries can cause exponential computation:MaxDepth based on your schemaβs maximum legitimate nesting.
Query Complexity Attacks
Complex queries can exhaust server resources:MaxComplexity to limit total query cost.
Introspection Leaks
Introspection exposes your entire schema structure:NoIntrospection() or Production().
Sensitive Field Access
Prevent access to sensitive fields:BlockFields() to prevent access to sensitive data.