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
1import { ApolloServer } from '@apollo/server';
2
3const server = new ApolloServer({
4 typeDefs,
5 resolvers,
6});
Options
Name / Type |
Description |
---|---|
Specifying a schema | |
| 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. |
| 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. |
| An executable GraphQL schema. Under the hood, Apollo Server automatically generates this field from typeDefs and resolvers .This field is helpful if:
|
| You can use this field to integrate your server with Apollo Gateway. |
Schema options | |
| 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 . |
| If true , Apollo Server strips out "did you mean" suggestions when an operation fails validation.For example, with this option set to true , an error would read Cannot query field "help" on type "Query". . With this option set to false , the same error would read Cannot query field "help" on type "Query". Did you mean "hello"? .The default value is false , but Apollo recommends enabling this option in production to avoid leaking information about your schema. |
| A custom resolver that will replace Apollo Server's default field resolvers. |
| 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. |
| 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. |
| A key-value cache that Apollo Server uses to store previously encountered GraphQL operations (as DocumentNode s). 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 :TypeScript
null to disable this cache entirely. |
Protocol options | |
| 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. |
| 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 . |
| 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 sent 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. |
| 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:
|
| 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 | |
| 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. |
| 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. |
| 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 | |
| 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 . |
| 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. |
| An object that specifies how your server parses GraphQL operations. See graphql-js for the available configuration options. |
| 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. |
| 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). |
| ⚠️ Caution: this option can lead to security vulnerabilities and unexpected
behavior. Use of this option in production is not supported by Apollo.When set to true , disable validation of graphql operations entirely.You might find this option interesting for performance reasons if you handle
operation validation at build time and enforce that only known, validated
operations are allowed to be executed at runtime. Note that validation of
operations is cached in Apollo Server's document store. |
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 tostartStandaloneServer
.
Always call await server.start()
before passing your server into your integration function and starting to accept requests:
1const server = new ApolloServer<MyContext>({
2 typeDefs,
3 resolvers,
4});
5await server.start();
6
7app.use(
8 '/graphql',
9 cors<cors.CorsRequest>(),
10 express.json(),
11 expressMiddleware(server),
12);
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:
If your server is a federated gateway, it attempts to fetch its schema. If the fetch fails,
start
throws an error.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:
1const server = new ApolloServer({
2 typeDefs,
3 plugins: [makeFirstPlugin()],
4});
5
6server.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.
1const response = await server.executeOperation({
2 query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
3 variables: { name: 'world' },
4});
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).
1const response = await server.executeOperation({
2 query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
3 variables: { name: 'world' },
4}, {
5 contextValue: { userId: 'test' },
6});
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
Name | Description |
---|---|
| 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. |
| An object containing any GraphQL variables to use as argument values for the executed operation. |
| If query contains more than one operation definition, you must provide this option to indicate which operation to execute. |
| 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. |
| 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:
1const result = await server.executeHTTPGraphQLRequest({
2 httpGraphQLRequest: OurHttpGraphQLRequest,
3 context: async () => ({
4 // token: ...,
5 }),
6});
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.