0
0
GraphQLquery~5 mins

Shared types across subgraphs in GraphQL

Choose your learning style9 modes available
Introduction

Shared types let different parts of a GraphQL system use the same data shapes. This helps keep data consistent and easy to manage.

When multiple teams build different parts of a GraphQL API but need to use the same user or product data.
When you want to avoid repeating the same type definitions in different subgraphs.
When you want to combine data from different services into one API without conflicts.
When you want to update a shared type once and have all subgraphs use the new version.
When you want to make sure queries across subgraphs understand the same data structure.
Syntax
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.

Examples
This shows a shared Product type identified by upc. The price field is added in this subgraph.
GraphQL
extend type Product @key(fields: "upc") {
  upc: String! @external
  price: Int
}
Here, the User type is shared by id. The name field is defined in this subgraph.
GraphQL
extend type User @key(fields: "id") {
  id: ID! @external
  name: String
}
This defines a Review type with a shared User type as author, showing how types can reference each other across subgraphs.
GraphQL
type Review @key(fields: "id") {
  id: ID!
  body: String
  author: User @provides(fields: "username")
}
Sample Program

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.

GraphQL
# 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
}
OutputSuccess
Important Notes

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.

Summary

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.