Docs
Launch GraphOS Studio
Apollo Server 3 is officially deprecated, with end-of-life scheduled for 22 October 2024. Learn more about upgrading to a supported Apollo Server version.

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 of this object are described below.

Example

const server = new ApolloServer({
typeDefs,
resolvers,
csrfPrevention: true, // highly recommended
cache: 'bounded',
plugins: [
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
],
});

Options

Name /
Type
Description

Schema options

typeDefs

DocumentNode or Array<DocumentNode>

Document or documents that represent your server's , generated by applying the gql tag to valid () 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 that executes for a particular . 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 . 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 and 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 generates it from typeDefs and resolvers.

This is helpful if:

  • You are building a subgraph for Apollo Federation, which uses the buildSubgraphSchema function to generate its schema
  • You are using a function like makeExecutableSchema from graphql-tools to create your schema
  • You are using a library that takes a code-first approach (i.e., instead of a schema-first approach) to generate a 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 strings, or provide false to disable 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 .

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

Pass null to disable this cache entirely.

Available in Apollo Server v3.4.0 and later.

cache

KeyValueCache | "bounded"

A KeyValueCache which Apollo Server uses for several features, including and full response caching. This cache is also available to Apollo Server's 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

csrfPrevention

Boolean or Object

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 Web, , or , you might need to modify the configuration of those clients before enabling this feature. For more details, see the full CSRF prevention documentation.

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

dangerouslyDisableValidation

Boolean

⚠️ 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 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
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-"" 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 . 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's context 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

NameDescription
query

string or DocumentNode

Required. The GraphQL operation to run. Note that you must use the query field even if the operation is a mutation.

variables

object

An object containing any GraphQL variables to use as argument values for the executed operation.
operationName

string

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.

index.ts
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageLocalDefault } = 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 }), ApolloServerPluginLandingPageLocalDefault({ embed: true })],
});
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 };
}
index.js
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageLocalDefault } = 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 }), ApolloServerPluginLandingPageLocalDefault({ embed: true })],
});
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((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.

Previous
Health checks
Next
Overview
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company