On this page
← All product updates

Federation Contexts in Native Composition

Kamil Kisiela
Kamil Kisiela

Hive’s native Federation composition now supports contextual arguments through the @context and @fromContext directives.

Contexts solve a common problem in federated schemas - a deeply nested field sometimes needs data from one of its ancestors.

Without contexts, passing this data through the graph can require adding extra fields to entity @keys. This makes types and subgraphs depend on data they don’t otherwise need.

With contexts, a type can make data available to fields further down the query without exposing that data as arguments in the public API.

A type can provide context using @context:

type Product @key(fields: "id") @context(name: "productContext") {
  id: ID!
  currency: String!
}

A nested field can then read a value from that context using @fromContext:

type Product @key(fields: "id") {
  id: ID!
  price(
    currency: String @fromContext(field: "$productContext { currency }")
  ): Money!
}

Here, Product provides the $productContext. When the router resolves Pricing.price, it takes the currency value from the closest $productContext and passes it to the field.

The currency argument isn’t part of the public API schema. Clients simply query price, while the router provides the value behind the scenes.

Native composition support

With @theguild/federation-composition v0.26.0, Hive’s native composition understands these directives and checks that contexts are used correctly during schema composition.

Schemas using @context and @fromContext can now be published, checked and composed with Hive’s native composition.