Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Theme
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Create API Key
Add Docs
Hive Gateway
https://github.com/graphql-hive/gateway
Admin
A fully open-source MIT-licensed GraphQL API gateway that acts as a federation or proxy gateway for
...
Tokens:
12,222
Snippets:
101
Trust Score:
7.7
Update:
1 month ago
Context
Skills
Chat
Benchmark
64.2
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Hive Gateway Hive Gateway is a fully open-source MIT-licensed GraphQL API gateway that can act as a GraphQL Federation Gateway or a Proxy Gateway for any GraphQL services. It provides a unified entry point for federated GraphQL architectures, handling query planning, execution across multiple subgraphs, and advanced features like authentication, caching, and observability. The gateway can be run as a standalone binary, a Docker image, or as a JavaScript package that works with Node.js, Bun, Deno, Google Cloud Functions, Azure Functions, or Cloudflare Workers. It seamlessly integrates with Apollo Federation and supports both Federation v1 and v2 specifications, making it an ideal choice for organizations looking to adopt or migrate to a federated GraphQL architecture. ## Core APIs and Functions ### createGatewayRuntime - Create Gateway Runtime Instance The `createGatewayRuntime` function creates a gateway runtime instance that handles GraphQL operations. It accepts configuration for supergraph federation, proxy mode, or subgraph serving, and returns a Yoga server instance with additional gateway-specific methods. ```typescript import { createGatewayRuntime } from '@graphql-hive/gateway-runtime'; // Federation Supergraph Mode const gateway = createGatewayRuntime({ supergraph: './supergraph.graphql', // or URL or SDL string pollingInterval: 10000, // Poll for schema updates every 10s plugins: (ctx) => [ // Add custom plugins ], }); // Proxy Mode - Forward requests to existing GraphQL endpoint const proxyGateway = createGatewayRuntime({ proxy: { endpoint: 'https://api.example.com/graphql', }, schema: './schema.graphql', // Optional local schema }); // Start the server const server = await gateway.listen(4000); console.log('Gateway running at http://localhost:4000/graphql'); // Access gateway methods const schema = await gateway.getSchema(); gateway.invalidateUnifiedGraph(); // Force schema refresh ``` ### defineConfig - Type-Safe Gateway Configuration The `defineConfig` function provides a type-safe way to define gateway configuration in a separate configuration file. It supports supergraph, subgraph, and proxy modes with full TypeScript inference. ```typescript // gateway.config.ts import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ // Supergraph from Hive CDN supergraph: { type: 'hive', endpoint: process.env.HIVE_CDN_ENDPOINT!, key: process.env.HIVE_CDN_KEY!, }, // Schema polling pollingInterval: 30000, // Built-in features graphqlEndpoint: '/graphql', healthCheckEndpoint: '/healthcheck', readinessCheckEndpoint: '/readiness', // Response caching responseCaching: { ttl: 2000, includeExtensionMetadata: true, }, // Security features maskedErrors: true, csrfPrevention: true, // Performance features executionCancellation: true, upstreamCancellation: true, deferStream: true, batching: { limit: 10 }, }); ``` ### CLI Commands - Run Gateway from Command Line The Hive Gateway CLI provides commands to run the gateway in different modes. It supports environment variables and command-line options for configuration. ```bash # Run with supergraph file hive-gateway supergraph ./supergraph.graphql # Run with Hive CDN hive-gateway supergraph \ --hive-cdn-endpoint $HIVE_CDN_ENDPOINT \ --hive-cdn-key $HIVE_CDN_KEY # Run in proxy mode hive-gateway proxy https://api.example.com/graphql # Run with Apollo GraphOS hive-gateway supergraph \ --apollo-graph-ref my-graph@production \ --apollo-key $APOLLO_KEY # Common options hive-gateway supergraph ./supergraph.graphql \ --host 0.0.0.0 \ --port 4000 \ --fork 4 \ --polling 30s \ --jit \ --opentelemetry http://jaeger:4318/v1/traces ``` ### Transport Configuration - Configure Subgraph Communication Transport entries configure how the gateway communicates with each subgraph, including HTTP options, WebSocket subscriptions, and custom headers. ```typescript import { defineConfig, WSTransportOptions, HTTPCallbackTransportOptions } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ transportEntries: { // Configure specific subgraph products: { options: { subscriptions: { kind: 'ws', location: '/subscriptions', options: { connectionParams: { token: '{context.headers.authorization}', }, } satisfies WSTransportOptions, }, }, }, // Configure all HTTP subgraphs with wildcard '*.http': { headers: [['user-agent', 'hive-gateway/1.0']], options: { timeout: 30000, retry: 3, }, }, // HTTP callback subscriptions (webhooks) reviews: { options: { subscriptions: { kind: 'http-callback', options: { public_url: process.env.PUBLIC_URL, } satisfies HTTPCallbackTransportOptions, }, }, }, }, }); ``` ### useJWT - JWT Authentication Plugin The JWT authentication plugin validates JWT tokens, extracts claims, and optionally forwards token information to subgraphs. It supports multiple signing key providers including remote JWKS endpoints. ```typescript import { defineConfig, createInlineSigningKeyProvider, createRemoteJwksSigningKeyProvider, } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ jwt: { // Token extraction from headers or cookies tokenLookupLocations: [ extractFromHeader({ name: 'Authorization', prefix: 'Bearer ' }), extractFromCookie({ name: 'auth_token' }), ], // Signing key providers signingKeyProviders: [ createInlineSigningKeyProvider(process.env.JWT_SECRET!), createRemoteJwksSigningKeyProvider({ jwksUri: 'https://auth.example.com/.well-known/jwks.json', }), ], // Forward JWT to subgraphs forward: { payload: true, // Forward decoded payload token: false, // Don't forward raw token extensionsFieldName: 'jwt', }, // Rejection behavior reject: { missingToken: false, // Allow anonymous requests invalidToken: true, // Reject invalid tokens }, }, }); // Access JWT in resolvers via context // context.jwt.payload contains the decoded token claims ``` ### usePropagateHeaders - Header Propagation Plugin The header propagation plugin allows forwarding headers from client requests to subgraphs and from subgraph responses back to clients. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ propagateHeaders: { // Propagate headers from client to subgraphs fromClientToSubgraphs({ context, request, subgraphName }) { return { 'x-request-id': context.headers['x-request-id'], 'x-user-id': context.headers['x-user-id'], 'authorization': request.headers.get('authorization'), }; }, // Propagate headers from subgraphs to client fromSubgraphsToClient({ response, subgraphName }) { return { 'x-served-by': response.headers.get('x-served-by'), 'x-cache-status': response.headers.get('x-cache-status'), }; }, // Deduplicate headers from multiple subgraphs deduplicateHeaders: true, }, }); ``` ### useUpstreamRetry - Retry Failed Requests The upstream retry plugin automatically retries failed subgraph requests with configurable backoff strategies. It handles network errors, rate limiting, and transient failures. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ upstreamRetry: { maxRetries: 3, retryDelay: 1000, // Initial delay in ms retryDelayFactor: 1.5, // Exponential backoff factor // Custom retry logic shouldRetry({ response, executionResult, executionRequest }) { // Retry on 5xx errors or rate limiting if (response?.status >= 500 || response?.status === 429) { return true; } // Retry on network errors if (executionResult?.errors?.some(e => e.message.includes('ECONNREFUSED'))) { return true; } return false; }, }, // Per-subgraph configuration upstreamRetry: ({ subgraphName }) => { if (subgraphName === 'critical-service') { return { maxRetries: 5, retryDelay: 500 }; } return { maxRetries: 2 }; }, }); ``` ### useUpstreamTimeout - Request Timeout Configuration The upstream timeout plugin sets timeouts for subgraph requests to prevent long-running operations from blocking the gateway. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ // Global timeout in milliseconds upstreamTimeout: 30000, // Or per-subgraph configuration upstreamTimeout: ({ subgraphName, executionRequest }) => { // Longer timeout for batch operations if (executionRequest.operationType === 'mutation') { return 60000; } // Quick timeout for fast services if (subgraphName === 'cache-service') { return 5000; } return 30000; }, }); ``` ### usePrometheus - Prometheus Metrics Plugin The Prometheus plugin exposes metrics for monitoring gateway performance including request duration, error rates, and subgraph execution times. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ prometheus: { endpoint: '/metrics', metrics: { graphql_envelop_request: true, graphql_envelop_request_duration: true, graphql_envelop_error_result: true, graphql_gateway_fetch_duration: true, graphql_gateway_subgraph_execute_duration: true, graphql_gateway_subgraph_execute_errors: true, }, labels: { subgraphName: true, fetchRequestHeaders: ['x-request-id'], fetchResponseHeaders: ['x-cache-status'], }, }, }); // Metrics exposed at /metrics endpoint: // graphql_gateway_fetch_duration_seconds{url="...",method="POST",statusCode="200"} // graphql_gateway_subgraph_execute_duration_seconds{subgraphName="products"} // graphql_gateway_subgraph_execute_errors_total{subgraphName="products"} ``` ### OpenTelemetry Integration - Distributed Tracing The gateway supports OpenTelemetry for distributed tracing, allowing you to trace requests across the gateway and all subgraphs. ```typescript // gateway.config.ts import { defineConfig } from '@graphql-hive/gateway'; import { trace } from '@graphql-hive/gateway/opentelemetry/api'; import { openTelemetrySetup } from '@graphql-hive/gateway/opentelemetry/setup'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; // Setup OpenTelemetry openTelemetrySetup({ traces: { exporter: new OTLPTraceExporter({ url: 'http://jaeger:4318/v1/traces', }), }, }); export const gatewayConfig = defineConfig({ openTelemetry: { traces: true, }, plugins: () => [ { onExecute() { // Add custom span attributes trace.getActiveSpan()?.setAttribute('custom.attribute', 'value'); }, }, ], }); // Or via CLI // hive-gateway supergraph --opentelemetry http://jaeger:4318/v1/traces ``` ### HMAC Signature - Upstream Request Signing The HMAC signature plugin signs outgoing requests to subgraphs for authentication and integrity verification. ```typescript import { defineConfig, createInlineSigningKeyProvider } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ hmacSignature: { secret: process.env.HMAC_SECRET!, // Headers to include in signature extensions: ['x-request-id', 'x-timestamp'], }, // Combine with JWT authentication jwt: { forward: { payload: true, token: false, }, signingKeyProviders: [ createInlineSigningKeyProvider(process.env.JWT_SECRET!), ], }, }); ``` ### Response Caching - Cache GraphQL Responses The response caching plugin caches GraphQL responses based on operation and variables, reducing load on subgraphs. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ responseCaching: { // TTL in milliseconds ttl: 60000, // Include cache metadata in response extensions includeExtensionMetadata: true, // Invalidation rules invalidateViaMutation: true, // Custom cache key cacheKey({ documentString, variableValues, context }) { const userId = context.jwt?.payload?.sub; return `${userId}:${documentString}:${JSON.stringify(variableValues)}`; }, // Scope responses per user scopePerSchemaCoordinate: { 'Query.me': 'PRIVATE', 'Query.publicPosts': 'PUBLIC', }, }, // Cache backend cache: { type: 'redis', host: 'localhost', port: 6379, }, }); ``` ### Custom Plugins - Extend Gateway Functionality Create custom plugins to extend gateway functionality with hooks for request lifecycle, subgraph execution, and response handling. ```typescript import { defineConfig, GatewayPlugin, GatewayContext } from '@graphql-hive/gateway'; // Custom logging plugin const useRequestLogger = (): GatewayPlugin => ({ onRequest({ request, url }) { console.log(`Incoming request: ${request.method} ${url.pathname}`); }, onFetch({ url, options, context }) { const start = Date.now(); return ({ response }) => { console.log(`Fetch ${url}: ${response.status} (${Date.now() - start}ms)`); }; }, onSubgraphExecute({ subgraphName, executionRequest }) { console.log(`Executing on ${subgraphName}: ${executionRequest.operationName}`); return ({ result }) => { if (result.errors) { console.error(`Errors from ${subgraphName}:`, result.errors); } }; }, onResponse({ response, request }) { console.log(`Response: ${response.status} for ${request.url}`); }, }); export const gatewayConfig = defineConfig({ plugins: (ctx) => [ useRequestLogger(), ], }); ``` ### PubSub - Event Publishing for Subscriptions The PubSub system enables GraphQL subscriptions by providing publish/subscribe functionality with support for in-memory, Redis, and NATS backends. ```typescript import { defineConfig, createRedisPubSub, createNatsPubSub, createPubSub } from '@graphql-hive/gateway'; // In-memory PubSub (single instance only) const memPubSub = createPubSub(); // Redis PubSub (multi-instance support) const redisPubSub = createRedisPubSub({ host: 'localhost', port: 6379, }); // NATS PubSub (multi-instance support) const natsPubSub = createNatsPubSub({ servers: ['nats://localhost:4222'], }); export const gatewayConfig = defineConfig({ pubsub: redisPubSub, // Enable webhooks for HTTP callback subscriptions webhooks: true, }); // Usage in resolvers // pubsub.publish('USER_CREATED', { userId: '123' }); // pubsub.subscribe('USER_CREATED'); // Returns AsyncIterable ``` ### Progressive Override - Gradual Rollout Progressive override allows gradual rollout of resolver implementations based on labels, enabling A/B testing and canary deployments. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ progressiveOverride(label, context) { // Enable beta features for specific users if (label === 'use-beta') { return context.headers['x-use-beta'] === 'true'; } // Percentage-based rollout if (label === 'new-resolver') { const userId = context.jwt?.payload?.sub; return hashCode(userId) % 100 < 10; // 10% rollout } return false; }, }); function hashCode(str: string): number { let hash = 0; for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i); } return Math.abs(hash); } ``` ### Hive CDN Integration - Schema Registry Integrate with GraphQL Hive's CDN for schema management, usage reporting, and persisted documents. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ // Fetch supergraph from Hive CDN supergraph: { type: 'hive', endpoint: process.env.HIVE_CDN_ENDPOINT!, key: process.env.HIVE_CDN_KEY!, circuitBreaker: { timeout: 5000, resetTimeout: 30000, }, }, // Usage reporting to Hive reporting: { type: 'hive', token: process.env.HIVE_ACCESS_TOKEN!, target: process.env.HIVE_TARGET, }, // Persisted documents from Hive persistedDocuments: { type: 'hive', endpoint: process.env.HIVE_PERSISTED_DOCS_ENDPOINT!, token: process.env.HIVE_PERSISTED_DOCS_TOKEN!, allowArbitraryDocuments: false, // Only allow registered operations }, }); ``` ### Apollo GraphOS Integration - Managed Federation Integrate with Apollo GraphOS for managed federation schema delivery and usage reporting. ```typescript import { defineConfig } from '@graphql-hive/gateway'; export const gatewayConfig = defineConfig({ // Fetch supergraph from Apollo GraphOS supergraph: { type: 'graphos', graphRef: 'my-graph@production', apiKey: process.env.APOLLO_KEY!, upLink: 'https://uplink.api.apollographql.com/', }, // Usage reporting to Apollo Studio reporting: { type: 'graphos', graphRef: 'my-graph@production', apiKey: process.env.APOLLO_KEY!, }, }); ``` ## Summary Hive Gateway is designed for organizations building or migrating to GraphQL Federation architectures. Its primary use cases include serving as a unified API gateway for microservices, providing a single GraphQL endpoint that federates multiple domain services, and acting as a proxy layer for existing GraphQL APIs. The gateway excels at handling complex enterprise requirements like authentication propagation, observability through OpenTelemetry and Prometheus, response caching, and graceful error handling across distributed systems. Integration patterns typically involve deploying the gateway as a Kubernetes service or serverless function, connecting it to a schema registry like GraphQL Hive or Apollo GraphOS for schema management, and configuring transport entries for each subgraph with appropriate authentication and retry policies. The gateway's plugin system allows extensive customization for logging, metrics, authentication, and business logic, making it adaptable to virtually any GraphQL infrastructure requirement. For production deployments, the gateway supports horizontal scaling through worker processes, multiple cache backends (Redis, Upstash, Cloudflare KV), and various PubSub systems for subscriptions.