GraphQL Yoga v4 documentation (superseded by v5): Learn how to use GraphQL Yoga with Apollo Federation to build a gateway server and a federated service.
Apollo Federation is a specification that applies
microservice architecture through GraphQL APIs.
bun add @apollo/gateway @envelop/apollo-federation graphql-yoga graphql@15
Example Gateway
import { createServer } from 'http'import { createYoga } from 'graphql-yoga'import { ApolloGateway } from '@apollo/gateway'import { useApolloFederation } from '@envelop/apollo-federation'// Initialize the gatewayconst gateway = new ApolloGateway({ serviceList: [ { name: 'accounts', url: 'http://localhost:4001' }, { name: 'products', url: 'http://localhost:4002' } // ...additional subgraphs... ]})// Make sure all services are loadedawait gateway.load()const yoga = createYoga({ plugins: [ useApolloFederation({ gateway }) ]})// Start the server and explore http://localhost:4000/graphqlconst server = createServer(yoga)server.listen(4000, () => { console.info('Server is running on http://localhost:4000/graphql')})
Handling Subgraph Errors
By default, GraphQL Yoga masks any unexpected GraphQL Errors. This is done to prevent leaking
internal errors to the client. If you know that your subgraph is safe and you want to expose the
errors to the client, you can customize the error masking bahviour.
bun add graphql-yoga @graphql-yoga/plugin-apollo-inline-trace graphql
Example Federated tracing
import { createServer } from 'http'import { createYoga } from 'graphql-yoga'import { useApolloInlineTrace } from '@graphql-yoga/plugin-apollo-inline-trace'const yoga = createYoga({ plugins: [ useApolloInlineTrace() // ...rest of your Apollo federation plugins ]})// Start the server and explore http://localhost:4000/graphqlconst server = createServer(yoga)server.listen(4000, () => { console.info('Server is running on http://localhost:4000/graphql')})