Apollo Server is a production-ready TypeScript GraphQL server that provides a batteries-included Express setup. It handles creating the Express app and HTTP server automatically, while offering flexible deployment options, built-in performance optimizations, and comprehensive tooling for development and production monitoring.
npm install apollo-server graphqlimport { ApolloServer, gql } from 'apollo-server';For CommonJS:
const { ApolloServer, gql } = require('apollo-server');import { ApolloServer, gql } from 'apollo-server';
// Define GraphQL schema using template literal
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
// Define resolvers
const resolvers = {
Query: {
books: () => [
{ title: 'The Awakening', author: 'Kate Chopin' },
{ title: 'City of Glass', author: 'Paul Auster' },
],
},
};
// Create server instance
const server = new ApolloServer({
typeDefs,
resolvers,
// Optional configuration
cors: true,
introspection: true,
playground: true
});
// Start the server
server.listen({ port: 4000 }).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});Apollo Server is built around several key components:
Core server classes for creating GraphQL servers. Includes both the base server class and the batteries-included Express integration.
// Base server class with core GraphQL functionality
class ApolloServerBase<ContextFunctionParams = any> {
constructor(config: Config<ContextFunctionParams>);
start(): Promise<void>;
stop(): Promise<void>;
executeOperation(request: GraphQLRequest, contextValue?: ContextFunctionParams): Promise<GraphQLResponse>;
}
// Batteries-included Express server
class ApolloServer extends ApolloServerExpress {
constructor(config: ApolloServerExpressConfig & {
cors?: CorsOptions | boolean;
onHealthCheck?: (req: express.Request) => Promise<any>;
healthCheckPath?: string | null;
stopGracePeriodMillis?: number;
});
listen(...opts: Array<any>): Promise<ServerInfo>;
}
interface ServerInfo {
address: string;
family: string;
url: string;
port: number | string;
server: http.Server;
}GraphQL template literal tag for parsing GraphQL documents with syntax highlighting and validation.
function gql(template: TemplateStringsArray | string, ...substitutions: any[]): DocumentNode;The gql function is used to define GraphQL schemas and queries with proper parsing and validation.
Comprehensive plugin system with 12+ built-in plugins for metrics, caching, landing pages, and Apollo Studio integration. Plugins provide extensible hooks into the request lifecycle.
interface ApolloServerPlugin<TContext = BaseContext> {
serverWillStart?(service: GraphQLServiceContext): Promise<GraphQLServerListener | void>;
requestDidStart?(requestContext: GraphQLRequestContext<TContext>): Promise<GraphQLRequestListener<TContext> | void>;
}Key plugins include:
Specialized GraphQL error classes with proper formatting and extensions. Provides structured error handling with Apollo-specific error codes.
class ApolloError extends Error {
constructor(message: string, code?: string, extensions?: Record<string, any>);
}
class AuthenticationError extends ApolloError;
class ForbiddenError extends ApolloError;
class UserInputError extends ApolloError;
class ValidationError extends ApolloError;
class SyntaxError extends ApolloError;
function toApolloError(error: Error, code?: string): Error & { extensions: Record<string, any> };Complete TypeScript type definitions covering configuration, context management, request/response lifecycle, and plugin development.
interface Config {
typeDefs?: TypeSource;
resolvers?: IResolvers | Array<IResolvers>;
schemaDirectives?: SchemaDirectiveVisitorClass;
context?: Context<ContextFunctionParams> | ContextFunction<ContextFunctionParams, any>;
// ... additional configuration options
}
interface GraphQLRequestContext<TContext = BaseContext> {
readonly request: GraphQLRequest;
readonly response?: GraphQLResponse;
readonly context: TContext;
readonly cache: KeyValueCache;
// ... additional context properties
}HTTP request handling and GraphQL execution utilities for integration development.
function convertNodeHttpToRequest(req: NodeHttpRequest): GraphQLRequest;
function runHttpQuery(options: HttpQueryOptions): Promise<GraphQLResponse>;
interface HttpQueryOptions {
method: string;
query: any;
options: GraphQLOptions;
request: any;
}These utilities are primarily used for creating custom Apollo Server integrations.