or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

caching-performance.mdcontext-types.mderror-handling.mdindex.mdlogging-system.mdplugin-system.mdrequest-processing.mdresult-processing.mdschema-management.mdserver-configuration.mdsubscription-system.md
tile.json

index.mddocs/

GraphQL Yoga

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.

Package Information

  • Package Name: graphql-yoga
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install graphql-yoga graphql

Core Imports

import { createYoga, createSchema } from "graphql-yoga";

For CommonJS:

const { createYoga, createSchema } = require("graphql-yoga");

Basic Usage

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')
})

Architecture

GraphQL Yoga is built around several key components:

  • Server Core: YogaServer class that handles GraphQL request processing and response generation
  • Plugin System: Extensible plugin architecture based on Envelop for customizing server behavior
  • Request Processing: Multi-format request parsing supporting JSON, form data, multipart, and GraphQL strings
  • Result Processing: Flexible result processors for different response formats (JSON, SSE, multipart)
  • Schema Integration: Integration with GraphQL Tools for schema creation and manipulation
  • WHATWG Fetch API: Cross-platform compatibility using standard web APIs

Capabilities

Server Creation and Configuration

Core 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>;

Server Configuration

Schema Creation and Management

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;
}

Schema Management

Plugin System

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;

Plugin System

Request Processing and Validation

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;

Request Processing

Result Processing and Response Formatting

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;

Result Processing

Error Handling and Masking

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;
}

Error Handling

Caching and Performance

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;
}

Caching and Performance

Context and Type System

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;
}

Context and Types

Subscription System

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>;
}

Subscription System

Logging System

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;
}

Logging System