Docs
Try GraphOS

API Reference: ApolloServer


This article documents the ApolloServer class from the @apollo/server package. You can use the ApolloServer class to create an instance of Apollo Server that you can then pass to a web framework integration function (e.g., startStandaloneServer or expressMiddleware).

Check out our Getting Started guide for an example of setting up Apollo Server!

constructor

Returns an initialized ApolloServer instance.

Takes an options object as a parameter. Supported fields of this object are described below.

Example

import { ApolloServer } from '@apollo/server';
const server = new ApolloServer({
typeDefs,
resolvers,
});
import { ApolloServer } from '@apollo/server';
const server = new ApolloServer({
typeDefs,
resolvers,
});

Options

Name /
Type
Description

Specifying a schema

typeDefs

string, DocumentNode, or Array<DocumentNode>

A valid Schema Definition Language (SDL) string, document, or documents that represent your server's GraphQL schema. To generate documents, you can apply the gql tag (from graphql-tag) to valid SDL strings.

Required unless you provide a schema or a gateway.

For an example, see Define your GraphQL schema.

resolvers

Object or Array

A map of functions that populate data for individual schema fields. Can also be an array of multiple maps that are merged.

While technically optional, if you are providing typeDefs, it is strongly recommended that you provide resolvers as well.

For details, see Resolvers.

schema

Object

An executable GraphQL schema. Under the hood, Apollo Server automatically generates this field from typeDefs and resolvers.

This field is helpful if:

  • You are building a subgraph for Apollo Federation, which uses the buildSubgraphSchema function to generate its schema
  • You are using a function like makeExecutableSchema from graphql-tools to create your schema
  • You are using a library that takes a code-first approach (i.e., instead of a schema-first approach) to generate a schema
gateway

Object

You can use this field to integrate your server with Apollo Gateway.

Schema options

introspection

boolean

If true, enables schema introspection by clients. This is required to use tools that figure out your server's schema from talking to it directly, like Apollo Sandbox and GraphQL Playground. (It's not needed for the non-Sandbox version of Apollo Studio Explorer, which uses the schema published in the Studio schema registry instead.)

The default value is true, unless the NODE_ENV environment variable is set to production.

fieldResolver

GraphQLFieldResolver

A custom resolver that will replace Apollo Server's default field resolvers.

rootValue

Any or Function

A value or function called with the parsed Document, creating the root value passed to the GraphQL executor.

Providing a function is useful if you want to use a different root value depending on the operation's details, such as whether it's a query or mutation.

validationRules

Array<Function>

An array containing custom functions to use as additional validation rules when validating operations against the schema. Note that these rules should depend only on the operation and the schema, not on anything else specific to an individual request, as the result of successful validation is cached across requests.

documentStore

KeyValueCache<DocumentNode> or null

A key-value cache that Apollo Server uses to store previously encountered GraphQL operations (as DocumentNodes). It does not store query results.

Whenever Apollo Server receives an incoming operation, it checks whether that exact operation is present in its documentStore. If it's present, Apollo Server can safely skip parsing and validating the operation, thereby improving performance.

The default documentStore is an InMemoryLRUCache with an approximate size of 30MiB. This is usually sufficient unless the server processes a large number of unique operations. Provide this option if you want to change the cache size or store the cache information in an alternate location.

To use InMemoryLRUCache but change its size to an amount approximateDocumentStoreMiB:

import { InMemoryLRUCache } from '@apollo/utils.keyvaluecache';
import type { DocumentNode } from 'graphql';
new ApolloServer({
documentStore: new InMemoryLRUCache<DocumentNode>({
maxSize: Math.pow(2, 20) * approximateDocumentStoreMiB,
sizeCalculation: InMemoryLRUCache.sizeCalculation,
}),
// ...
});

Pass null to disable this cache entirely.

Protocol options

persistedQueries

Object or false

If you're using automated persisted queries (APQ), you can provide an object with cache and/or ttl fields to customize how Apollo Server stores the mapping between operation hashes and query strings, or provide false to disable APQ entirely.

csrfPrevention

boolean or Object

By default, the CSRF prevention feature is enabled to protect Apollo Server from CSRF and XS-Search attacks.

This feature can prevent certain GET requests from executing GraphQL operations if those requests don't specify certain headers. You can configure the headers that allow operation execution by passing a configuration object to this option (e.g., csrfPrevention: { requestHeaders: ['special-header'] }).

If your server has clients that send GET requests and those clients aren't one of Apollo's client libraries (Web, iOS, Kotlin), you might need to modify the configuration of those clients to use this feature. For more details, see the CSRF prevention documentation.

You can disable this recommended security feature by passing false to csrfPrevention.

formatError

Function

Provide this function to transform the structure of error objects before they're sent to a client.

The formatError hook receives two arguments: the first is a GraphQLFormattedError (to be spent with the response), and the second is the original error (wrapped in GraphQLError if thrown by a resolver). This function should return a GraphQLFormattedError object.

apollo

Object

An object containing configuration options for connecting Apollo Server to Apollo Studio. Each field of this object can also be set with an environment variable, which is the recommended method of setting these parameters. All fields are optional. The fields are:

  • key: The graph API key that Apollo Server should use to authenticate with Apollo Studio. You can set this with the APOLLO_KEY environment variable.
  • graphRef: A reference of your graph in Apollo's registry, such as graph-id@my-variant or just graph-id. You can set this with the APOLLO_GRAPH_REF environment variable.
  • graphId: The ID of your graph in Apollo's registry. You can set this with the APOLLO_GRAPH_ID environment variable. You may not specify this if you specify the graph ref.
  • graphVariant: The variant of your graph to associate this server's schema and metrics with. You can set this with the APOLLO_GRAPH_VARIANT environment variable. The default value is current. You may not specify this if you specify the graph ref.
allowBatchedHttpRequests

boolean

Controls whether to allow Batching Queries in a single HTTP Request. Defaults to false. If a request comes in formatted as an array rather than as a single request object, an error will be thrown ( i.e., Operation batching disabled) unless batching is enabled.

Lifecycle options

cache

KeyValueCache

A KeyValueCache which Apollo Server uses for several features, including APQs and full response caching. This cache is also available to Apollo Server's plugins.

The default cache is an InMemoryLRUCache with a default size of roughly 30MiB. (For backwards-compatibility with Apollo Server 3, specifying cache: 'bounded' also selects this default bounded cache.)

To learn more about configuring Apollo Server's cache, see Configuring cache backends.

plugins

Array

An array of plugins to install in your server instance.

You can also add plugins to your server before you start it using the addPlugin method. This might be useful in the event that your plugin needs to access the ApolloServer instance.

Apollo Server comes with several plugins that it installs automatically in their default configuration if certain conditions are met. For example, the usage reporting plugin is installed if you provide a graph API key and a graph ref. Apollo Server skips this automatic installation if you manually provide the plugin (in the plugins array or with the addPlugin method), or if you provide the plugin's corresponding "disabled" plugin (such as ApolloServerPluginUsageReportingDisabled() for ApolloServerPluginUsageReporting). For details, see the API references for these plugins: usage reporting, schema reporting, landing page, cache control, and inline trace.

stopOnTerminationSignals

boolean

By default, whenever Apollo Server receives a SIGINT or SIGTERM signal, it calls await this.stop() on itself. It then sends that same signal to itself to continue process shutdown. Subsequent SIGINT and SIGTERM signals are ignored while Apollo Server awaits this.stop(). Note that this does not happen when NODE_ENV equals test or when Apollo Server is running in serverless mode.

Set this option to false to disable this default behavior, or to true to enable the behavior even when NODE_ENV does equal test.

The signal handler is installed after start() returns successfully.

You can also manually call stop() in other contexts. Note that stop() is asynchronous, so it isn't useful in a process.on('exit') handler.

Debugging options

includeStacktraceInErrorResponses

boolean

If true, stack traces are included in GraphQL responses when errors occur.

Defaults to true unless the NODE_ENV environment variable is production or test.

logger

Logger

An object to use for logging in place of console. If provided, this object must implement all methods of the Logger interface.

If you provide this value, Apollo Server automatically logs all messages of all severity levels (debug through error). It is the responsibility of the logger to determine how to handle logged messages of each level.

This logger is automatically added to the GraphQLRequestContext object that's passed to all Apollo Server plugin functions.

parseOptions

Object

An object that specifies how your server parses GraphQL operations. See graphql-js for the available configuration options.

nodeEnv

string

If this is set to any string value, use that value instead of the environment variable NODE_ENV for the features whose defaults depend on NODE_ENV (such as introspection). Note that passing the empty string here is equivalent to running with the NODE_ENV environment variable unset. This is primarily meant for testing the effects of the NODE_ENV environment variable.

status400ForVariableCoercionErrors

boolean

Set this option to true. It mitigates a regression introduced in Apollo Server v4 where the server returns a 200 status code (instead of 400) when a client query provides invalid variables. Learn more.

Apollo Server v5 will always behave as if this option is true (and will ignore any provided value).

start

The async start method instructs Apollo Server to prepare to handle incoming operations.

Call start only if you are using a framework integration for a non-serverless environment (e.g., expressMiddleware).

  • If you're using a serverless framework integration (such as Lambda), you shouldn't call this method before passing your server into the integration function. Your serverless integration function will take care of starting your server for you.

  • If you're using startStandaloneServer you do not need to start your server before passing it directly to startStandaloneServer.

Always call await server.start() before passing your server into your integration function and starting to accept requests:

const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
});
await server.start();
app.use('/graphql', cors<cors.CorsRequest>(), json(), expressMiddleware(server));
const server = new ApolloServer({
typeDefs,
resolvers,
});
await server.start();
app.use('/graphql', cors(), json(), expressMiddleware(server));

This allows you to react to Apollo Server startup failures by crashing your process instead of starting to serve traffic.

If you are testing your server using executeOperation (i.e., you're not actually starting an HTTP server), you don't need to call start() because executeOperation will do that for you.

Triggered actions

The start method triggers the following actions:

  1. If your server is a federated gateway, it attempts to fetch its schema. If the fetch fails, start throws an error.
  2. Your server calls all of the serverWillStart handlers of your installed plugins. If any of these handlers throw an error, start throws an error.

startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests

Serverless integrations handle starting an Apollo Server instance in the background by calling the startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests method. This method is synchronous and doesn't need to be awaited. This means any errors that occur happen in the background, so you can't immediately handle them. See Building integrations for more details.

This method triggers the same actions as the start() method.

addPlugin

You can use the addPlugin method to add plugins before your server is started. This is helpful when you want to add a plugin that accepts your initialized ApolloServer instance itself, like so:

const server = new ApolloServer({
typeDefs,
plugins: [makeFirstPlugin()],
});
server.addPlugin(makeSecondPlugin(server));
const server = new ApolloServer({
typeDefs,
plugins: [makeFirstPlugin()],
});
server.addPlugin(makeSecondPlugin(server));

assertStarted

Framework integrations should call server.assertStarted() to ensure a server has started before accepting requests. See Building integrations for more details.

stop

ApolloServer.stop() is an async method that tells all of Apollo Server's background tasks to complete. Specifically, it:

  • Calls and awaits all drainServer plugin handlers. These should generally:
    • Stop listening for new connections
    • Close idle connections (i.e., connections with no current HTTP request)
    • Close active connections whenever they become idle
    • Wait for all connections to be closed
    • After a grace period, if any connections remain active, forcefully close them. If you're using startStandaloneServer, this happens by default. Otherwise, you can use the drain HTTP server plugin to drain your HTTP server.
  • Transitions the server to a state where it will not start executing more GraphQL operations.
  • Calls and awaits all serverWillStop plugin handlers (including the usage reporting plugin's handler, which sends a final usage report to Apollo Studio).
  • If your server is a federated gateway, stop also stops gateway-specific background activities, such as polling for updated service configuration.

This method takes no arguments. You should only call it after start() returns successfully (or after you've called startStandaloneServer with your ApolloServer instance).

In some circumstances, Apollo Server calls stop automatically when the process receives a SIGINT or SIGTERM signal. See the stopOnTerminationSignals constructor option for details.

executeOperation

The async executeOperation method is used primarily for testing GraphQL operations through Apollo Server's request pipeline without sending an HTTP request.

const response = await server.executeOperation({
query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
variables: { name: 'world' },
});

The executeOperation method takes two arguments:

  • The first argument is an object describing the GraphQL operation to be executed.
    • Supported fields are listed in the table below.
  • The second argument is the optional options object. This object includes the operation's optional contextValue. This argument is only optional if your server doesn't expect a context value (i.e., your server uses the default context because you didn't explicitly provide another one).
const response = await server.executeOperation({
query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
variables: { name: 'world' },
}, {
contextValue: { userId: 'test' },
});

The response object returned from executeOperation is a GraphQLResponse, which has body and http fields.

Apollo Server 4 supports incremental delivery directives such as @defer and @stream (when combined with an appropriate version of graphql-js), and so the structure of response.body can represent either a single result or multiple results. response.body.kind is either 'single' or 'incremental'. If it is 'single', then incremental delivery has not been used, and response.body.singleResult is an object with data, errors, and extensions fields. If it is 'incremental', then response.body.initialResult is the initial result of the operation, and response.body.subsequentResults is an async iterator that will yield subsequent results. (The precise structure of initialResult and subsequentResults is defined by graphql-js and may change between the current pre-release of graphql-js v17 and its final release; if you write code that processes these values before graphql-js v17 has been released you may have to adapt it when the API is finalized.)

The http field contains an optional numeric status code and a headers map specifying any HTTP status code and headers that should be set.

Below are the available fields for the first argument of executeOperation:

Fields

NameDescription
query

string or DocumentNode

Required. The GraphQL operation to run. Note that you must use the query field even if the operation is a mutation. This may also be a TypedQueryDocumentNode, in which case TypeScript types for the variables option and response.body.singleResult.data will be automatically inferred.

variables

object

An object containing any GraphQL variables to use as argument values for the executed operation.
operationName

string

If query contains more than one operation definition, you must provide this option to indicate which operation to execute.

extensions

object

The extensions object is usually used to pass request metadata within your server from one touch point to another (e.g., from a request to a plugin) during the lifecycle of a request. In this scenario, this object represents the request extensions sent in an actual request.

http

HTTPGraphQLRequest

An object implementing the HTTPGraphQLRequest interface, containing information that pertains to the incoming HTTP request.

executeHTTPGraphQLRequest

The executeHTTPGraphQLRequest method is the main entry point for web framework integrations. You can pass a HTTPGraphQLRequest object to the executeHTTPGraphQLRequest method to execute a GraphQL request:

const result = await server.executeHTTPGraphQLRequest({
httpGraphQLRequest: OurHttpGraphQLRequest,
context: async () => ({
// token: ...,
}),
});
const result = await server.executeHTTPGraphQLRequest({
httpGraphQLRequest: OurHttpGraphQLRequest,
context: async () => ({
// token: ...,
}),
});

For details and examples, see Building Integrations.

cache

A public readonly field on ApolloServer that enables you to access your server's cache.

logger

A public readonly field on ApolloServer that enables you to access your server's logger.

Previous
Health checks
Next
startStandaloneServer
ForumsDiscord