Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience
Ready-to-use plugins for GraphiQL interface, health checks, request parsing, result processing, and development tools. These plugins provide essential functionality for GraphQL Yoga servers.
Plugin to enable the GraphiQL interactive GraphQL IDE interface.
/**
* Plugin to enable GraphiQL interface for GraphQL development
* @param options - GraphiQL configuration options
* @returns Plugin for GraphiQL integration
*/
function useGraphiQL(options: {
graphqlEndpoint: string;
options?: GraphiQLOptionsOrFactory<TServerContext>;
render?: (options?: GraphiQLOptions) => PromiseOrValue<BodyInit>;
logger: YogaLogger;
}): Plugin;
/**
* GraphiQL configuration options
*/
interface GraphiQLOptions {
/** Default query to show in GraphiQL */
defaultQuery?: string;
/** Initial headers in JSON format */
headers?: string;
/** Request credentials mode */
credentials?: RequestCredentials;
/** Page title for GraphiQL */
title?: string;
/** Subscription protocol to use */
subscriptionsProtocol?: 'SSE' | 'GRAPHQL_SSE' | 'WS' | 'LEGACY_WS';
/** Additional headers to always include */
additionalHeaders?: Record<string, string>;
}
/**
* GraphiQL options or factory function
*/
type GraphiQLOptionsOrFactory<TServerContext> =
| GraphiQLOptions
| ((context: TServerContext) => GraphiQLOptions);Usage Examples:
import { createYoga, useGraphiQL } from "graphql-yoga";
// Basic GraphiQL setup
const yoga = createYoga({
graphiql: true // Enables with default options
});
// Custom GraphiQL configuration
const yoga = createYoga({
graphiql: {
title: 'My API Explorer',
defaultQuery: `
query GetUsers {
users {
id
name
email
}
}
`,
headers: JSON.stringify({
'Authorization': 'Bearer your-token-here'
}),
credentials: 'include',
subscriptionsProtocol: 'SSE'
}
});
// Dynamic GraphiQL options
const yoga = createYoga({
graphiql: ({ request }) => ({
title: `API for ${request.headers.get('host')}`,
additionalHeaders: {
'X-Client-Version': '1.0.0'
}
})
});Plugin for custom readiness/health checks to monitor service availability.
/**
* Plugin for custom readiness checks
* @param options - Readiness check configuration
* @returns Plugin for readiness check functionality
*/
function useReadinessCheck(options: ReadinessCheckPluginOptions): Plugin;
/**
* Readiness check plugin configuration
*/
interface ReadinessCheckPluginOptions {
/** Endpoint path for readiness check (default: "/ready") */
endpoint?: string;
/** Function to check service readiness */
check: (payload: {
request: Request;
fetchAPI: FetchAPI;
}) => void | boolean | Response | Promise<void | boolean | Response>;
}Usage Examples:
import { createYoga, useReadinessCheck } from "graphql-yoga";
// Basic readiness check
const yoga = createYoga({
plugins: [
useReadinessCheck({
check: async () => {
// Check database connection
const isDbHealthy = await checkDatabaseConnection();
return isDbHealthy;
}
})
]
});
// Advanced readiness check with custom response
const yoga = createYoga({
plugins: [
useReadinessCheck({
endpoint: '/health/ready',
check: async ({ fetchAPI }) => {
try {
const dbStatus = await checkDatabase();
const redisStatus = await checkRedis();
if (dbStatus && redisStatus) {
return new fetchAPI.Response(
JSON.stringify({ status: 'ready', services: { db: 'ok', redis: 'ok' } }),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
} else {
return new fetchAPI.Response(
JSON.stringify({ status: 'not ready', services: { db: dbStatus ? 'ok' : 'error', redis: redisStatus ? 'ok' : 'error' } }),
{
status: 503,
headers: { 'Content-Type': 'application/json' }
}
);
}
} catch (error) {
throw new Error(`Health check failed: ${error.message}`);
}
}
})
]
});Plugin for caching GraphQL parsing and validation results to improve performance.
/**
* Plugin for caching parser and validation results
* @param options - Cache configuration options
* @returns Plugin for parsing/validation cache
*/
function useParserAndValidationCache(options?: ParserAndValidationCacheOptions): Plugin;
/**
* Parser and validation cache configuration
*/
interface ParserAndValidationCacheOptions {
/** Maximum number of cached items */
max?: number;
/** Time to live for cache entries in milliseconds */
ttl?: number;
}Usage Examples:
import { createYoga, useParserAndValidationCache } from "graphql-yoga";
// Default cache settings
const yoga = createYoga({
parserAndValidationCache: true
});
// Custom cache configuration
const yoga = createYoga({
plugins: [
useParserAndValidationCache({
max: 2000, // Cache up to 2000 items
ttl: 600000 // 10 minutes TTL
})
]
});
// Disable caching
const yoga = createYoga({
parserAndValidationCache: false
});Plugin for custom HTTP request parsing to extract GraphQL parameters.
/**
* Plugin for custom request parsing
* @param options - Request parser configuration
* @returns Plugin for request parsing
*/
function useRequestParser(options: {
match: (request: Request) => boolean;
parse: RequestParser;
}): Plugin;
/**
* Request parser function type
*/
type RequestParser = (
request: Request
) => PromiseOrValue<GraphQLParams> | PromiseOrValue<GraphQLParams[]>;Usage Examples:
import { createYoga, useRequestParser } from "graphql-yoga";
// Custom request parser for specific content type
const yoga = createYoga({
plugins: [
useRequestParser({
match: (request) => request.headers.get('content-type')?.includes('application/graphql-query'),
parse: async (request) => {
const query = await request.text();
return { query };
}
})
]
});
// Parser for custom format
const yoga = createYoga({
plugins: [
useRequestParser({
match: (request) => request.url.includes('/graphql-custom'),
parse: async (request) => {
const body = await request.json();
return {
query: body.gql,
variables: body.vars,
operationName: body.op
};
}
})
]
});Plugin for custom result processing and response formatting.
/**
* Plugin for custom result processing
* @returns Plugin for result processing
*/
function useResultProcessors(): Plugin;
/**
* Result processor function type
*/
type ResultProcessor = (
result: ResultProcessorInput,
fetchAPI: FetchAPI,
acceptedMediaType: string
) => PromiseOrValue<Response>;Usage Examples:
import { createYoga, useResultProcessors } from "graphql-yoga";
// Built-in result processors (automatically included)
const yoga = createYoga({
plugins: [
useResultProcessors() // Handles JSON, SSE, multipart responses
]
});
// Custom result processor plugin
const customResultPlugin: Plugin = {
onResultProcess({ request, setResultProcessor }) {
const acceptHeader = request.headers.get('accept');
if (acceptHeader?.includes('text/csv')) {
setResultProcessor(async (result, fetchAPI) => {
const csvData = convertResultToCSV(result);
return new fetchAPI.Response(csvData, {
headers: { 'Content-Type': 'text/csv' }
});
}, 'text/csv');
}
}
};Plugin for basic server health checks.
/**
* Plugin for basic health checks
* @param options - Health check configuration
* @returns Plugin for health check functionality
*/
function useHealthCheck(options: {
id: string;
logger: YogaLogger;
endpoint?: string;
}): Plugin;Usage Examples:
import { createYoga, useHealthCheck } from "graphql-yoga";
// Basic health check (automatically included in Yoga)
const yoga = createYoga({
plugins: [
useHealthCheck({
id: 'my-server',
logger: myLogger,
endpoint: '/health'
})
]
});Utility functions for GraphiQL rendering and detection.
/**
* Render GraphiQL HTML interface
* @param opts - GraphiQL rendering options
* @returns GraphiQL HTML string
*/
function renderGraphiQL(opts: GraphiQLRendererOptions): string;
/**
* Check if request should receive GraphiQL interface
* @param request - HTTP request
* @returns Whether to render GraphiQL
*/
function shouldRenderGraphiQL(request: Request): boolean;
/**
* GraphiQL rendering options
*/
interface GraphiQLRendererOptions {
/** GraphQL endpoint path */
endpoint?: string;
/** Default query to show */
defaultQuery?: string;
/** Initial headers in JSON format */
headers?: string;
/** Request credentials mode */
credentials?: RequestCredentials;
/** Page title */
title?: string;
/** Subscription protocol */
subscriptionsProtocol?: 'SSE' | 'GRAPHQL_SSE' | 'WS' | 'LEGACY_WS';
/** Additional headers */
additionalHeaders?: Record<string, string>;
}Usage Examples:
import { renderGraphiQL, shouldRenderGraphiQL } from "graphql-yoga";
// Custom GraphiQL rendering
const customGraphiQLPlugin: Plugin = {
onRequest({ request, endResponse, fetchAPI }) {
if (shouldRenderGraphiQL(request)) {
const html = renderGraphiQL({
endpoint: '/graphql',
title: 'Custom GraphiQL',
defaultQuery: 'query { __typename }'
});
endResponse(new fetchAPI.Response(html, {
headers: { 'Content-Type': 'text/html' }
}));
}
}
};
// Check if GraphiQL should be rendered
app.use('/graphql', (req, res, next) => {
if (shouldRenderGraphiQL(req)) {
// Serve GraphiQL
const html = renderGraphiQL({ endpoint: '/graphql' });
res.send(html);
} else {
next();
}
});tessl i tessl/npm-graphql-yoga@4.0.0