GraphQL Yoga is a fully-featured GraphQL server library for Node.js that prioritizes ease of setup, high performance, and excellent developer experience. It provides a comprehensive solution for building GraphQL APIs with features including built-in GraphiQL IDE, subscription support, file uploads, middleware system through Envelop plugins, automatic schema stitching and federation capabilities, TypeScript support with full type safety, and extensive customization options for authentication, caching, and error handling.
npm install graphql-yoga graphqlimport { createYoga, createSchema } from "graphql-yoga";For CommonJS:
const { createYoga, createSchema } = require("graphql-yoga");import { createServer } from 'node:http'
import { createSchema, createYoga } from 'graphql-yoga'
const yoga = createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello from Yoga!'
}
}
})
})
const server = createServer(yoga)
server.listen(4000, () => {
console.info('Server is running on http://localhost:4000/graphql')
})GraphQL Yoga is built around several key components:
YogaServer class that handles GraphQL request processing and response generationCore server creation functionality for setting up GraphQL endpoints with comprehensive configuration options. Supports TypeScript generics for type-safe server and user contexts.
function createYoga<
TServerContext extends Record<string, any> = {},
TUserContext extends Record<string, any> = {},
>(
options: YogaServerOptions<TServerContext, TUserContext>
): YogaServerInstance<TServerContext, TUserContext>;
interface YogaServerOptions<TServerContext, TUserContext> {
schema?: YogaSchemaDefinition<TServerContext, TUserContext>;
plugins?: Array<Plugin<TUserContext & TServerContext & YogaInitialContext, TServerContext, TUserContext>>;
cors?: CORSOptions;
context?:
| ((initialContext: YogaInitialContext & TServerContext) => Promise<TUserContext> | TUserContext)
| Promise<TUserContext>
| TUserContext;
graphqlEndpoint?: string;
healthCheckEndpoint?: string;
landingPage?: boolean | LandingPageRenderer;
graphiql?: GraphiQLOptionsOrFactory<TServerContext> | boolean;
renderGraphiQL?: (options?: GraphiQLOptions) => PromiseOrValue<BodyInit>;
batching?: BatchingOptions;
parserAndValidationCache?: boolean | ParserAndValidationCacheOptions;
maskedErrors?: boolean | Partial<YogaMaskedErrorOpts>;
logging?: boolean | YogaLogger | LogLevel;
fetchAPI?: Partial<FetchAPI>;
multipart?: boolean;
id?: string;
extraParamNames?: string[];
}
class YogaServer<
TServerContext extends Record<string, any>,
TUserContext extends Record<string, any>,
> {
readonly getEnveloped: GetEnvelopedFn<TUserContext & TServerContext & YogaInitialContext>;
logger: YogaLogger;
readonly graphqlEndpoint: string;
fetchAPI: FetchAPI;
readonly version: string;
}
interface BatchingOptions {
limit?: number;
}
type YogaServerInstance<TServerContext, TUserContext> = YogaServer<TServerContext, TUserContext> & ServerAdapter<TServerContext>;Schema creation utilities that integrate with GraphQL Tools for defining executable GraphQL schemas with resolvers, type definitions, and context integration.
function createSchema<TContext = {}>(
opts: IExecutableSchemaDefinition<TContext & YogaInitialContext>
): GraphQLSchemaWithContext<TContext & YogaInitialContext>;
type YogaSchemaDefinition<TServerContext, TUserContext> =
| GraphQLSchema
| ((context: TServerContext) => GraphQLSchema | Promise<GraphQLSchema>);
interface GraphQLSchemaWithContext<TContext> extends GraphQLSchema {
_context?: TContext;
}Comprehensive plugin system for extending server functionality with custom middleware, authentication, caching, validation, and more. Based on Envelop architecture.
interface Plugin<
TPluginContext extends Record<string, any> = {},
TServerContext extends Record<string, any> = {},
TUserContext extends Record<string, any> = {},
> {
onYogaInit?: OnYogaInitHook<TServerContext>;
onRequestParse?: OnRequestParseHook<TServerContext>;
onParams?: OnParamsHook<TServerContext>;
onExecutionResult?: OnExecutionResultHook<TServerContext>;
onResultProcess?: OnResultProcess<TServerContext>;
}
function useGraphiQL<TServerContext>(
config?: GraphiQLPluginConfig<TServerContext>
): Plugin;
function useSchema<TServerContext, TUserContext>(
schemaOrSchemaFactory: YogaSchemaDefinition<TServerContext, TUserContext>
): Plugin;
function useHealthCheck(options: HealthCheckPluginOptions): Plugin;
function useReadinessCheck(options: ReadinessCheckPluginOptions): Plugin;
function useExecutionCancellation(): Plugin;Multi-format request parsing and validation system supporting JSON, form data, multipart uploads, and GraphQL query strings with comprehensive parameter validation.
interface GraphQLParams<
TVariables = Record<string, any>,
TExtensions = Record<string, any>,
> {
operationName?: string;
query?: string;
variables?: TVariables;
extensions?: TExtensions;
}
function useRequestParser(options: RequestParserPluginOptions): Plugin;
function useCheckGraphQLQueryParams(extraParamNames?: string[]): Plugin;
function useCheckMethodForGraphQL(): Plugin;
function usePreventMutationViaGET(): Plugin;
function useLimitBatching(limit?: number): Plugin;Flexible result processing system supporting different response formats including regular JSON, Server-Sent Events for subscriptions, and multipart responses for file uploads.
function useResultProcessors(): Plugin;
function processRegularResult(input: ResultProcessorInput, fetchAPI: FetchAPI): Response;
function getSSEProcessor(): ResultProcessor;
function processMultipartResult(result: ResultProcessorInput, fetchAPI: FetchAPI): Response;
type ResultProcessor = (
executionResult: ExecutionResultWithSerializer,
fetchAPI: FetchAPI
) => Response | Promise<Response>;
type ResultProcessorInput =
| ExecutionResult
| AsyncIterable<ExecutionResult>
| Response;Comprehensive error handling system with configurable error masking for production environments, GraphQL error utilities, and HTTP error response generation.
type MaskError = (error: unknown, message: string, isDev?: boolean) => Error;
function maskError(error: unknown, message: string, isDev?: boolean): Error;
function handleError(
error: unknown,
maskedErrorsOpts: YogaMaskedErrorOpts | null,
logger: YogaLogger
): GraphQLError[];
function isGraphQLError(val: unknown): val is GraphQLError;
function isOriginalGraphQLError(error: GraphQLError): boolean;
function areGraphQLErrors(obj: unknown): obj is readonly GraphQLError[];
interface YogaMaskedErrorOpts {
maskError?: MaskError;
errorMessage?: string;
isDev?: boolean;
}Built-in caching utilities including LRU cache implementation and parser/validation caching for improved performance in production environments.
function createLRUCache<T extends {}>(options: LRUCacheOptions): LRUCache<T>;
function useParserAndValidationCache(options: ParserAndValidationCacheOptions): Plugin;
interface LRUCacheOptions {
max: number;
ttl?: number;
}
interface ParserAndValidationCacheOptions {
max?: number;
ttl?: number;
}
interface LRUCache<T extends {}> {
get(key: string): T | undefined;
set(key: string, value: T): void;
has(key: string): boolean;
delete(key: string): boolean;
clear(): void;
}Type-safe context system with initial context setup, user context extension, and comprehensive TypeScript support for server and user context types.
interface YogaInitialContext extends ServerAdapterInitialContext {
params: GraphQLParams;
request: Request;
}
type CORSOptions =
| {
origin?: string[] | string;
methods?: string[];
allowedHeaders?: string[];
exposedHeaders?: string[];
credentials?: boolean;
maxAge?: number;
}
| false;
type FetchAPI = ReturnType<typeof createFetch>;
interface FetchEvent extends Event {
request: Request;
respondWith(response: Response | Promise<Response>): void;
}Real-time GraphQL subscriptions with PubSub implementation, event streaming, and transformation utilities. Supports Server-Sent Events (SSE) and WebSocket protocols with filtering and mapping operations.
function createPubSub(): PubSub;
function filter<T>(predicate: (value: T) => boolean | Promise<boolean>): (source: AsyncIterable<T>) => AsyncIterable<T>;
function map<T, U>(mapper: (value: T) => U | Promise<U>): (source: AsyncIterable<T>) => AsyncIterable<U>;
function pipe<T>(source: AsyncIterable<T>, ...operators: Array<(source: AsyncIterable<any>) => AsyncIterable<any>>): AsyncIterable<any>;
interface PubSub {
publish<T = any>(topic: string, payload: T): void;
subscribe<T = any>(topic: string): AsyncIterableIterator<T>;
subscribe<T = any>(...topics: string[]): AsyncIterableIterator<T>;
}
class Repeater<T, TReturn = any, TNext = unknown> implements AsyncIterableIterator<T> {
constructor(executor: (push: (value: T) => void, stop: (value?: TReturn) => void) => void | Promise<void>);
next(): Promise<IteratorResult<T, TReturn>>;
return(value?: TReturn): Promise<IteratorResult<T, TReturn>>;
throw(error?: any): Promise<IteratorResult<T, TReturn>>;
[Symbol.asyncIterator](): AsyncIterableIterator<T>;
}Configurable logging system with structured output, log level filtering, and custom logger support. Integrates with server lifecycle and plugin system for comprehensive monitoring.
function createLogger(logLevel?: LogLevel, logger?: YogaLogger): YogaLogger;
enum LogLevel {
Debug = 0,
Info = 1,
Warn = 2,
Error = 3,
Silent = 4,
}
interface YogaLogger {
debug(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
}