Launch Apollo Studio

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
});

Options

Name /
Type
Description

Schema options

typeDefs

DocumentNode or Array<DocumentNode>

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.

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.

Required unless you provide schema.

For details, see Resolvers.

context

Object or Function

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.

dataSources

Function

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.

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.

schema

Object

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 most commonly used with Apollo Federation, which uses a special buildFederatedSchema function to generate its schema.

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.

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 the schema.

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-server-caching';
import type { DocumentNode } from 'graphql';
new ApolloServer({
  documentStore: new InMemoryLRUCache<DocumentNode>({
    maxSize: Math.pow(2, 20) * approximateDocumentStoreMiB,
    sizeCalculator: InMemoryLRUCache.jsonBytesSizeCalculator,
  }),
})

Do not share a documentStore between multiple ApolloServer instances, unless you assign a unique prefix to each instance's entries (for example, using PrefixingKeyValueCache). Apollo Server skips parsing and validating any operation that's present in its documentStore, so if servers with different schemas share the same documentStore, a server might execute an operation that its schema doesn't support.

Pass null to disable this cache entirely.

Available in Apollo Server v3.4.0 and later.

Networking options

formatError

Function

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.

formatResponse

Function

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.

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 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

plugins

Array

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.

stopOnTerminationSignals

Boolean

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

debug

Boolean

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.

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), 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.

mocks

Boolean or Object

If true, enables default mock resolvers for schema fields. If an object, enables custom mock resolvers based on the object's fields.

mockEntireSchema

Boolean

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.

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 (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.

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
healthCheckPath

string or null

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.

onHealthCheck

Function

A custom function to execute when Apollo Server receives a request at the HTTP-level health check endpoint.

cors

Object or Boolean

An Object containing configuration options for the server's CORS behavior. Provide false to remove CORS middleware entirely.

stopGracePeriodMillis

number

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:

MiddlewareContext fields
AWS Lambda{
  event: APIGatewayProxyEvent,
  context: LambdaContext,
  express: {
    req: express.Request,
    res: express.Response
  }
}
Azure Functions{
  request: HttpRequest,
  context: Context
}
Cloudflare{ req: Request }
Express (including apollo-server){
  req: express.Request,
  res: express.Response
}
Fastify{
  request: FastifyRequest,
  reply: FastifyReply
}
Google Cloud Functions{ req: Request, res: Response }
hapi{
  request: hapi.Request,
  h: hapi.ResponseToolkit
}
Koa{ ctx: Koa.Context }
Micro{ req: MicroRequest, res: 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 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
url

String

The URL that the server is listening on.

server

http.Server

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, call listen 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:

  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.

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 the stopGracePeriodMillis 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.

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.

index.ts
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,
    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
app

HttpServer

Required for applyMiddleware (not supported for getMiddleware/getHandler). The server middleware instance to integrate with Apollo Server.

path

String

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 /.

cors

Object or Boolean

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.

bodyParserConfig

Object or Boolean

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.

onHealthCheck

Function

A custom function to execute when Apollo Server receives a request at its health checks endpoint.

For details, see Health checks.

disableHealthCheck

Boolean

If true, Apollo Server disables its health checks endpoint.

The default value is false.

Edit on GitHub