0
0
GraphQLquery~5 mins

Field-level permissions in GraphQL

Choose your learning style9 modes available
Introduction

Field-level permissions control who can see or change specific pieces of data in a database. This keeps sensitive information safe.

When you want only managers to see employee salaries.
When users should only update their own profile information.
When some data fields are private and should not be shown to all users.
When you want to hide certain fields from public API responses.
When different roles have different access to parts of the data.
Syntax
GraphQL
type User {
  id: ID!
  name: String!
  email: String! @auth(requires: USER)
  salary: Float @auth(requires: ADMIN)
}
Use directives like @auth to specify who can access each field.
Permissions can be set per field to allow fine control.
Examples
Only logged-in users can see the email field.
GraphQL
type User {
  id: ID!
  name: String!
  email: String! @auth(requires: USER)
}
Only admins can see the salary field.
GraphQL
type User {
  id: ID!
  name: String!
  salary: Float @auth(requires: ADMIN)
}
Only the author can see the content field.
GraphQL
type Post {
  id: ID!
  title: String!
  content: String! @auth(requires: AUTHOR)
}
Sample Program

This query tries to get user details including email and salary. The email is visible to users with USER role, salary only to ADMIN role.

GraphQL
type User {
  id: ID!
  name: String!
  email: String! @auth(requires: USER)
  salary: Float @auth(requires: ADMIN)
}

query GetUser {
  user(id: "1") {
    id
    name
    email
    salary
  }
}
OutputSuccess
Important Notes

Field-level permissions help protect sensitive data without hiding the whole record.

Permissions are often based on user roles or ownership.

Always test your permissions to avoid accidental data leaks.

Summary

Field-level permissions control access to individual data fields.

They help keep sensitive information safe.

Use directives or rules to set who can see or edit each field.