API Reference: ApolloServer
This API reference documents the ApolloServer
class.
There are multiple implementations of ApolloServer
for different web frameworks with slightly different behavior.
constructor
Returns an initialized ApolloServer
instance.
Takes an options
object as a parameter. Supported fields of this object are described below.
Example
const server = new ApolloServer({typeDefs,resolvers,csrfPrevention: true, // highly recommendedcache: 'bounded',});
Options
Name / Type | Description |
---|---|
Schema options | |
| Document or documents that represent your server's GraphQL schema, generated by applying the Required unless you provide 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. Required unless you provide For details, see Resolvers. |
| An object (or a function that creates an object) that's passed to every resolver that executes for a particular operation. This enables resolvers to share helpful context, such as a database connection. Certain fields are added to this object automatically, depending on which Node.js middleware your server uses. For more details, see The |
| A function that returns an object containing For more details, see Adding data sources to Apollo Server. |
| If The default value is |
| An executable GraphQL schema. You usually don't need to provide this value, because Apollo Server generates it from This field is most commonly used with Apollo Federation, which uses a special |
| If you're using automated persisted queries (APQ), you can provide an object with |
| 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 the schema. |
| 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 Available in Apollo Server v3.4.0 and later. |
| A By default, the cache that Apollo Server 3 uses is unbounded. We strongly recommend that all users pass The default bounded cache is an To learn more about configuring Apollo Server's cache, see Configuring cache backends. |
Networking options | |
| Passing |
| Provide this function to transform the structure of error objects before they're sent to a client. The function takes a |
| Provide this function to transform the structure of GraphQL response objects before they're sent to a client. The function takes a |
| 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 | |
| An array of plugins to install in your server instance. Each array element can be either a valid plugin object or a zero-argument function that returns a valid plugin object. In certain cases, Apollo Server installs some of its built-in plugins automatically (for example, when you provide an Apollo Studio API key with the |
| By default (when running in Node when the 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 |
| If |
| If The default value is |
| If this is set to any string value, use that value instead of the environment variable |
apollo-server
-specific options
These options are only part of the batteries-included apollo-server
package. They do not exist in framework integrations.
Name / Type | Description |
---|---|
| Disable HTTP-level health checks by passing |
| A custom function to execute when Apollo Server receives a request at the HTTP-level health check endpoint. |
| An |
| The amount of time to wait after The default value is |
Middleware-specific context
fields
The context
object passed between Apollo Server resolvers automatically includes certain fields, depending on which Node.js middleware you're using:
Middleware | Context fields |
---|---|
AWS Lambda | { |
Azure Functions | { |
Cloudflare | { req: |
Express (including apollo-server ) | { |
Fastify | { |
Google Cloud Functions | { req: |
hapi | { |
Koa | { ctx: |
Micro | { req: |
listen
This method is provided only by the apollo-server
package. If you're integrating with Node.js middleware via a different package (such as apollo-server-express
), instead see both start
and the framework-specific middleware function.
Instructs Apollo Server to begin listening for incoming requests:
await server.listen({port: 4001,});
Takes an options
object as a parameter, which is passed to the listen
method of http.Server
. Supported options are listed in the documentation for net.Server.listen
.
Returns a Promise
that resolves to an object containing the following properties:
Name / Type | Description |
---|---|
| The URL that the server is listening on. |
| The server instance that's listening at |
start
The async start
method instructs Apollo Server to prepare to handle incoming operations.
Call start
only if you are using a middleware integration for a non-"serverless" environment (e.g., apollo-server-express
).
- If you're using the core
apollo-server
library, calllisten
instead. - If you're using a "serverless" middleware integration (such as
apollo-server-lambda
), this method isn't necessary because the integration doesn't distinguish between starting the server and serving a request.
Always call await server.start()
before calling server.applyMiddleware
and starting your HTTP server. This allows you to react to Apollo Server startup failures by crashing your process instead of starting to serve traffic.
If the only thing you are doing with your server is calling executeOperation
on it (ie, you're not actually starting an HTTP server), you don't have to call start()
; executeOperation
will do that for you.
This method was optional in Apollo Server 2 but is required in Apollo Server 3.
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.
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
- Closes idle connections (i.e., connections with no current HTTP request)
- Closes active connections whenever they become idle
- Waits for all connections to be closed
- After a grace period, if any connections remain active, forcefully close them.
If you're using the batteries-included
apollo-server
package, it does this by default. (You can configure the grace period with thestopGracePeriodMillis
constructor option.) 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 listen()
if you're using the batteries-included apollo-server
package).
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 result = 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 optional argument is passed to
ApolloServer
'scontext
function.- This is helpful when testing that your server's
context
is correctly gathering the values needed from a request.
- This is helpful when testing that your server's
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 |
Framework-specific middleware function
Framework-specific Apollo Server packages (such as apollo-server-express
) each define a method that you use to connect Apollo Server to your web framework. Depending on the package, this function is applyMiddleware
, getMiddleware
, or createHandler
.
You call this method instead of listen
if you're using a framework-specific package. For non-serverless frameworks (Express, Fastify, Hapi, Koa, and Micro), you must call await server.start()
before calling this method.
These functions take an options
object as a parameter. Some supported fields of this object are described below. Not all packages support all options. See your package's description to see what the name of the function is and which options are supported.
Here's an example of using applyMiddleware
with apollo-server-express
.
const express = require('express');const { ApolloServer } = require('apollo-server-express');const { ApolloServerPluginDrainHttpServer } = require('apollo-server-core');const { typeDefs, resolvers } = require('./schema');async function startApolloServer() {const app = express();const httpServer = http.createServer(app);const server = new ApolloServer({typeDefs,resolvers,csrfPrevention: true,cache: 'bounded',plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],});await server.start();// Additional middleware can be mounted at this point to run before Apollo.app.use('*', jwtCheck, requireAuth, checkScope);// Mount Apollo middleware here.server.applyMiddleware({ app, path: '/specialUrl' });await new Promise<void>(resolve => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);return { server, app };}
Options
Name / Type | Description |
---|---|
| Required for |
| The path for Apollo Server to listen on. The default value for framework-specific packages ( The default value for |
| Middleware-specific configuration options for CORS. See available options for your middleware: express | hapi | koa Provide The default value is |
| Middleware-specific configuration options for body parsing. See available options for your middleware: express | koa Provide The default value is |
| A custom function to execute when Apollo Server receives a request at its health checks endpoint. For details, see Health checks. |
| If The default value is |