StackPractices
advanced By Mathias Paulenko

Complete Guide to GraphQL Security

Secure a production GraphQL API: introspection control, depth and cost limits, rate limiting, persisted queries, injection prevention, and error sanitization.

Introduction

A GraphQL endpoint is a single URL that accepts arbitrary queries. That flexibility is what makes it great for clients and attractive for attackers: one POST request can ask for your entire user table, nest itself ten levels deep, or pack fifty operations into a single HTTP call. REST APIs limit exposure through fixed routes; GraphQL exposes the full schema and lets the client decide what to ask for.

If you expose a GraphQL API in production, you inherit an attack surface that REST teams never had to think about. This guide walks through that surface threat by threat and shows the defenses that actually work against Apollo Server 4/5 — the code below targets @apollo/server v4+ and current @graphql-tools APIs, not the legacy Apollo Server 2/3 patterns that still dominate most tutorials.

The GraphQL Attack Surface

Six threats account for nearly every GraphQL-specific incident. Keep this map in mind — the rest of the guide builds each defense.

ThreatWhat it looks likePrimary defense
Introspection leakAttacker dumps your entire schema, including admin fieldsintrospection: false + gated introspection
Depth attackuser { posts { author { posts { ... } } } } recursing through resolversgraphql-depth-limit validation rule
Cost-based DoSShallow query asking for 10,000 items × 50 fieldsCost/complexity limits (GraphQL Armor)
Alias/directive overloadOne operation with 5,000 aliases or directivesmaxAliases / maxDirectives rules
Batching abuse200 queries in one HTTP request, bypassing per-request limitsBatch size cap or allowBatchedHttpRequests: false
InjectionResolver input reaching SQL/NoSQL unescapedParameterized queries + input whitelists

Two more deserve mention: field suggestion enumeration (GraphQL “did you mean” errors let an attacker map your schema without introspection) and unbounded request payloads (multi-megabyte documents that exhaust the parser). Both are covered below.

Defense pipeline — every request passes through transport limits, document validation, authentication, resolver-level authorization, and error sanitization

When These Defenses Apply

Apply the full stack when your endpoint is reachable by clients you don’t control: public APIs, partner integrations, or any app where a browser’s JavaScript can be inspected and imitated. Public introspection, unlimited depth, and unrestricted batching are safe defaults only behind a private network boundary.

There are legitimate cases for relaxing them. Internal tools (GraphiQL, codegen pipelines, schema registries) need introspection, which is why the gated-introspection pattern exists instead of a blanket ban. And a persisted-query allowlist — the strictest posture — only makes sense once your client operations are stable enough to pre-register; on a rapidly evolving schema it breaks CI/CD more often than it blocks attackers.

If you’re hardening an API that’s already live, don’t try to ship everything at once. The order that pays off fastest: sanitizing errors and disabling field suggestions (one config flag each), then validation limits (depth, cost, aliases), then auth correctness, and only then persisted queries or an allowlist. The first row closes the cheapest reconnaissance paths in an afternoon; the last one changes your deployment process.

Introspection and Schema Exposure

Disable Introspection in Production

Introspection lets anyone download your entire schema: every type, field, argument, and relationship. Attackers use it to find sensitive fields (ssn, internalNotes, adminDashboard) and craft targeted queries. In production, turn it off — a public API has no legitimate consumer for a full schema dump.

import { ApolloServer } from "@apollo/server";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: process.env.NODE_ENV !== "production",
});

Gate Introspection for Internal Tools

Disabling introspection breaks legitimate tooling (GraphiQL, codegen). The fix is to allow introspection only for authenticated admin users. The correct Apollo Server 4 way is a plugin that inspects the parsed operation — not string matching on the query text, which produces false positives on comments and string literals:

import { ApolloServer } from "@apollo/server";
import { GraphQLError } from "graphql";

const introspectionGatePlugin = {
  async requestDidStart() {
    return {
      async didResolveOperation(requestContext) {
        const selections = requestContext.operation?.selectionSet.selections ?? [];
        const isIntrospection = selections.some(
          (s) => s.kind === "Field" && (s.name.value === "__schema" || s.name.value === "__type"),
        );
        if (isIntrospection && requestContext.contextValue.user?.role !== "ADMIN") {
          throw new GraphQLError("Introspection requires admin access", {
            extensions: { code: "FORBIDDEN" },
          });
        }
      },
    };
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true,
  plugins: [introspectionGatePlugin],
});

requestContext.operation is the parsed OperationDefinitionNode, so this can’t be bypassed by encoding tricks — __schema and __type are reserved field names in GraphQL and can’t be obfuscated. Older tutorials use string checks like query.includes("__schema"); that’s the pattern you want to avoid because it either misses nested introspection or fires on innocent queries containing the word in a string argument.

Hide Field Suggestions

Even with introspection off, GraphQL’s helpful “Did you mean email?” errors let an attacker enumerate your schema by guessing field names — tools like clairvoyance automate exactly this. Apollo Server 4 has a dedicated option:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: false,
  hideSchemaDetailsFromClientErrors: true, // strips "did you mean" hints
});

This option also strips other schema details from validation errors, which is what you want: a client that gets Cannot query field "eemail" learns nothing about what the real field is called.

Depth, Cost, and Alias Limiting

Depth Limiting

A query like user { posts { author { posts { author { ... } } } } } recurses through resolvers and databases for as many levels as the client chooses. graphql-depth-limit is a validation rule — it rejects the document before any resolver runs:

import depthLimit from "graphql-depth-limit";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [depthLimit(10)], // reject documents deeper than 10 levels
});

validationRules is a first-class option in Apollo Server 4 — the rules run inside validation and successful results are cached per document, so repeated identical queries don’t pay the cost twice.

To pick a real limit, write the deepest legitimate query your schema supports and measure it. A typical e-commerce graph might need query { users { orders { items { product { category { name } } } } } } = depth 6, so a limit of 10 gives headroom without inviting abuse. Set it too tight and legitimate mobile dashboards start failing; too loose and it’s a placebo.

Cost and Complexity Limiting

Depth alone doesn’t stop a two-level query that asks for 100 fields over a list of 10,000 items. Cost analysis assigns a weight to each field and rejects queries whose total exceeds a budget. The package you’ll see in older guides, graphql-cost-analysis, has been unmaintained for years — the maintained alternative is GraphQL Armor’s cost-limit rule:

import { costLimitRule } from "@escape.tech/graphql-armor-cost-limit";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    depthLimit(10),
    costLimitRule({
      maxCost: 1000,        // reject queries above 1000 complexity points
      objectCost: 2,        // each object field costs 2
      scalarCost: 1,        // each scalar costs 1
      depthCostFactor: 1.5, // deeper nesting multiplies cost
      ignoreIntrospection: true,
    }),
  ],
});

For Relay-style connections, annotate expensive edges so the estimator can account for pagination arguments — the @cost/@listSize directive conventions originated in the complexity-analysis ecosystem and are still the cleanest way to declare “this field returns N times its child cost”:

type Query {
  users(first: Int = 10): [User!]! @cost(complexity: 2, multipliers: ["first"])
  search(term: String!, limit: Int = 20): [SearchResult!]! @cost(complexity: 5, multipliers: ["limit"])
  report(startDate: DateTime!, endDate: DateTime!): Report @cost(complexity: 50)
}

Alias and Directive Overload

Aliases let a client repeat a field thousands of times in one operation — a1: user(id:1) a2: user(id:1) ... a5000: user(id:1) — inflating response size and resolver work without adding depth. Directives can be abused the same way. Both are cheap to cap:

import { maxAliasesRule } from "@escape.tech/graphql-armor-max-aliases";
import { maxDirectivesRule } from "@escape.tech/graphql-armor-max-directives";
import { maxTokensRule } from "@escape.tech/graphql-armor-max-tokens";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    depthLimit(10),
    costLimitRule({ maxCost: 1000 }),
    maxAliasesRule({ n: 15 }),
    maxDirectivesRule({ n: 50 }),
    maxTokensRule({ n: 15000 }), // cap raw document size before parsing finishes
  ],
});

Since Apollo Server 4.12, maxRecursiveSelections: true also guards against recursive fragment explosions — fragments that spread into themselves and expand a small document into millions of selections during validation. Enable it if your clients use fragments heavily.

GraphQL Armor: Defense in One Package

Instead of wiring rules one by one, GraphQL Armor bundles the whole validation layer. It’s maintained by Escape, tested against the attacks above, and drops into Apollo Server as a config spread:

import { ApolloArmor } from "@escape.tech/graphql-armor";

const armor = new ApolloArmor();
const protection = armor.protect();

const server = new ApolloServer({
  typeDefs,
  resolvers,
  ...protection, // installs plugins + validationRules
});

GraphQLArmorConfig lets you tune each rule (maxDepth.n, costLimit.maxCost, maxAliases.n, blockFieldSuggestions) and observe rejections via onAccept/onReject callbacks — the cleanest way to log suspicious documents without writing plugin plumbing yourself.

Rate Limiting

Per-IP and Per-Operation Limits

Request-level rate limiting is still necessary — it throttles brute force and credential stuffing before GraphQL validation even runs:

import rateLimit from "express-rate-limit";

const limiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 100,            // 100 requests per minute per IP
  standardHeaders: true,
});

app.use("/graphql", limiter);

Two production caveats. First, the default in-memory store doesn’t survive a second instance — behind a load balancer each pod counts separately, so use rate-limit-redis (or any shared store) once you run more than one replica. Second, make sure trust proxy is set correctly or every request will appear to come from your load balancer’s IP and share one bucket.

Cost-Aware Budgets

A client that sends 10 cheap queries shouldn’t hit the same limit as one that sends 10 queries costing 4,000 complexity points each. Track a cost budget per client identity (user ID or API key — not IP, which is shared in offices and CGNAT):

// In production back this with Redis INCR + EXPIRE, not an in-process Map
async function checkCostBudget(clientId, queryCost, redis) {
  const key = `cost-budget:${clientId}`;
  const current = await redis.incrby(key, queryCost);
  if (current === queryCost) {
    await redis.pexpire(key, 60_000); // 1-minute window
  }
  if (current > 5000) {
    throw new GraphQLError("Cost budget exceeded", {
      extensions: { code: "RATE_LIMITED" },
    });
  }
}

For the shared depth, complexity, and alias limits that should apply across your whole API surface, see the GraphQL API design guidelines.

Batching Abuse Prevention

Apollo Client can pack dozens of operations into one HTTP request. Attackers abuse this to send hundreds of queries inside a single request, multiplying the work allowed by each rate-limit token. In Apollo Server 4, allowBatchedHttpRequests defaults to false — leave it off unless a client specifically needs it. If you do enable it, cap the batch:

// Express middleware to limit batch size — runs before Apollo sees the request
app.use("/graphql", (req, res, next) => {
  if (Array.isArray(req.body) && req.body.length > 10) {
    return res.status(400).json({ error: "Batch size limit: 10 operations" });
  }
  next();
});

Note that cost-based budgets solve this more elegantly: whether a client sends 10 cheap operations or packs them into one request, they drain the same budget. Batching caps are a belt-and-suspenders control, not the primary defense.

Persisted Queries and Trusted Documents

Persisted queries invert the model: instead of sending query text, the client sends a hash (extensions.persistedQuery.sha256Hash) and the server looks up a query it already knows. For public-facing APIs this is the strongest posture available — if you only accept hashes you’ve pre-registered, arbitrary attacker queries never reach execution.

Apollo Server 4 ships with Automatic Persisted Queries on by default, backed by an unbounded in-memory cache — fix that, or a flood of unique hashes can exhaust memory:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: false,
  persistedQueries: {
    ttl: 900,             // expire unused entries after 15 minutes
    // or pass a bounded KeyValueCache (Memcached/Redis) for multi-instance setups
  },
});

For true trusted-documents-only mode, reject any request carrying raw query text:

const trustedDocumentsOnly = {
  async requestDidStart() {
    return {
      async didResolveOperation(requestContext) {
        if (requestContext.request.query) {
          throw new GraphQLError("Only persisted operations are allowed", {
            extensions: { code: "FORBIDDEN" },
          });
        }
      },
    };
  },
};

The remaining piece is registering the allowed documents at deploy time — Apollo GraphOS and the Apollo Router both support safelisted operations, and for self-hosted setups a hash allowlist checked in didResolveOperation works the same way. This does add operational overhead (every client change needs a registration step), which is why teams usually roll it out after rate and cost limits are already in place.

Query Timeouts and Payload Limits

Two limits people forget because they live outside GraphQL:

import express from "express";

const app = express();
app.use(express.json({ limit: "100kb" })); // reject multi-megabyte documents
app.use("/graphql", (req, res, next) => {
  req.setTimeout(10_000); // kill requests that run longer than 10s
  next();
});

Apollo Server doesn’t ship a per-query execution timeout — resolvers that hang on a slow database will hold the request open. Options: wrap expensive resolvers with Promise.race against a timeout, enforce statement timeouts at the database (statement_timeout in PostgreSQL), or terminate at the gateway (Envoy, NGINX, Apollo Router). Defense in depth means at least two of these, not zero.

Authentication and Authorization

Authentication in Context

Authenticate at the HTTP layer, not in resolvers. In Apollo Server 4, context is not a constructor option — it belongs to the integration middleware:

import { expressMiddleware } from "@apollo/server/express4";

await server.start();

app.use(
  "/graphql",
  express.json({ limit: "100kb" }),
  expressMiddleware(server, {
    context: async ({ req }) => {
      const token = req.headers.authorization?.replace("Bearer ", "");
      if (!token) return { user: null };
      try {
        return { user: await verifyToken(token) };
      } catch {
        return { user: null }; // invalid token → anonymous, resolvers decide
      }
    },
  }),
);

Putting auth in the schema instead (a login mutation that returns a session ID stored in a resolver-owned map, for example) splits your trust boundary and is the single most common GraphQL auth mistake in the wild.

Field-Level Authorization

Check permissions inside resolvers. Never rely on the client to avoid querying sensitive fields — the whole point of GraphQL is that clients construct arbitrary queries:

const resolvers = {
  User: {
    email: (user, _args, ctx) => {
      if (!ctx.user) throw new GraphQLError("Not authenticated");
      if (ctx.user.id !== user.id && ctx.user.role !== "ADMIN") {
        throw new GraphQLError("Not authorized to view email");
      }
      return user.email;
    },
    ssn: (user, _args, ctx) => {
      if (ctx.user?.role !== "ADMIN") {
        throw new GraphQLError("SSN requires admin access");
      }
      return user.ssn;
    },
  },
};

Schema Directives for Authorization

Declaring roles in the schema makes permissions visible and auditable. The modern @graphql-tools API is mapSchema + getDirective — the SchemaDirectiveVisitor class that older tutorials use was removed from graphql-tools v8 in 2021:

directive @auth(requires: Role!) on FIELD_DEFINITION

enum Role {
  ADMIN
  USER
  GUEST
}

type Query {
  adminDashboard: AdminDashboard @auth(requires: ADMIN)
  userSettings: UserSettings @auth(requires: USER)
}
import { mapSchema, getDirective, MapperKind } from "@graphql-tools/utils";
import { defaultFieldResolver, GraphQLError } from "graphql";

function authDirectiveTransformer(schema) {
  return mapSchema(schema, {
    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
      const authDirective = getDirective(schema, fieldConfig, "auth")?.[0];
      if (!authDirective) return fieldConfig;

      const requiredRole = authDirective.requires;
      const { resolve = defaultFieldResolver } = fieldConfig;

      fieldConfig.resolve = async (source, args, ctx, info) => {
        if (!ctx.user) throw new GraphQLError("Not authenticated");
        if (ctx.user.role !== requiredRole && ctx.user.role !== "ADMIN") {
          throw new GraphQLError(`Requires ${requiredRole} role`);
        }
        return resolve(source, args, ctx, info);
      };
      return fieldConfig;
    },
  });
}

const schema = authDirectiveTransformer(makeExecutableSchema({ typeDefs, resolvers }));
const server = new ApolloServer({ schema });

The full working version — including @owner directives and role hierarchies — is in Field-Level Auth with Custom GraphQL Schema Directives.

Injection Prevention

GraphQL doesn’t prevent injection. If a resolver passes client input to a database, the database decides what happens next.

// VULNERABLE: string concatenation
const resolvers = {
  Query: {
    userByName: (_root, { name }, ctx) =>
      ctx.db.query(`SELECT * FROM users WHERE name = '${name}'`),
  },
};

// SAFE: parameterized query — the driver escapes the value
const resolvers = {
  Query: {
    userByName: (_root, { name }, ctx) =>
      ctx.db.query("SELECT * FROM users WHERE name = $1", [name]),
  },
};

NoSQL needs the same discipline. A MongoDB find that receives { "email": { "$ne": null } } matches every document — classic operator injection:

// VULNERABLE: raw client input straight into the query
const resolvers = {
  Query: {
    search: (_root, { filter }, ctx) => ctx.db.users.find(filter).toArray(),
  },
};

// SAFE: whitelist allowed keys and drop everything else
const resolvers = {
  Query: {
    search: (_root, { filter }, ctx) => {
      const safeFilter = { name: filter.name, email: filter.email };
      Object.keys(safeFilter).forEach(
        (k) => safeFilter[k] === undefined && delete safeFilter[k],
      );
      return ctx.db.users.find(safeFilter).toArray();
    },
  },
};

Validating and constraining inputs at the schema edge is covered in detail in Validate and Sanitize GraphQL Input Types Server-Side.

Error Handling and Information Disclosure

Stack traces, ORM error messages, and file paths are reconnaissance data. Return generic errors with stable codes:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  includeStacktraceInErrorResponses: process.env.NODE_ENV !== "production",
  formatError: (formattedError, error) => {
    console.error(error); // full detail stays in server logs
    if (formattedError.extensions?.code === "INTERNAL_SERVER_ERROR") {
      return {
        message: "Internal server error",
        extensions: { code: "INTERNAL_SERVER_ERROR" },
      };
    }
    return formattedError;
  },
});

formatError still works in Apollo Server 4 but was removed in v5 in favor of plugin hooks (unexpectedErrorProcessingRequest / masking via didEncounterErrors) — if you’re already on v5, move this logic into a plugin. Either way, never echo user input back in error messages: “User with email alice@example.com not found” confirms the account exists. Return “User not found” and let support correlate the log.

Subscriptions and Other Transport Concerns

Subscriptions over WebSocket bypass every HTTP-layer control above. If you use graphql-ws, authenticate during the connection handshake — connectionParams — and re-validate on each operation, because a token issued at connect time may expire while the socket stays open. Field-level authorization still applies per emitted event.

Two more transport notes: Apollo Server 4 rejects GET mutations and requires non-simple request headers for cross-site requests by default (built-in CSRF protection) — don’t relax that. And file uploads aren’t part of @apollo/server core; if you add graphql-upload, enforce size and MIME limits separately or you’ve added an unauthenticated write path.

Common Mistakes

  • Trusting the client for field auth. Greying out ssn in the UI does nothing — the field is one introspection or guess away. Authorize in resolvers.
  • Rate limiting by IP only. Behind NATs and office networks, IPs are shared; per-identity budgets are the real control. And an in-memory Map resets on every deploy and doesn’t share state across instances — use Redis.
  • Detecting introspection by substring. query.includes("__schema") fires on string literals and comments. Inspect the parsed operation’s AST instead.
  • Disabling introspection but leaving field suggestions. The enumeration path stays open; set hideSchemaDetailsFromClientErrors too.
  • Treating depth limiting as complete protection. Depth 10 still allows users(first: 100000). Cost limits and pagination caps close the loop.
  • Hardening production, forgetting staging. A public staging environment with introspection on leaks the same schema, so gate it with the same controls as production.
  • Logging nothing. Without cost/depth rejection logs you’ll never see the attack that almost worked — wire onReject callbacks to your monitoring.

Production Hardening Checklist

If you only take five practices from this guide: disable introspection and field suggestions on public endpoints, cap depth and cost in validation, authenticate in context and authorize per field, parameterize every database call, and sanitize errors. The rest of the checklist covers the full hardening pass — work through it top to bottom and you’ll cover every threat in the attack surface table.

  • Introspection disabled in production, or gated behind admin auth via didResolveOperation
  • hideSchemaDetailsFromClientErrors: true to block field-suggestion enumeration
  • Depth limit set (typically 7-12, measured against your deepest legitimate query)
  • Cost/complexity limit with a real budget (@escape.tech/graphql-armor-cost-limit or equivalent)
  • Alias, directive, and token caps (maxAliases, maxDirectives, maxTokens)
  • maxRecursiveSelections enabled if clients use fragments heavily
  • Rate limiting per IP (shared store, e.g. Redis) and per client identity by cost
  • Batch size limited or allowBatchedHttpRequests: false (the AS4 default)
  • Persisted queries with bounded cache (ttl) or trusted-documents-only for public APIs
  • express.json({ limit }) body cap and request timeouts at server and database layers
  • Authentication in context via expressMiddleware, not in the schema
  • Field-level authorization on sensitive fields (resolver checks or @auth directive)
  • Parameterized queries and input whitelists on every database path
  • Errors sanitized: no stack traces, no echoed input, stable error codes
  • HTTPS enforced; CORS restricted to known origins (never * with credentials)
  • Subscription auth at handshake and per-operation
  • Rejection logging wired to monitoring (onReject, security event logs)

Further Reading

See Also

Frequently Asked Questions

Should I disable introspection in production?

Yes for public APIs. Introspection reveals your entire schema to anyone who can send a query — attackers use it to find sensitive fields and craft targeted requests. If internal tools need it, gate it behind admin authentication with a didResolveOperation plugin rather than leaving it open.

Is GraphQL less secure than REST?

Its attack surface is wider because it accepts arbitrary queries, while REST limits exposure through fixed endpoints. With depth limiting, cost analysis, field-level auth, and sanitized errors, GraphQL can be as secure as REST — but only if you add those controls deliberately, because none of them are REST defaults you inherit for free.

How do I prevent N+1 queries from being exploited?

Use DataLoader for batch loading so nested fields don't fan out into thousands of database calls. Cost analysis rejects queries that request many list fields, and depth limiting prevents recursive nesting. Together these defenses cover most N+1-based DoS attacks.

What is a persisted query?

A persisted query is registered on the server ahead of time: the client sends a sha256 hash instead of query text and the server looks up the stored document. This shrinks the attack surface to pre-approved operations only — the strongest posture for public APIs, at the cost of a registration step on every client change.

How do I handle CORS for GraphQL?

Restrict CORS to the origins your clients actually use, and never combine Access-Control-Allow-Origin: * with credentials — that pair lets any website ride a user's session:

import cors from "cors";

app.use(
  "/graphql",
  cors({
    origin: ["https://app.example.com", "https://admin.example.com"],
    credentials: true,
  }),
);
Should I use a WAF for GraphQL?

Yes, if the endpoint is public. A GraphQL-aware WAF (Cloudflare GraphQL Protection, AWS WAF) can block malformed or malicious operations before they reach your server. Look for one that understands operation types, depth, and complexity — a generic HTTP WAF can't tell a deep query from a cheap one.