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
1const server = new ApolloServer({
2 typeDefs,
3 resolvers,
4 csrfPrevention: true, // highly recommended
5 cache: 'bounded',
6 plugins: [
7 ApolloServerPluginLandingPageLocalDefault({ embed: true }),
8 ],
9});
Options
Name / Type |
Description |
---|---|
Schema options | |
| Document or documents that represent your server's GraphQL schema, generated by applying the gql tag to valid Schema Definition Language (SDL) strings.Required unless you provide schema .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 schema .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 context argument . |
| A function that returns an object containing DataSource instances for use by your resolvers. The object is automatically added to each operation's context .For more details, see Adding data sources to Apollo Server . |
| 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 . |
| An executable GraphQL schema. You usually don't need to provide this value, because Apollo Server generates it from typeDefs and resolvers .This field is helpful if:
|
| 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. |
| 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 the schema. |
| 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.Available in Apollo Server v3.4.0 and later. |
| A KeyValueCache which Apollo Server uses for several features, including APQs and full response caching. This cache is also available to Apollo Server's data sources and plugins.By default, the cache that Apollo Server 3 uses is unbounded. We strongly recommend that all users pass cache: "bounded" or configure their cache in a manner that isn't unbounded. This protects your server from attacks that exhaust available memory, causing a DOS.The default bounded cache is an InMemoryLRUCache with a default size of roughly 30MiB.To learn more about configuring Apollo Server's cache, see Configuring cache backends . |
Networking options | |
| Passing true enables Apollo Server's CSRF and XS-Search prevention features. This flag is highly recommended for all users and will be enabled by default in Apollo Server 4. Enabling this feature prevents certain GET requests from executing GraphQL operations. If your server has clients that send GET requests and those clients are not one of Apollo Client Web, Apollo iOS, or Apollo Kotlin, you might need to modify the configuration of those clients before enabling this feature. For more details, see the full CSRF prevention documentation . |
| Provide this function to transform the structure of error objects before they're sent to a client. The function takes a GraphQLError object and should return a GraphQLFormattedError object. |
| Provide this function to transform the structure of GraphQL response objects before they're sent to a client. The function takes a GraphQLResponse object and a GraphQLRequestContext object, and it should return a GraphQLResponse object, or null to preserve the existing structure. |
| 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 true . If the GraphQL Server has this flag set to false and a request comes in formatted as an array rather than as a single request object, an error will be thrown. |
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 APOLLO_KEY environment variable). For details, see the API references for these plugins: usage reporting , schema reporting , and inline trace . |
| By default (when running in Node when the NODE_ENV environment variable does not equal test and not using a serverless-specific package ), whenever Apollo Server receives a SIGINT or SIGTERM signal, it calls await this.stop() on itself. (While this call to this.stop() is running, it ignores all SIGINT and SIGTERM signals.) It then sends that same signal to itself to continue process shutdown.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, and some extra information is logged via the logger at the debug level.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 ), regardless of whether the debug option is set to true . 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 . |
| If true , enables default mock resolvers for schema fields. If an object, enables custom mock resolvers based on the object's fields. |
| If true and mocks is also specified, mock resolvers are enabled even for fields that you've defined a resolver for.The default value is true . Set this to false to use mocked resolvers only for fields that you haven't defined a resolver for. |
| 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 (like the debug and introspection options). 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. |
| ⚠️ 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. |
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 null , or change the path on which it is served from the default of /.well-known/apollo/server-health . |
| A custom function to execute when Apollo Server receives a request at the HTTP-level health check endpoint. |
| An Object containing configuration options for the server's CORS behavior. Provide false to remove CORS middleware entirely. |
| The amount of time to wait after ApolloServer.stop() is called (including via a termination signal ) before forcefully closing all active connections. If you pass Infinity , Apollo Server waits indefinitely for all active connections to go idle.The default value is 10_000 (10 seconds). |
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 | Reference Links |
---|---|---|
AWS Lambda | js { event: APIGatewayProxyEvent, context: LambdaContext, express: { req: express.Request, res: express.Response } } | - APIGatewayProxyEvent - LambdaContext - express.Request - express.Response |
Azure Functions | js { request: HttpRequest, context: Context } | - HttpRequest - Context |
Cloudflare | js { req: Request } | - Request |
Express (including apollo-server ) | js { req: express.Request, res: express.Response } | - express.Request - express.Response |
Fastify | js { request: FastifyRequest, reply: FastifyReply } | - FastifyRequest - FastifyReply |
Google Cloud Functions | js { req: Request, res: Response } | - Request - Response |
hapi | js { request: hapi.Request, h: hapi.ResponseToolkit } | - hapi.Request - hapi.ResponseToolkit |
Koa | js { ctx: Koa.Context } | - Koa.Context |
Micro | js { req: MicroRequest, res: ServerResponse } | - MicroRequest - ServerResponse |
listen
This method is provided only by the
apollo-server
package. If you're integrating with Node.js middleware via a different package (such asapollo-server-express
), instead see bothstart
and the framework-specific middleware function .
Instructs Apollo Server to begin listening for incoming requests:
1await server.listen({
2 port: 4001,
3});
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 url . |
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.
1const result = 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 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.
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. |
| 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. |
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
.
1const express = require('express');
2const { ApolloServer } = require('apollo-server-express');
3const {
4 ApolloServerPluginDrainHttpServer,
5 ApolloServerPluginLandingPageLocalDefault
6} = require('apollo-server-core');
7const { typeDefs, resolvers } = require('./schema');
8
9async function startApolloServer() {
10 const app = express();
11 const httpServer = http.createServer(app);
12 const server = new ApolloServer({
13 typeDefs,
14 resolvers,
15 csrfPrevention: true,
16 cache: 'bounded',
17 plugins: [
18 ApolloServerPluginDrainHttpServer({ httpServer }),
19 ApolloServerPluginLandingPageLocalDefault({ embed: true }),
20 ],
21 });
22
23 await server.start();
24
25 // Additional middleware can be mounted at this point to run before Apollo.
26 app.use('*', jwtCheck, requireAuth, checkScope);
27
28 // Mount Apollo middleware here.
29 server.applyMiddleware({ app, path: '/specialUrl' });
30 await new Promise<void>(resolve => httpServer.listen({ port: 4000 }, resolve));
31 console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
32 return { server, app };
33}
Options
Name / Type |
Description |
---|---|
| Required for applyMiddleware (not supported for getMiddleware /getHandler ). The server middleware instance to integrate with Apollo Server. |
| The path for Apollo Server to listen on.The default value for framework-specific packages (apollo-server-express , apollo-server-fastify , etc) is /graphql .The default value for apollo-server and serverless-specific packages (apollo-server-lambda , etc) is / . |
| Middleware-specific configuration options for CORS. See available options for your middleware: express | hapi | koa Provide false to remove CORS middleware entirely, or true to use your middleware's default configuration.The default value is true . |
| Middleware-specific configuration options for body parsing. See available options for your middleware: express | koa Provide false to remove body parsing middleware entirely, or true to use your middleware's default configuration.The default value is true . |
| A custom function to execute when Apollo Server receives a request at its health checks endpoint.For details, see Health checks . |
| If true , Apollo Server disables its health checks endpoint .The default value is false . |