GraphQL authorization and complexity
Local baseline: Node.js 22.16.0, ECMAScript modules, synthetic data. Run each complete example independently as node main.mjs in a disposable directory. Static ByteMind blocks do not imply live Node execution. SQLite is experimental in this baseline. Third-party integrations below are staged candidates, not installed or validated dependencies.
Apply field-level ownership
const record={owner:'u1',title:'Private notes'};function title(principal, record) { return principal?.id === record.owner ? record.title : null;}console.log(title({id:'u1'},record));console.log(title({id:'u2'},record));console.log(title(null,record));Expected output:
Private notesnullnullThe unauthorized and anonymous paths return no private value. A real schema must choose nullable or error semantics deliberately.
How it works
Use an authenticated principal from trusted request context, not a client-supplied owner ID. An authorized parent object does not automatically authorize all nested fields. A depth limit bounds nesting, but aliases, list fan-out and batches can increase cost without increasing depth. Assign cost weights to fields, cap list sizes and total operation work, enforce timeouts and redact internal errors. A production checker must inspect the validated AST, handle fragments, aliases and variables, and reject oversized input before expensive processing. The model below uses a precomputed, finite list of field costs; it is not an AST parser.
Enforce a synthetic operation budget
function allowed({depth, costs, pageSize}) { return depth <= 4 && pageSize <= 20 && costs.reduce((a,b)=>a+b,0) <= 50;}for (const req of [{depth:3,costs:[8,12],pageSize:10}, {depth:2,costs:[30,30],pageSize:5},{depth:5,costs:[1],pageSize:1}]) { console.log(allowed(req));}Expected output:
truefalsefalseWide and deep requests are refused independently. All costs in this example are trusted synthetic inputs.
Common mistakes
Do not disable introspection as the only security measure. Do not trust a complexity value supplied by a client. A rate limit on HTTP requests alone is insufficient if one request can perform much more work than another.
Practice and next steps
Design a policy for a catalog with at most 20 books per page and one nested publisher field. Decide how to charge two aliases for the same field and how to handle a missing authenticated principal.
Further reading: https://graphql.org/learn/security/. Related staged reference: node-graphql-authorization-and-complexity-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
GraphQL authorization and complexity — knowledge check
Apply the lesson to a fresh scenario and identify the failure boundary.
Why is depth limiting alone insufficient?
Which source should establish the principal?
Where should nested private-field access be checked?