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 | |
| A valid Schema Definition Language (SDL) string, document, or documents that represent your server's GraphQL schema. To generate documents, you can apply the Required unless you provide a 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 For details, see Resolvers. |
| An executable GraphQL schema. Under the hood, Apollo Server automatically generates this field from This field is helpful if:
|
| You can use this field to integrate your server with Apollo Gateway. |
Schema options | |
| If The default value is |
| A custom resolver that will replace Apollo Server's default field resolvers. |
| A value or function called with the parsed 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 Whenever Apollo Server receives an incoming operation, it checks whether that exact operation is present in its The default To use
Pass |
Protocol options | |
| If you're using automated persisted queries (APQ), you can provide an object with |
| By default, the CSRF prevention feature is enabled to protect Apollo Server from CSRF and XS-Search attacks. This feature can prevent certain If your server has clients that send You can disable this recommended security feature by passing |
| Provide this function to transform the structure of error objects before they're sent to a client. The |
| 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 |
Lifecycle options | |
| A The default cache is an 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 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 |
| By default, whenever Apollo Server receives a Set this option to The signal handler is installed after You can also manually call |
Debugging options | |
| If Defaults to |
| An object to use for logging in place of If you provide this value, Apollo Server automatically logs all messages of all severity levels ( This logger is automatically added to the |
| An object that specifies how your server parses GraphQL operations. See |
| If this is set to any string value, use that value instead of the environment variable |
| Set this option to Apollo Server v5 will always behave as if this option is |
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:
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:
- 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:
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
Name | Description |
---|---|
| Required. The GraphQL operation to run. Note that you must use the |
| An object containing any GraphQL variables to use as argument values for the executed operation. |
| If |
| The |
| An object implementing the |
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.