0
0
GraphqlHow-ToBeginner · 3 min read

How to Use @external Directive in GraphQL for Federation

Use the @external directive in GraphQL federation to mark fields that are defined in another service but referenced in your local schema. It allows you to extend types by indicating which fields come from external schemas, enabling schema stitching across services.
📐

Syntax

The @external directive is used on fields inside an extend type to mark them as coming from another service. This tells the GraphQL gateway that the field is not resolved locally but exists in a different federated service.

Basic syntax:

extend type TypeName {
  fieldName: FieldType @external
}

Here, TypeName is the type you want to extend, fieldName is the field from another service, and @external marks it as external.

graphql
extend type Product {
  upc: String! @external
}
💻

Example

This example shows how to extend a Product type by referencing an external field upc from another service. The @external directive marks upc as defined elsewhere, allowing you to add a new local field price.

graphql
extend type Product {
  upc: String! @external
  price: Int
}

# This schema assumes 'upc' is defined in another federated service.
# 'price' is resolved locally here.
⚠️

Common Pitfalls

  • Not using @external on fields that come from other services causes schema validation errors.
  • Forgetting to use extend type when adding external fields leads to conflicts with original type definitions.
  • Using @external on fields that are actually resolved locally can cause unexpected behavior.

Correct usage requires marking only fields from other services and extending the type properly.

graphql
type Product {
  upc: String!  # Wrong: should be @external and use extend
  price: Int
}

# Correct:
extend type Product {
  upc: String! @external
  price: Int
}
📊

Quick Reference

DirectivePurposeUsage Context
@externalMarks a field as defined in another federated serviceUsed on fields inside extend type
extend typeAdds fields to an existing type from another serviceUsed to extend types with external fields
@keyDefines the primary key for a federated typeUsed on base types to identify entities

Key Takeaways

Use @external only on fields defined in other federated services.
Always use extend type when adding external fields to a type.
Do not mark locally resolved fields with @external.
@external helps GraphQL federation stitch schemas across services.
Combine @external with @key and other federation directives for full schema federation.