Complete TypeScript type definitions covering configuration, context management, request/response lifecycle, and plugin development. Apollo Server provides 50+ interfaces and types for full type safety.
Main server configuration interface with all available options.
/**
* Core Apollo Server configuration interface
*/
interface Config<ContextFunctionParams = any> {
/** GraphQL schema modules */
modules?: GraphQLSchemaModule[];
/** GraphQL type definitions - SDL string, AST, or schema instance */
typeDefs?: TypeSource;
/** GraphQL field resolvers */
resolvers?: IResolvers | Array<IResolvers>;
/** Parse options for GraphQL schema creation */
parseOptions?: ParseOptions;
/** Complete GraphQL schema (alternative to typeDefs + resolvers) */
schema?: GraphQLSchema;
/** Context object or function for request-scoped data */
context?: Context<ContextFunctionParams> | ContextFunction<ContextFunctionParams>;
/** Enable GraphQL introspection queries */
introspection?: boolean;
/** Mock configuration for development */
mocks?: boolean | IMocks;
/** Mock entire schema (not just missing resolvers) */
mockEntireSchema?: boolean;
/** Array of plugins to extend functionality */
plugins?: PluginDefinition[];
/** Persisted queries configuration */
persistedQueries?: PersistedQueryOptions | false;
/** Gateway for federated GraphQL */
gateway?: GatewayInterface;
/** Stop server on termination signals */
stopOnTerminationSignals?: boolean;
/** Apollo Studio configuration */
apollo?: ApolloConfigInput;
/** Node environment override */
nodeEnv?: string;
/** Disable GraphQL validation (dangerous) */
dangerouslyDisableValidation?: boolean;
/** Document store for persisted queries */
documentStore?: DocumentStore | null;
/** CSRF prevention configuration */
csrfPrevention?: CSRFPreventionOptions | boolean;
/** Cache implementation - 'bounded' creates default in-memory cache */
cache?: KeyValueCache | 'bounded';
/** Enable debug mode with detailed logging */
debug?: boolean;
/** Root value for GraphQL execution */
rootValue?: any;
/** Custom GraphQL validation rules */
validationRules?: ValidationRule[];
/** Custom GraphQL executor function */
executor?: GraphQLExecutor;
/** Response formatting function */
formatResponse?: (response: GraphQLResponse, requestContext: GraphQLRequestContext) => GraphQLResponse;
/** Error formatting function */
formatError?: (error: GraphQLError) => GraphQLFormattedError;
/** Custom field resolver */
fieldResolver?: GraphQLFieldResolver<any, any>;
/** Data sources factory function */
dataSources?: () => DataSources;
/** Logger instance */
logger?: Logger;
/** Allow batched HTTP requests */
allowBatchedHttpRequests?: boolean;
}
/**
* Type source for GraphQL schema definition
*/
type TypeSource = string | DocumentNode | GraphQLSchema | Array<string | DocumentNode>;
/**
* GraphQL schema module interface
*/
interface GraphQLSchemaModule {
typeDefs: TypeSource;
resolvers?: IResolvers;
}
/**
* IMocks type for schema mocking
*/
type IMocks = Record<string, any>;
/**
* IResolvers type for GraphQL resolvers
*/
type IResolvers = Record<string, any>;
/**
* ParseOptions for GraphQL document parsing
*/
interface ParseOptions {
noLocation?: boolean;
allowLegacySDLEmptyFields?: boolean;
allowLegacySDLImplementsInterfaces?: boolean;
experimentalFragmentVariables?: boolean;
}
/**
* Logger interface
*/
interface Logger {
debug?(message?: any): void;
info?(message?: any): void;
warn?(message?: any): void;
error?(message?: any): void;
}
/**
* Data sources type
*/
type DataSources<TContext = BaseContext> = Record<string, DataSource<TContext>>;
/**
* Persisted query options
*/
interface PersistedQueryOptions {
cache?: KeyValueCache;
ttl?: number;
}
/**
* Plugin definition - can be plugin instance or function returning plugin
*/
type PluginDefinition = ApolloServerPlugin | (() => ApolloServerPlugin);Configuration for Cross-Site Request Forgery (CSRF) protection.
/**
* CSRF prevention configuration options
* Protects against CSRF attacks by requiring specific headers
*/
interface CSRFPreventionOptions {
/**
* Required headers that trigger browser preflight
* Default: ['x-apollo-operation-name', 'apollo-require-preflight']
* Operations must include at least one of these headers
*/
requestHeaders?: string[];
}Options for GraphQL execution engine.
/**
* GraphQL execution options
*/
interface GraphQLOptions {
/** GraphQL schema */
schema: GraphQLSchema;
/** Root value for resolvers */
rootValue?: any;
/** Context value for resolvers */
contextValue?: any;
/** Variable values for operation */
variableValues?: VariableValues;
/** Operation name to execute */
operationName?: string;
/** Field resolver function */
fieldResolver?: GraphQLFieldResolver<any, any>;
/** Custom validation rules */
validationRules?: ValidationRule[];
/** Execute function */
execute?: typeof execute;
/** Format error function */
formatError?: (error: GraphQLError) => GraphQLFormattedError;
/** Format response function */
formatResponse?: (response: ExecutionResult, context: GraphQLRequestContext) => ExecutionResult;
/** Enable debug mode */
debug?: boolean;
/** Log function for debug messages */
logFunction?: (message: string) => void;
/** Extensions to add to response */
extensions?: (info: GraphQLRequestInfo) => Record<string, any>;
/** Cache control extension */
cacheControl?: CacheControlExtensionOptions;
/** Tracing extension */
tracing?: TracingExtensionOptions;
}
/**
* Variable values type
*/
type VariableValues = { [name: string]: any };Core context interfaces for request-scoped data.
/**
* Base context interface
*/
interface BaseContext {
[key: string]: any;
}
/**
* Context function type for dynamic context creation
*/
type ContextFunction<FunctionParams, ProducedContext> = (
params: FunctionParams
) => Promise<ProducedContext> | ProducedContext;
/**
* Context type union
*/
type Context<T = BaseContext> = T | ContextFunction<any, T>;
/**
* Express-specific context parameters
*/
interface ExpressContext {
/** Express request object */
req: express.Request;
/** Express response object */
res: express.Response;
}
/**
* Context function parameters for Express integration
*/
type ContextFunctionParams = ExpressContext;Complete request context with lifecycle information.
/**
* GraphQL request context containing request lifecycle data
*/
interface GraphQLRequestContext<TContext = BaseContext> {
/** The GraphQL request */
readonly request: GraphQLRequest;
/** The GraphQL response (available after execution) */
readonly response?: GraphQLResponse;
/** User-defined context object */
readonly context: TContext;
/** Cache instance for this request */
readonly cache: KeyValueCache;
/** GraphQL schema being executed */
readonly schema: GraphQLSchema;
/** Parsed GraphQL document */
readonly document?: DocumentNode;
/** Selected operation from document */
readonly operation?: OperationDefinitionNode;
/** Operation name being executed */
readonly operationName?: string;
/** Variable values for operation */
readonly variables?: VariableValues;
/** Request metrics and timing */
readonly metrics: GraphQLRequestMetrics;
/** Source of the GraphQL request */
readonly source?: string;
/** Errors encountered during execution */
readonly errors?: ReadonlyArray<GraphQLError>;
/** Query hash for caching */
readonly queryHash?: string;
/** Persisted query information */
readonly persistedQuery?: PersistedQuery;
/** Request HTTP information */
readonly requestIp?: string;
}
/**
* GraphQL request structure
*/
interface GraphQLRequest {
/** GraphQL query string */
query?: string;
/** Operation name to execute */
operationName?: string;
/** Variable values */
variables?: VariableValues;
/** Extensions object */
extensions?: Record<string, any>;
/** HTTP-specific request information */
http?: HTTPGraphQLRequest;
}
/**
* HTTP-specific GraphQL request information
*/
interface HTTPGraphQLRequest {
/** HTTP method */
method: string;
/** Request URL */
url: string;
/** Request headers */
headers: Map<string, string>;
/** Request body */
body?: any;
/** Start time for metrics */
startTime?: number;
}
/**
* GraphQL response structure
*/
interface GraphQLResponse {
/** Response data */
data?: Record<string, any> | null;
/** Response errors */
errors?: ReadonlyArray<GraphQLFormattedError>;
/** Response extensions */
extensions?: Record<string, any>;
/** HTTP-specific response information */
http?: HTTPGraphQLResponse;
}
/**
* HTTP-specific GraphQL response information
*/
interface HTTPGraphQLResponse {
/** Response status code */
status?: number;
/** Response headers */
headers?: Map<string, string>;
/** Response body */
body?: any;
}Performance metrics for GraphQL requests.
/**
* GraphQL request performance metrics
*/
interface GraphQLRequestMetrics {
/** Request start time */
startHrTime: [number, number];
/** Parsing start time */
parsingStartHrTime?: [number, number];
/** Validation start time */
validationStartHrTime?: [number, number];
/** Execution start time */
executionStartHrTime?: [number, number];
/** Overall start time */
requestStartHrTime: [number, number];
/** Persistent query cache hit */
persistedQueryHit?: boolean;
/** Persistent query register */
persistedQueryRegister?: boolean;
/** Response cache hit */
responseCacheHit?: boolean;
/** Forbidden operation */
forbiddenOperation?: boolean;
/** Registered operation */
registeredOperation?: boolean;
}Specialized context types for different request phases.
/**
* Context after GraphQL source resolution
*/
interface GraphQLRequestContextDidResolveSource<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly source: string;
}
/**
* Context when parsing starts
*/
interface GraphQLRequestContextParsingDidStart<TContext = BaseContext>
extends GraphQLRequestContextDidResolveSource<TContext> {}
/**
* Context when validation starts
*/
interface GraphQLRequestContextValidationDidStart<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly document: DocumentNode;
}
/**
* Context after operation resolution
*/
interface GraphQLRequestContextDidResolveOperation<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly document: DocumentNode;
readonly operation: OperationDefinitionNode;
readonly operationName?: string;
}
/**
* Context when errors are encountered
*/
interface GraphQLRequestContextDidEncounterErrors<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly errors: ReadonlyArray<GraphQLError>;
}
/**
* Context for operation response
*/
interface GraphQLRequestContextResponseForOperation<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly document: DocumentNode;
readonly operation: OperationDefinitionNode;
readonly response: GraphQLResponse;
}
/**
* Context when execution starts
*/
interface GraphQLRequestContextExecutionDidStart<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly document: DocumentNode;
readonly operation: OperationDefinitionNode;
}
/**
* Context before sending response
*/
interface GraphQLRequestContextWillSendResponse<TContext = BaseContext>
extends GraphQLRequestContext<TContext> {
readonly response: GraphQLResponse;
}Core plugin interfaces for extending Apollo Server.
/**
* Apollo Server plugin interface
*/
interface ApolloServerPlugin<TContext = BaseContext> {
/**
* Server lifecycle hook - called when server starts
*/
serverWillStart?(service: GraphQLServiceContext): Promise<GraphQLServerListener | void>;
/**
* Request lifecycle hook - called for each request
*/
requestDidStart?(requestContext: GraphQLRequestContext<TContext>): Promise<GraphQLRequestListener<TContext> | void>;
}
/**
* Server lifecycle listener
*/
interface GraphQLServerListener {
/** Called when server is stopping */
serverWillStop?(): Promise<void>;
}
/**
* Request lifecycle listener
*/
interface GraphQLRequestListener<TContext = BaseContext> {
/** Called when request starts */
requestDidStart?(requestContext: GraphQLRequestContext<TContext>): Promise<void>;
/** Called after source resolution */
didResolveSource?(requestContext: GraphQLRequestContextDidResolveSource<TContext>): Promise<void>;
/** Called when parsing starts */
parsingDidStart?(requestContext: GraphQLRequestContextParsingDidStart<TContext>): Promise<void>;
/** Called when validation starts */
validationDidStart?(requestContext: GraphQLRequestContextValidationDidStart<TContext>): Promise<void>;
/** Called after operation resolution */
didResolveOperation?(requestContext: GraphQLRequestContextDidResolveOperation<TContext>): Promise<void>;
/** Called when errors are encountered */
didEncounterErrors?(requestContext: GraphQLRequestContextDidEncounterErrors<TContext>): Promise<void>;
/** Called when execution starts */
executionDidStart?(requestContext: GraphQLRequestContextExecutionDidStart<TContext>): Promise<GraphQLRequestExecutionListener<TContext> | void>;
/** Called before sending response */
willSendResponse?(requestContext: GraphQLRequestContextWillSendResponse<TContext>): Promise<void>;
}
/**
* Execution phase listener
*/
interface GraphQLRequestExecutionListener<TContext = BaseContext> {
/** Called when execution starts */
executionDidStart?(executionRequestContext: GraphQLRequestContextExecutionDidStart<TContext>): Promise<void>;
/** Called before field resolution */
willResolveField?(fieldResolverParams: GraphQLFieldResolverParams<any, TContext>): Promise<(error: Error | null, result?: any) => void> | void;
/** Called when execution ends */
executionDidEnd?(endedRequestContext: GraphQLRequestContextExecutionDidStart<TContext>): Promise<void>;
}
/**
* GraphQL service context for plugins
*/
interface GraphQLServiceContext {
/** GraphQL schema */
schema: GraphQLSchema;
/** Apollo configuration */
apollo: ApolloConfig;
/** Server ID */
serverlessFramework?: boolean;
/** Engine configuration */
engine: boolean;
}Cache implementation interfaces for query and data caching.
/**
* Key-value cache interface
*/
interface KeyValueCache<V = string> {
/** Get a value by key */
get(key: string): Promise<V | undefined>;
/** Set a value with optional TTL */
set(key: string, value: V, options?: KeyValueCacheSetOptions): Promise<void>;
/** Delete a value by key */
delete(key: string): Promise<boolean | void>;
/** Flush all cached values */
flush?(): Promise<void>;
}
/**
* Cache set options
*/
interface KeyValueCacheSetOptions {
/** Time to live in seconds */
ttl?: number;
}
/**
* Document store for persisted queries
*/
interface DocumentStore {
/** Get a document by hash */
get(hash: string): Promise<DocumentNode | undefined>;
/** Set a document with hash */
set(hash: string, document: DocumentNode): Promise<void>;
}Cache control and policy types for HTTP caching.
/**
* Cache hint for GraphQL fields
*/
interface CacheHint {
/** Maximum age in seconds */
maxAge?: number;
/** Cache scope */
scope?: CacheScope;
}
/**
* Cache scope enumeration
*/
enum CacheScope {
Public = 'PUBLIC',
Private = 'PRIVATE'
}
/**
* Cache annotation for field-level caching
*/
interface CacheAnnotation {
/** Maximum age */
maxAge: number;
/** Cache scope */
scope: CacheScope;
}
/**
* Mutable cache policy
*/
interface CachePolicy {
/** Maximum age */
maxAge: number;
/** Cache scope */
scope: CacheScope;
/** Replace policy */
replace(hint: CacheHint): void;
/** Restrict policy */
restrict(hint: CacheHint): void;
}Types for Apollo Studio integration and configuration.
/**
* Apollo Studio configuration input
*/
interface ApolloConfigInput {
/** Apollo API key */
key?: string;
/** Graph ID */
graphId?: string;
/** Graph variant */
graphVariant?: string;
/** Graph reference (graphId@graphVariant) */
graphRef?: string;
}
/**
* Processed Apollo configuration
*/
interface ApolloConfig {
/** Apollo API key */
key: string;
/** Graph ID */
graphId: string;
/** Graph variant */
graphVariant: string;
/** Graph reference */
graphRef: string;
}
/**
* Client information interface
*/
interface ClientInfo {
/** Client name */
clientName?: string;
/** Client version */
clientVersion?: string;
/** Client reference ID */
clientReferenceId?: string;
}
/**
* Generate client info function type
*/
type GenerateClientInfo<TContext> = (
requestContext: GraphQLRequestContext<TContext>
) => ClientInfo;Types for usage and schema reporting configuration.
/**
* Base options for sending values to Apollo Studio
*/
interface SendValuesBaseOptions {
/** Send all values */
all?: boolean;
/** Send only these values */
only?: Array<string>;
/** Send all except these values */
except?: Array<string>;
/** Send no values except these */
exceptNames?: Array<string>;
/** Send only these names */
onlyNames?: Array<string>;
}
/**
* Variable value sending options
*/
interface VariableValueOptions extends SendValuesBaseOptions {
/** Transform function for variable values */
transform?: (options: {
variables: VariableValues;
operationString: string;
}) => VariableValues;
}Utility types for common patterns and type manipulation.
/**
* Value or Promise union type
*/
type ValueOrPromise<T> = T | Promise<T>;
/**
* Make specific keys required
*/
type WithRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;
/**
* GraphQL field resolver parameters
*/
interface GraphQLFieldResolverParams<TSource = any, TContext = BaseContext> {
/** Source object */
source: TSource;
/** Field arguments */
args: { [argName: string]: any };
/** Request context */
context: TContext;
/** GraphQL resolve info */
info: GraphQLResolveInfo;
}
/**
* Validation rule function type
*/
type ValidationRule = (context: ValidationContext) => ASTVisitor;
/**
* GraphQL executor function type
*/
type GraphQLExecutor = (
requestContext: GraphQLRequestContext
) => Promise<GraphQLExecutionResult>;
/**
* GraphQL execution result
*/
interface GraphQLExecutionResult {
/** Execution data */
data?: Record<string, any> | null;
/** Execution errors */
errors?: ReadonlyArray<GraphQLError>;
/** Execution extensions */
extensions?: Record<string, any>;
}
/**
* Unsubscriber function type
*/
type Unsubscriber = () => void;
/**
* Schema change callback type
*/
type SchemaChangeCallback = (schema: GraphQLSchema) => void;Types for GraphQL federation and gateway integration.
/**
* Gateway interface for federated schemas
*/
interface GatewayInterface {
/** Load schema */
load(options?: { apollo: ApolloConfig; engine: boolean }): Promise<SchemaDerivedData>;
/** Subscribe to schema changes */
onSchemaChange(callback: SchemaChangeCallback): Unsubscriber;
/** Stop the gateway */
stop?(): Promise<void>;
}
/**
* Legacy gateway interface name
*/
interface GraphQLService extends GatewayInterface {}
/**
* Gateway service configuration
*/
interface GraphQLServiceConfig {
/** Service URL */
url: string;
/** Service name */
name: string;
/** Service headers */
headers?: Record<string, string>;
}
/**
* Schema and derived data
*/
interface SchemaDerivedData {
/** GraphQL schema */
schema: GraphQLSchema;
/** Executor function */
executor?: GraphQLExecutor;
}Types for Express-specific configuration and middleware integration.
/**
* Express-specific Apollo Server configuration
* Extends base Config with Express integration options
*/
interface ApolloServerExpressConfig extends Config {
/** Express app instance (optional - will create if not provided) */
app?: express.Application;
/** GraphQL endpoint path */
path?: string;
/** CORS configuration */
cors?: CorsOptions | boolean;
/** Body parser configuration */
bodyParserConfig?: OptionsJson | boolean;
/** Health check endpoint path */
healthCheckPath?: string;
/** Custom health check function */
onHealthCheck?: (req: express.Request) => Promise<any>;
/** Disable health check endpoint */
disableHealthCheck?: boolean;
}
/**
* Express-specific context parameters
* Passed to context functions in Express integration
*/
interface ExpressContext {
/** Express request object */
req: express.Request;
/** Express response object */
res: express.Response;
}
/**
* Options for applying Apollo Server middleware to Express app
*/
interface GetMiddlewareOptions {
/** GraphQL endpoint path (default: '/graphql') */
path?: string;
/** CORS configuration */
cors?: CorsOptions | boolean;
/** Body parser configuration */
bodyParserConfig?: OptionsJson | boolean;
/** Custom health check function */
onHealthCheck?: (req: express.Request) => Promise<any>;
/** Health check endpoint path */
healthCheckPath?: string;
/** Disable health check endpoint */
disableHealthCheck?: boolean;
/** Express app instance */
app?: express.Application;
}
/**
* Registration object returned when applying middleware to Express app
*/
interface ServerRegistration {
/** Express app with Apollo Server middleware applied */
app: express.Application;
/** GraphQL endpoint path */
path: string;
/** Server instance */
server: ApolloServerExpress;
}
/**
* Body parser JSON configuration options
*/
interface OptionsJson {
/** Request body size limit */
limit?: string | number;
/** Strict JSON parsing */
strict?: boolean;
/** Request type verification function */
type?: string | string[] | ((req: express.Request) => boolean);
/** Character encoding */
encoding?: string;
/** Verify function for request body */
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/** Inflate compressed bodies */
inflate?: boolean;
/** JSON reviver function */
reviver?: (key: string, value: any) => any;
}Types for landing page configuration and customization.
/**
* Landing page configuration
*/
interface LandingPage {
/** Landing page HTML */
html: string;
}
/**
* Landing page base options
*/
interface ApolloServerPluginLandingPageDefaultBaseOptions {
/** Page title */
title?: string;
/** Footer text */
footer?: string;
/** Version information */
version?: string;
}Constants used throughout Apollo Server.
/**
* Automatic Persisted Queries cache prefix
*/
const APQ_CACHE_PREFIX: 'apq:';This comprehensive type system ensures full TypeScript support across all Apollo Server functionality, from basic server setup to advanced plugin development and Apollo Studio integration.