Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience
Core server factory function and configuration options for creating GraphQL Yoga servers with comprehensive customization including logging, error handling, CORS, GraphiQL, and deployment settings.
Main factory function to create a configured GraphQL Yoga server instance.
/**
* Creates a new GraphQL Yoga server instance with specified configuration
* @param options - Server configuration options
* @returns Configured Yoga server instance
*/
function createYoga<
TServerContext extends Record<string, any> = {},
TUserContext extends Record<string, any> = {}
>(options: YogaServerOptions<TServerContext, TUserContext>): YogaServerInstance<TServerContext, TUserContext>;Usage Examples:
import { createYoga, createSchema } from "graphql-yoga";
// Basic server
const yoga = createYoga({
schema: createSchema({
typeDefs: `type Query { hello: String }`,
resolvers: { Query: { hello: () => "Hello!" } }
})
});
// Advanced configuration
const yoga = createYoga({
schema: mySchema,
logging: true,
maskedErrors: { isDev: process.env.NODE_ENV === 'development' },
graphqlEndpoint: '/api/graphql',
healthCheckEndpoint: '/health',
cors: {
origin: ['https://example.com'],
credentials: true
},
context: async ({ request }) => ({
user: await getUserFromRequest(request)
}),
plugins: [myCustomPlugin]
});Complete configuration interface for customizing GraphQL Yoga server behavior.
/**
* Configuration options for the GraphQL Yoga server
*/
interface YogaServerOptions<TServerContext, TUserContext> {
/** Enable/disable logging or provide custom logger (default: true) */
logging?: boolean | YogaLogger | LogLevel;
/** Error masking configuration for production safety (default: true) */
maskedErrors?: boolean | Partial<YogaMaskedErrorOpts>;
/** Context provider function or object */
context?: ((initialContext: YogaInitialContext & TServerContext) => Promise<TUserContext> | TUserContext) | Promise<TUserContext> | TUserContext;
/** CORS configuration */
cors?: CORSOptions;
/** GraphQL endpoint path (default: "/graphql") */
graphqlEndpoint?: string;
/** Health check endpoint path (default: "/health") */
healthCheckEndpoint?: string;
/** Whether to show landing page (default: true) */
landingPage?: boolean;
/** GraphiQL configuration (default: true) */
graphiql?: GraphiQLOptionsOrFactory<TServerContext>;
/** GraphQL schema definition */
schema?: YogaSchemaDefinition<TServerContext, TUserContext>;
/** Array of Envelop/Yoga plugins */
plugins?: Array<Plugin<TUserContext & TServerContext & YogaInitialContext> | Plugin | {}>;
/** Parser and validation cache configuration (default: true) */
parserAndValidationCache?: boolean | ParserAndValidationCacheOptions;
/** Custom Fetch API implementation */
fetchAPI?: Partial<FetchAPI>;
/** GraphQL multipart request support (default: true) */
multipart?: boolean;
/** Request batching configuration (default: false) */
batching?: BatchingOptions;
/** Server instance identifier */
id?: string;
}Context provider configuration for adding custom data to GraphQL execution context.
/**
* Context provider types for GraphQL execution
*/
type ContextProvider<TServerContext, TUserContext> =
| ((initialContext: YogaInitialContext & TServerContext) => Promise<TUserContext> | TUserContext)
| Promise<TUserContext>
| TUserContext;Usage Examples:
// Function-based context
const yoga = createYoga({
context: async ({ request }) => {
const token = request.headers.get('authorization');
const user = await authenticateUser(token);
return { user, startTime: Date.now() };
}
});
// Object context
const yoga = createYoga({
context: {
apiVersion: '1.0',
environment: 'production'
}
});
// Promise context
const yoga = createYoga({
context: initializeContext()
});Cross-Origin Resource Sharing configuration for controlling client access.
/**
* CORS configuration options
*/
type CORSOptions = {
/** Allowed origins */
origin?: string[] | string;
/** Allowed HTTP methods */
methods?: string[];
/** Allowed request headers */
allowedHeaders?: string[];
/** Headers exposed to the client */
exposedHeaders?: string[];
/** Whether to include credentials */
credentials?: boolean;
/** Preflight cache max age in seconds */
maxAge?: number;
} | false;Usage Examples:
// Basic CORS
const yoga = createYoga({
cors: {
origin: 'https://my-app.com',
credentials: true
}
});
// Multiple origins
const yoga = createYoga({
cors: {
origin: ['https://app.com', 'https://admin.com'],
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}
});
// Disable CORS
const yoga = createYoga({
cors: false
});Request batching configuration for handling multiple GraphQL operations in a single request.
/**
* Batching configuration options
*/
type BatchingOptions = boolean | {
/** Maximum number of operations per batch (default: 10) */
limit?: number;
};Usage Examples:
// Enable batching with default limit
const yoga = createYoga({
batching: true
});
// Custom batch limit
const yoga = createYoga({
batching: { limit: 5 }
});Error masking configuration for hiding sensitive information in production environments.
/**
* Error masking configuration
*/
interface YogaMaskedErrorOpts {
/** Custom error masking function */
maskError: MaskError;
/** Default error message for masked errors */
errorMessage: string;
/** Whether running in development mode */
isDev?: boolean;
}
/**
* Error masking function signature
*/
type MaskError = (error: unknown, message: string, isDev?: boolean) => Error;Usage Examples:
// Custom error masking
const yoga = createYoga({
maskedErrors: {
errorMessage: 'Something went wrong',
isDev: process.env.NODE_ENV === 'development',
maskError: (error, message, isDev) => {
if (isDev && error instanceof Error) {
return error;
}
return new Error(message);
}
}
});
// Disable error masking
const yoga = createYoga({
maskedErrors: false
});The complete server instance type returned by createYoga.
/**
* GraphQL Yoga server instance with adapter functionality
*/
type YogaServerInstance<
TServerContext extends Record<string, any>,
TUserContext extends Record<string, any>
> = ServerAdapter<TServerContext, YogaServer<TServerContext, TUserContext>>;tessl i tessl/npm-graphql-yoga@4.0.0