0
0
GraphqlHow-ToBeginner · 3 min read

How to Use @deprecated Directive in GraphQL: Syntax and Examples

In GraphQL, use the @deprecated directive to mark fields or enum values as outdated. Add @deprecated(reason: "your reason") after the field or enum value to inform clients about the deprecation and optionally provide a reason.
📐

Syntax

The @deprecated directive is added after a field or enum value in your GraphQL schema. You can optionally provide a reason argument to explain why it is deprecated.

  • Without reason: Marks the element as deprecated without explanation.
  • With reason: Provides a message to guide clients on what to use instead.
graphql
type ExampleType {
  oldField: String @deprecated
  olderField: Int @deprecated(reason: "Use 'newField' instead")
}
enum Status {
  ACTIVE
  INACTIVE @deprecated(reason: "Use DISABLED instead")
  DISABLED
}
💻

Example

This example shows a GraphQL schema where a field and an enum value are marked as deprecated with reasons. Clients querying this schema will see deprecation warnings and can update their queries accordingly.

graphql
type Query {
  user: User
}

type User {
  id: ID!
  username: String
  email: String @deprecated(reason: "Use 'contactEmail' instead")
  contactEmail: String
}
enum Role {
  ADMIN
  USER
  GUEST @deprecated(reason: "Guests are no longer supported")
}
Output
When introspecting the schema, clients see the 'email' field and 'GUEST' enum value marked as deprecated with their reasons.
⚠️

Common Pitfalls

Common mistakes when using @deprecated include:

  • Not providing a reason, which leaves clients guessing why the field is deprecated.
  • Deprecating fields without offering alternatives, causing confusion.
  • Forgetting to update client queries after deprecation, leading to runtime errors.

Always provide a clear reason and suggest alternatives if possible.

graphql
type Product {
  price: Float @deprecated
  cost: Float
}

# Better approach:
# type Product {
#   price: Float @deprecated(reason: "Use 'cost' instead")
#   cost: Float
# }
📊

Quick Reference

Directive UsageDescription
@deprecatedMarks a field or enum value as deprecated without a reason
@deprecated(reason: "message")Marks as deprecated with an explanation for clients
Use on fields or enum valuesCannot be used on types or input fields
Provide clear reasonsHelps clients migrate away from deprecated elements

Key Takeaways

Use @deprecated to mark outdated fields or enum values in GraphQL schemas.
Always provide a reason to explain why the element is deprecated.
Deprecation helps clients know what to avoid and what to use instead.
Do not forget to update client queries after deprecation to prevent errors.
The @deprecated directive works only on fields and enum values, not on types.