Shared types let different parts of a GraphQL system use the same data shapes. This helps keep data consistent and easy to manage.
Shared types across subgraphs in GraphQL
extend type User @key(fields: "id") { id: ID! @external username: String } # In another subgraph extend type User @key(fields: "id") { id: ID! email: String }
@key marks the field(s) used to identify the shared type.
@external marks fields that exist in another subgraph.
upc. The price field is added in this subgraph.extend type Product @key(fields: "upc") { upc: String! @external price: Int }
id. The name field is defined in this subgraph.extend type User @key(fields: "id") { id: ID! @external name: String }
type Review @key(fields: "id") { id: ID! body: String author: User @provides(fields: "username") }
This example shows two subgraphs sharing the User type. Subgraph A knows username, Subgraph B knows email. Both use id to identify the same User.
# Subgraph A schema extend type User @key(fields: "id") { id: ID! @external username: String } # Subgraph B schema extend type User @key(fields: "id") { id: ID! email: String } type Query { me: User }
Shared types use @key to identify the unique field(s) that link the same type across subgraphs.
Fields marked @external are defined in other subgraphs and not stored locally.
Using shared types helps avoid duplication and keeps data consistent across services.
Shared types let multiple subgraphs use the same data structure identified by unique keys.
Use @key to mark the identifying fields and @external for fields from other subgraphs.
This approach helps build a unified GraphQL API from multiple services easily.