0
0
GraphQLquery~5 mins

Schema visibility control in GraphQL

Choose your learning style9 modes available
Introduction

Schema visibility control helps decide which parts of a GraphQL schema users can see or use. It keeps data safe and organized.

When you want to hide some fields from certain users for privacy.
When you want to show only specific queries or mutations to different user roles.
When you want to limit access to sensitive data in a public API.
When you want to simplify the schema for beginner users by hiding advanced features.
When you want to control which parts of the schema are available during development or testing.
Syntax
GraphQL
type Query {
  visibleField: String
  hiddenField: String @deprecated(reason: "Hidden from users")
}

# Or use schema directives or middleware to control visibility
GraphQL itself does not have built-in visibility control, so you use directives or server logic.
You can use custom directives or middleware to hide or show fields based on user roles.
Examples
This example uses a custom @auth directive to show privateData only to logged-in users.
GraphQL
type Query {
  publicData: String
  privateData: String @auth(requires: USER)
}
This example marks a field as deprecated to discourage its use, which can help hide it gradually.
GraphQL
directive @deprecated(reason: String) on FIELD_DEFINITION

type Query {
  oldField: String @deprecated(reason: "Use newField instead")
  newField: String
}
Sample Program

This schema defines an @auth directive to control who can see secretInfo. Only ADMIN users can access it.

GraphQL
directive @auth(requires: Role = USER) on FIELD_DEFINITION

enum Role {
  ADMIN
  USER
  GUEST
}

type Query {
  publicInfo: String
  secretInfo: String @auth(requires: ADMIN)
}

# Server logic checks user role before resolving secretInfo
OutputSuccess
Important Notes

GraphQL does not enforce visibility by itself; you must add logic in your server code.

Use directives or middleware to check user roles or permissions before returning data.

Hiding fields improves security and user experience by showing only relevant data.

Summary

Schema visibility control limits what users can see or use in a GraphQL schema.

It is done using directives or server-side logic, not built-in GraphQL features.

This helps protect sensitive data and tailor the API to different user needs.