GraphiQL in Production: Security and Introspection

GraphiQL is wonderful while you build an API. But what happens when you deploy? Should the page stay on? What about introspection? Can someone abuse your endpoint with a huge query?

This post answers those questions. We will look at GraphiQL in production: what to turn off, what to limit, and which tools to use instead. Everything here is shown with Spring Boot and Spring for GraphQL.

Table of Contents

The Short Answer

For most teams, the answer is simple: do not expose the stock GraphiQL page in production.

The Spring documentation says clearly that the stock integration is intended for development only. It loads its static resources from the esm.sh CDN and does not require any authentication to access the GraphQL API it targets. Before putting a GraphiQL page in production, you should review your security model, decide whether an unauthenticated, CDN-dependent IDE is acceptable, and protect access with the same authentication and authorization as the rest of your application.

If your team really needs an in-browser explorer in production, build a custom page and protect it. If not, switch it off and use another tool from your own computer.

What Can Go Wrong?

Here are the main risks, in plain words.

1. Anyone can learn your schema

GraphiQL works through introspection, which lets a client ask the server for every type and field. That is great for you and also great for an attacker. The OWASP GraphQL guidance says to disable introspection queries system-wide in any production or publicly accessible environment. For internal APIs, it says the easiest approach is to disable introspection altogether.

2. Field suggestions leak names

Even without introspection, some servers answer a mistyped field with a "did you mean...?" message. OWASP's testing guide says to disable field suggestions in production as well, because they independently allow schema enumeration. We will check this in the test step.

3. Expensive queries

GraphQL lets a client build deeply nested queries. For example, a book has an author, the author has books, each book has an author, and so on. One request can ask for a lot of work. OWASP recommends limiting the maximum depth of allowed queries to prevent abuse of resources.

4. Unprotected tools

If the page or the schema printer is reachable without a login, you have given strangers a free map and a free test console.

5. CDN dependency

The stock page pulls scripts from a third-party CDN. If that CDN is blocked or compromised, your page breaks or runs code you did not review.

Remember that hiding the schema is not real security. The real protection is authentication, authorization, and limits. Hiding the schema just makes an attacker's job harder.

Step 1: Use Profiles

The cleanest approach is to turn tools on only in development. Keep your main application.yml safe, and add development extras in a separate file.

application.yml (safe defaults)

spring:
  graphql:
    graphiql:
      enabled: false
    schema:
      printer:
        enabled: false
      introspection:
        enabled: false

application-dev.yml (developer extras)

spring:
  graphql:
    graphiql:
      enabled: true
    schema:
      printer:
        enabled: true
      introspection:
        enabled: true

Now run locally with the dev profile:

./mvnw spring-boot:run -Dspring-boot.run.profiles=dev

And in production, run without it, or explicitly use a production profile:

java -jar app.jar --spring.profiles.active=prod

A word about DevTools

Spring Boot exposes the GraphiQL page automatically when spring-boot-devtools is present, because the stock page is very useful during development. DevTools is meant for development, and Spring Boot disables it when an application runs as a fully packaged jar. Still, do not rely on that alone. Keep the explicit false setting for production, so the behavior is clear to everyone.

Step 2: Disable Introspection

Spring Boot allows introspection by default, because tools such as GraphiQL need it. To turn it off, set this property:

spring.graphql.schema.introspection.enabled=false

After that, a query like this no longer returns the schema:

query {
  __schema {
    types {
      name
    }
  }
}

Your real application queries keep working. Only the introspection feature is disabled.

What breaks when introspection is off?

  • GraphiQL cannot build documentation or autocomplete.
  • Some code generators and client tools that read the schema from the live server will fail.
  • Front-end teams need the schema from somewhere else, such as a file in your repository.

The fix for the last point is easy. Keep your .graphqls files in version control and share them with client teams, or use the schema printer in a development environment.

Public APIs are a special case

If your API is public and meant for outside developers, such as a partner or open API, introspection can be part of your product. In that case, you may keep it on, but you should then rely even more on authentication, rate limits, and query limits.

Step 3: Limit Depth and Complexity

GraphQL Java ships two ready-made instrumentation classes for this. MaxQueryDepthInstrumentation aborts a query when its depth exceeds a limit. MaxQueryComplexityInstrumentation aborts a query when the total number of fields exceeds a limit.

An example of a deep query

Imagine the schema also lets an author list their books. A client could write this:

query {
  books {
    author {
      books {
        author {
          books {
            author {
              books {
                name
              }
            }
          }
        }
      }
    }
  }
}

Each level multiplies the work. With a limit on depth, the server refuses this query before running it.

Register the limits in Spring Boot

You can add instrumentation through a GraphQlSourceBuilderCustomizer bean. This is the same kind of customizer that the Spring Boot documentation uses for runtime wiring changes.

import graphql.analysis.MaxQueryComplexityInstrumentation;
import graphql.analysis.MaxQueryDepthInstrumentation;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class GraphQlLimitsConfig {

    @Bean
    GraphQlSourceBuilderCustomizer queryLimits() {
        return builder -> builder.instrumentation(List.of(
            new MaxQueryDepthInstrumentation(10),
            new MaxQueryComplexityInstrumentation(200)
        ));
    }
}

The package name of GraphQlSourceBuilderCustomizer has changed between Spring Boot versions. If the import above does not compile in your project, let your IDE find the class, or check the Spring Boot API documentation for your version.

Choosing the numbers

  • Look at your real queries. Find the deepest legitimate query your front end sends.
  • Set the limit a little above that value, not far above it.
  • Log rejected queries for a while, so you can spot false alarms.

The values 10 and 200 are only examples. There is no universal number.

Other limits worth adding

  • Pagination limits: never return an unlimited list. Cap page sizes on the server.
  • Request size limits: limit the maximum size of the request body in your web server settings.
  • Timeouts: stop long-running queries.
  • Rate limiting: apply it at your gateway or with a filter, per user or per API key.

Step 4: Require Authentication

This is the most important step. The Spring documentation says the path to the GraphQL endpoint can be secured with HTTP URL security so that only authenticated users can reach it. It also says this does not tell different GraphQL requests apart, so for finer control you add Spring Security annotations such as @PreAuthorize or @Secured to the service methods that fetch specific parts of the response.

A good production setup looks like this:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
        throws Exception {

    http
        .authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/graphql").authenticated()
            .anyRequest().denyAll()
        )
        .oauth2ResourceServer(oauth2 ->
            oauth2.jwt(Customizer.withDefaults())
        );

    return http.build();
}

Notice the denyAll() at the end. The schema printer, GraphiQL path, and anything else you forgot about are blocked by default. This is called a deny-by-default rule, and it protects you from mistakes.

If you really need GraphiQL in production

Sometimes a support team or partner needs an explorer. If so, take these steps:

  1. Build a custom GraphiQL page instead of using the stock one, so no CDN code is loaded.
  2. Serve it behind your normal login, with the same rules as the rest of the app.
  3. Restrict it by role, for example only for an internal developer group.
  4. Keep depth, complexity, and rate limits on.
  5. Log who uses it.

Step 5: Hide Internal Errors

Error messages can leak details such as class names, SQL, or file paths. Make sure unexpected exceptions return a safe, general message, and handle expected problems yourself.

import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import org.springframework.graphql.data.method.annotation.GraphQlExceptionHandler;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.web.bind.annotation.ControllerAdvice;

@ControllerAdvice
public class GraphQlErrorAdvice {

    @GraphQlExceptionHandler
    public GraphQLError handleNotFound(
            GraphqlErrorBuilder<?> errorBuilder,
            BookNotFoundException ex) {

        return errorBuilder
            .errorType(ErrorType.NOT_FOUND)
            .message("Book not found")
            .build();
    }
}

The point is to write messages for users on purpose, and to log the technical details on the server where only your team can read them.

Step 6: Check Your Setup

Never assume your production settings work. Test them from the outside, using curl, with the production profile on.

Is the GraphiQL page gone?

curl -i https://api.example.com/graphiql

You should see a 401, 403, or 404 response, not the page.

Is the schema printer gone?

curl -i https://api.example.com/graphql/schema

Is introspection off?

curl -X POST https://api.example.com/graphql \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { types { name } } }"}'

The response should contain an error and no list of types.

Do field suggestions leak names?

curl -X POST https://api.example.com/graphql \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query":"{ bookz { id } }"}'

Read the error message. If it suggests a real field name, such as "Did you mean books?", your server is helping people guess your schema. OWASP advises disabling these suggestions in production. How you do that depends on your GraphQL Java version, so check its documentation for the option available to you.

Are deep queries rejected?

Send a query that is deeper than your limit and confirm that you get an error instead of data.

Is an anonymous request rejected?

curl -i -X POST https://api.example.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ books { id } }"}'

Without a token, you should get a 401 response.

Automate it

Put these checks in your deployment pipeline, so a wrong setting is found before users find it.

GraphiQL Alternatives

If you switch GraphiQL off in production, you can still explore the API from your own machine. Here is how the common tools compare.

Tool Best for Things to know
GraphiQL Embedded explorer inside your own app or docs Free and open source, maintained under the GraphQL Foundation, easy to customize
Postman Teams that keep REST and GraphQL requests together Supports shared collections and team workflows
Apollo Sandbox Teams using the Apollo platform Browser-based and free without an account, but some features, such as schema history, are not included
Altair A standalone client that works with any server A good option when you do not want to embed anything in your app
Insomnia Developers who prefer a desktop client Similar to Postman, with a focus on API design and testing

The nice thing about desktop clients is that they run on your machine and talk to your API with your own token. Nothing extra is hosted on your server, so there is less to secure.

For automated tests, use code

No browser tool replaces automated tests. Spring for GraphQL has test helpers in the spring-graphql-test artifact. The official guide shows a @GraphQlTest slice test that focuses on a single controller:

@GraphQlTest(BookController.class)
class BookControllerTests {

    @Autowired
    private GraphQlTester graphQlTester;

    @Test
    void shouldGetFirstBook() {
        graphQlTester
            .document("{ bookById(id: \"book-1\") { name } }")
            .execute()
            .path("bookById.name")
            .entity(String.class)
            .isEqualTo("Effective Java");
    }
}

In your own project, a controller slice test may need extra beans, such as a mocked BookService. Add them with @MockitoBean or your preferred approach for your Spring Boot version.

Production Checklist

  • GraphiQL page is disabled in production.
  • Schema printer is disabled in production.
  • Introspection is disabled, unless your API is public on purpose.
  • Field suggestions are checked and, if possible, disabled.
  • /graphql requires authentication.
  • Everything else is denied by default.
  • Sensitive operations use method security.
  • Query depth and complexity are limited.
  • Page sizes are capped on the server.
  • Request size, timeouts, and rate limits are set.
  • Error messages hide internal details.
  • CORS lists exact origins only.
  • A custom GraphiQL page, if used, sits behind your login.
  • Production settings are tested with curl in your pipeline.

Common Mistakes

  • Relying on DevTools to hide the page: set the properties explicitly.
  • Disabling introspection and calling it done: it only hides the map. You still need authentication and limits.
  • Forgetting the schema printer: it shows the whole schema as plain text.
  • Copying dev CORS rules to production: wide-open origins are risky.
  • Setting limits too low: real front-end queries start failing. Measure first.
  • No limit on list sizes: one request can still ask for millions of rows.
  • Trusting the client: always check permissions on the server.

FAQs

Should I use GraphiQL in production?

Usually not. The stock page is for development only. If you need an explorer in production, build a custom page and protect it with your normal authentication and authorization.

How do I disable GraphiQL in Spring Boot?

Set spring.graphql.graphiql.enabled=false. The page is off by default, but setting the value explicitly makes the intent clear and protects you from DevTools exposing it by accident.

How do I disable introspection in Spring Boot?

Set spring.graphql.schema.introspection.enabled=false. Spring Boot allows introspection by default because tools like GraphiQL need it.

Is disabling introspection enough to secure my API?

No. It only makes the schema harder to discover. You also need authentication, authorization, query limits, and good error handling.

How do I limit query depth in Spring Boot?

Register GraphQL Java's MaxQueryDepthInstrumentation, for example with a GraphQlSourceBuilderCustomizer bean. Use MaxQueryComplexityInstrumentation to limit the total number of fields.

What is the best GraphiQL alternative?

It depends on your team. Postman suits teams that already use it for REST. Apollo Sandbox suits Apollo users. Altair and Insomnia are good standalone clients.

Does turning off introspection break my app?

Normal queries keep working. Tools that read your schema from the live server, such as GraphiQL's explorer and some code generators, stop working. Share the schema files instead.

Can I keep the schema printer on in production?

It is better not to. It exposes your full schema as text. Use it in development and keep it off in production, or protect it like any other sensitive endpoint.

Final Thoughts

GraphiQL is a development tool, and in production the safest default is to switch it off. Disable the page and the schema printer, turn off introspection unless your API is public, and put real protection in front of /graphql: authentication, authorization, and query limits.

Then test the result from the outside, with curl, as part of your pipeline. Developers can keep exploring the API from a desktop client or a development profile, and your production server stays quiet.

Comments