How to Secure GraphQL Resolvers
Authorize every GraphQL resolver with field-level checks, depth limiting, and query cost analysis to prevent data leaks and expensive queries.
On this page
Introduction
GraphQL gives clients a lot of power: they can ask for any field on any type, nest queries arbitrarily, and request as much data as the schema allows. That power is also a risk. Without authorization on every resolver, a client can read fields they should not see. Without depth and cost limits, a client can craft a query that exhausts the server. This guide shows how to secure resolvers at the field level, limit query depth, and enforce a cost budget.
The problem
A common mistake is to check authorization only at the query entry point. If a user can query a list of users and each user has an email field, the entry-point check passes but the email field is exposed to anyone who can run the query. Another mistake is ignoring query complexity: a nested query like friends-of-friends-of-friends can ask for exponential data and take down the server.
Design decisions
Authorization belongs in the resolver, not the gateway. Each resolver receives the parent object, arguments, context, and info; the context carries the authenticated user. The resolver checks whether the user can access the field before returning data. For depth, a middleware counts the nesting level and rejects queries deeper than a threshold. For cost, each field has a complexity score; a visitor sums the score and rejects queries over budget.
const resolvers = {
User: {
email: (parent, args, ctx) => {
if (ctx.user.id !== parent.id && !ctx.user.isAdmin)
throw new ForbiddenError('cannot read email');
return parent.email;
},
},
};
Implementation
Install depth limit and cost analysis as middleware or validation rules on the schema. The depth limit rejects queries deeper than a configured max, such as ten levels. The cost analysis walks the query AST, multiplies each field complexity by the number of list items it returns, and rejects queries whose total exceeds the budget. Both run before execution, so expensive queries never hit the resolvers.
import depthLimit from 'graphql-depth-limit';
import costAnalysis from 'graphql-cost-analysis';
const server = new ApolloServer({
schema,
validationRules: [
depthLimit({ maxDepth: 10 }),
costAnalysis({ maximumCost: 1000, variables: ctx }),
],
});
Testing the boundary
Test that a user querying another user’s email gets a ForbiddenError. Test that a query nested twenty levels deep is rejected before execution. Test that a query with a cost of two thousand is rejected, while a cost of five hundred succeeds. Test that an admin can read any email and a normal user can read their own.
Common pitfalls
Avoid putting auth only on Query and Mutation types; every field that returns sensitive data needs a check. Avoid setting the cost budget too high; it should reflect the worst-case your server can handle in the request timeout. Avoid skipping depth limits on introspection in production; introspection can be used to map the schema. Avoid logging rejected query details with full context, which may leak the attempted access.
Operational considerations
Authorize at the resolver level, not at the query level. A query-level check that verifies the user can run a query misses field-level leaks: a query that selects a public field and a private field on the same type passes a query-level check but must still deny the private field. Each resolver checks the context user against the specific field it resolves, so a field that should only be visible to an admin is denied for a non-admin even inside an otherwise allowed query. This is more code than a single gate, but it is the only place the check can be correct, because the resolver is the last point before the data leaves the system.
Limit query depth to a small number like ten, to block a query that nests a self-referential type indefinitely. A query like { user { posts { author { posts { author { ... } } } } } } expands into a join explosion that can exhaust the database or the resolver stack. A depth limit is a blunt instrument, because some legitimate queries are deep, but it is a cheap first filter. Pair it with a query cost analysis that assigns a weight to each field and rejects queries whose total cost exceeds a budget, so a wide query with many sibling fields is also bounded, not just a deep one.
Rate limit by query cost, not by request count. A client that sends one expensive query consumes more resources than a client that sends ten cheap ones, so a request-count limit lets the expensive client through while throttling the cheap one. A cost-based limit deducts the query cost from a token bucket and refills the bucket over time, so a client stays under a steady-state cost budget regardless of how they batch their queries. Document the cost model so clients can predict whether a query will be accepted, because a query that works in testing and is rejected in production is a bad migration experience.
Disable introspection in production, because an exposed schema tells an attacker every type, field, and relation and turns a secured API into a map of the attack surface. Keep introspection on in staging and development, where tooling needs it, and gate it behind an environment check. If a production client needs schema information, provide a frozen schema document out of band, not a live introspection endpoint. Persisted queries are a stronger control: the client sends a query hash, the server maps it to a pre-approved query, and arbitrary query strings are rejected entirely, so an attacker cannot even submit a query to analyze.
Conclusion
Securing GraphQL resolvers means authorizing every field, limiting depth, and enforcing a cost budget. Put the checks in the resolvers and the limits in validation rules. Test the boundaries: unauthorized access, deep nesting, and expensive queries. The result is a schema that gives clients power without giving them the keys.
Sources: GraphQL security, graphql-cost-analysis.
FAQ
- Why field-level auth instead of type-level?
- Field-level auth prevents leaking sensitive fields like email or salary on a type the user can otherwise read; type-level is too coarse.
- How do I limit query cost?
- Assign a complexity score to each field, sum the score across the query, and reject if the total exceeds a per-request budget.
- Should auth checks run before or after data loading?
- Before. Loading data the user cannot see wastes resources and risks leaking it through error messages or logs.
Report a problem with this articleOpens a pre-filled issue on GitHub.