Core ApolloServer class providing GraphQL server initialization, lifecycle management, and request execution capabilities.
Main GraphQL server class that handles schema management, plugin initialization, and request processing.
/**
* Apollo GraphQL server implementation
* @template TContext - The type of the GraphQL context object
*/
class ApolloServer<in out TContext extends BaseContext = BaseContext> {
/** Cache instance used by the server */
readonly cache: KeyValueCache<string>;
/** Logger instance used by the server */
readonly logger: Logger;
/**
* Creates a new Apollo Server instance
* @param config - Server configuration options
*/
constructor(config: ApolloServerOptions<TContext>);
/**
* Starts the Apollo Server, loading schema and initializing plugins
* Must be called before handling requests (except serverless environments)
*/
start(): Promise<void>;
/**
* Starts server in background for serverless frameworks
* Startup errors are logged and requests fail with generic errors
*/
startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests(): void;
/**
* Stops the Apollo Server and cleans up resources
* Should be called after successful start()
*/
stop(): Promise<void>;
/**
* Ensures the server has been started before handling requests
* @param expressionForError - Expression name for error message
* @throws Error if server not started
*/
assertStarted(expressionForError: string): void;
/**
* Executes a GraphQL operation directly (primarily for testing)
* @param request - GraphQL request object
* @param options - Execution options including context
* @returns Promise resolving to GraphQL response
*/
executeOperation<TData = Record<string, unknown>, TVariables extends VariableValues = VariableValues>(
request: Omit<GraphQLRequest<TVariables>, 'query'> & {
query?: string | DocumentNode | TypedQueryDocumentNode<TData, TVariables>;
},
options?: ExecuteOperationOptions<TContext>
): Promise<GraphQLResponse<TData>>;
/**
* Executes a GraphQL request from HTTP context
* Used by framework integrations to process HTTP requests
* @param params - HTTP request and context
* @returns Promise resolving to HTTP response
*/
executeHTTPGraphQLRequest(params: {
httpGraphQLRequest: HTTPGraphQLRequest;
context: ContextThunk<TContext>;
}): Promise<HTTPGraphQLResponse>;
/**
* Adds a plugin to the server
* Can only be called before start() is invoked
* @param plugin - Plugin to add
* @throws Error if called after startup
*/
addPlugin(plugin: ApolloServerPlugin<TContext>): void;
}Configuration options for creating an Apollo Server instance.
/**
* Apollo Server configuration options
* Union of different configuration approaches
*/
type ApolloServerOptions<TContext extends BaseContext> =
| ApolloServerOptionsWithSchema<TContext>
| ApolloServerOptionsWithTypeDefs<TContext>
| ApolloServerOptionsWithGateway<TContext>;
/**
* Configuration with pre-built GraphQL schema
*/
interface ApolloServerOptionsWithSchema<TContext extends BaseContext> {
/** Pre-built GraphQL schema */
schema: GraphQLSchema;
/** Array of plugins to install */
plugins?: ApolloServerPlugin<TContext>[];
/** Custom error formatting function */
formatError?: (formattedError: GraphQLFormattedError, error: unknown) => GraphQLFormattedError;
/** Cache implementation or 'bounded' for default */
cache?: KeyValueCache<string> | 'bounded';
/** Logger implementation */
logger?: Logger;
/** Enable/disable GraphQL introspection */
introspection?: boolean;
/** CSRF prevention configuration */
csrfPrevention?: CSRFPreventionOptions | boolean;
/** Include stacktraces in error responses */
includeStacktraceInErrorResponses?: boolean;
/** Custom field resolver */
fieldResolver?: GraphQLFieldResolver<any, TContext>;
/** Persisted queries configuration */
persistedQueries?: PersistedQueryOptions;
/** Stop server on termination signals */
stopOnTerminationSignals?: boolean;
/** Apollo Studio configuration */
apollo?: ApolloConfigInput;
/** Node environment override */
nodeEnv?: string;
}
/**
* Configuration with type definitions and resolvers
*/
interface ApolloServerOptionsWithTypeDefs<TContext extends BaseContext>
extends Omit<ApolloServerOptionsWithSchema<TContext>, 'schema'> {
/** GraphQL type definitions */
typeDefs: TypeSource;
/** GraphQL resolvers */
resolvers?: IResolvers;
}
/**
* Configuration with Apollo Gateway for federation
*/
interface ApolloServerOptionsWithGateway<TContext extends BaseContext>
extends Omit<ApolloServerOptionsWithSchema<TContext>, 'schema'> {
/** Apollo Gateway instance */
gateway: GatewayInterface;
}Types for direct operation execution and HTTP request handling.
/**
* Options for executeOperation method
*/
interface ExecuteOperationOptions<TContext extends BaseContext> {
/** Context value for the operation */
contextValue?: TContext;
}
/**
* GraphQL operation request
*/
interface GraphQLRequest<TVariables = VariableValues> {
/** GraphQL query string or AST */
query?: string | DocumentNode;
/** Operation name for multi-operation documents */
operationName?: string;
/** Variables for the operation */
variables?: TVariables;
/** Extensions object */
extensions?: Record<string, any>;
/** HTTP-specific information */
http?: HTTPGraphQLHead;
}
/**
* GraphQL operation response
*/
interface GraphQLResponse<TData = Record<string, unknown>> {
/** HTTP response metadata */
http: HTTPGraphQLHead;
/** Response body (single result or incremental) */
body: GraphQLResponseBody<TData>;
}
/**
* Variable values type
*/
type VariableValues = { [name: string]: any };import { ApolloServer } from "@apollo/server";
const server = new ApolloServer({
typeDefs: `
type Query {
books: [Book]
}
type Book {
title: String
author: String
}
`,
resolvers: {
Query: {
books: () => [
{ title: "The Awakening", author: "Kate Chopin" },
{ title: "City of Glass", author: "Paul Auster" },
],
},
},
});
// Start the server
await server.start();interface MyContext {
user?: User;
dataSources: {
booksAPI: BooksAPI;
};
}
const server = new ApolloServer<MyContext>({
schema: mySchema,
formatError: (formattedError, error) => {
// Custom error formatting
console.error(error);
return formattedError;
},
});// Useful for testing
const response = await server.executeOperation({
query: `
query GetBooks {
books {
title
author
}
}
`,
}, {
contextValue: {
user: currentUser,
dataSources: { booksAPI: new BooksAPI() },
},
});
console.log(response.body.kind === 'single' ? response.body.singleResult : null);// Proper server lifecycle management
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
// Handle shutdown signals
process.on('SIGINT', async () => {
console.log('Shutting down server...');
await server.stop();
process.exit(0);
});