/
Launch Apollo Studio

API Reference: apollo-server


This API reference documents the exports from the apollo-server package.

class ApolloServer

The core of an Apollo Server implementation. For an example, see Get started with Apollo Server.

Methods

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.

The default value is true, unless the NODE_ENV environment variable is set to production.

schemaDirectives

Object

A map of all custom schema directives used in your schema, if any.

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.

Note that if you are using file uploads, you need to add the Upload scalar to your schema manually before providing it here, as Apollo Server's automatic uploads integration does not apply if you use this particular option..

persistedQueries

Object or false

If you're using automated persisted queries (APQ), you can provide an object with a cache field as the value of this option to customize where Apolllo Server stores the mapping between operation hashes and query strings.

Provide false to disable APQ entirely.

subscriptions

Object or String or false

Provide a String to specify the server's subscription-specific endpoint, or an Object to further configure subscription behavior.

Provide false to disable subscription operations 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

Object

An object containing custom functions to use as additional validation rules when validating the schema.

uploads

Object or Boolean

By default, Apollo Server 2 integrates an outdated version of the graphql-upload npm module into your schema which does not support Node 14. If you provide an object here, it will be passed as the third options argument to that module's processRequest option.

We recommend instead that you pass false here, which will disable Apollo Server's integration with graphql-upload, and instead integrate the latest version of that module directly. This integration will be removed in Apollo Server 3.

Networking options

cors

Object or Boolean

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

This option is used only by the apollo-server package. If you're integrating with Node.js middleware via a different package, instead see applyMiddleware.

cacheControl

Object

An Object containing configuration options for the apollo-cache-control package, including defaultMaxAge, calculateHttpHeaders, and stripFormattedExtensions.

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.
  • graphId: The ID of your graph in Apollo's registry. You can set this with the APOLLO_GRAPH_ID environment variable. Most users will not specify this explicitly and allow Apollo Server to infer the ID from your API key.
  • 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.
engine

Object or Boolean

Deprecated as of Apollo Server v2.18. New projects should instead use Apollo Server's Studio connection plugins. For details, see the migration docs.

An object containing configuration options for connecting Apollo Server to Apollo Studio.

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 and when the NODE_ENV environment variable does not equal test), 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.

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.

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.

This option is used only by the apollo-server package. If you're integrating with Node.js middleware via a different package, it's your responsibility to stop your HTTP server in whatever way is appropriate.

The default value is 10_000 (10 seconds).

Debugging options

playground

Boolean or Object

If truthy, the server hosts GraphQL Playground from its URL. Can be an object to pass configuration options to the playground.

The default value is true, unless the NODE_ENV environment variable is set to production.

Note that introspection must be enabled for GraphQL Playground to function properly.

debug

Boolean

If true, enables development mode helpers and logs messages of all severity levels (debug through error). If false, only warn- and error-level messages are logged.

Defaults to true.

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.

Experimental options

These options are experimental. They might be removed or change at any time, even within a patch release.

Name /
Type
Description
experimental_approximateDocumentStoreMiB

number

Sets the approximate size (in MiB) of the server's DocumentNode cache. The server checks the SHA-256 hash of each incoming operation against cached DocumentNodes, and skips unnecessary parsing and validation if a match is found.

The cache's default size is 30MiB, which is usually sufficient unless the server processes a large number of unique operations.

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
}
Azure Functions{
  request: HttpRequest,
  context: Context
}
Cloudflare{ req: Request }
Express{
  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 }
Subscription configuration fields

Apollo Server supports the following fields of an object you provide to the subscriptions option of the ApolloServer constructor:

Name /
Type
Description
path

String

Required. The URL for the server's subscription-specific endpoint.

keepAlive

Number

The frequency with which the subscription endpoint should send keep-alive messages to open client connections, in milliseconds, if any.

If this value isn't provided, the subscription endpoint doesn't send keep-alive messages.

onConnect

Function

A lifecycle hook that's called whenever a subscription connection is initiated by a client. See an example

onDisconnect

Function

A lifecycle hook that's called whenever a subscription connection is terminated by a client.

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

Instructs Apollo Server to begin listening for incoming requests:

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.

subscriptionsPath

String

The path of the server's subscriptions endpoint.

subscriptionsUrl

String

The full URL of the server's subscriptions endpoint.

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.

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.
Backward compatibility

To ensure backward compatibility, calling await server.start() is optional. If you don't call it yourself, your integration package invokes it when you call server.applyMiddleware. Incoming GraphQL operations wait to execute until Apollo Server has started, and those operations fail if startup fails (a redacted error message is sent to the GraphQL client).

We recommend calling await server.start() yourself, so that your web server doesn't start accepting GraphQL requests until Apollo Server is ready to process them.

applyMiddleware

Connects Apollo Server to the HTTP framework of a Node.js middleware library, such as hapi or express.

You call this method instead of listen if you're using a middleware integration, such as apollo-server-express. You should call await server.start() before calling this method.

Takes an options object as a parameter. Supported fields of this object are described below.

Example
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');

async function startApolloServer() {
  const server = new ApolloServer({
    typeDefs,
    resolvers,
  });
  await server.start();

  const app = express();

  // 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 => app.listen({ port: 4000 }, resolve));
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
  return { server, app };
}
Options
Name /
Type
Description
app

HttpServer

Required. The server middleware instance to integrate with Apollo Server.

path

String

The path for Apollo Server to listen on.

The default value is /graphql.

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.

getMiddleware

Returns an array of the middlewares that together form a complete instance of Apollo Server. Includes middleware for HTTP body parsing, GraphQL Playground, file uploads, and subscriptions.

Unlike applyMiddleware, getMiddleware does not automatically apply Apollo Server middlewares to your application. Instead, this method enables you to apply or omit individual middlewares according to your use case. For an Express or Koa application, you can apply a particular middleware by calling app.use.

The getMiddleware method takes the same options as applyMiddleware, except the app option.

stop

ApolloServer.stop() is an async method that tells all of Apollo Server's background tasks to complete. It calls and awaits all serverWillStop plugin handlers (including the usage reporting plugin's handler, which sends a final usage report to Apollo Studio). This method takes no arguments.

If your server is a federated gateway, stop also stops gateway-specific background activities, such as polling for updated service configuration.

In some circumstances, Apollo Server calls stop automatically when the process receives a SIGINT or SIGTERM signal. See the stopOnTerminationSignals constructor option for details.

If you're using the apollo-server package (which handles setting up an HTTP server for you), this method first stops the HTTP server. Specifically, it:

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

If any connections remain active after a grace period (10 seconds by default), Apollo Server forcefully closes those connections. You can configure this grace period with the stopGracePeriodMillis constructor option.

If you're using a middleware package instead of apollo-server, you should stop your HTTP server before calling ApolloServer.stop().


gql

A template literal tag for wrapping GraphQL strings, such as schema definitions:

const { gql } = require('apollo-server');

const typeDefs = gql`
  type Author {
    name
  }
`;

This converts GraphQL strings into the format that Apollo libraries expect when working with operations and schemas. It also helps tools identify when a string contains GraphQL language (such as to enable syntax highlighting).


makeExecutableSchema

Builds a schema from provided type definitions and resolvers.

The ApolloServer constructor automatically calls this method using the typeDefs and resolvers options you provide, so in most cases you don't need to call it yourself.

This method is defined in the graphql-tools library and is re-exported from apollo-server as a convenience. See its documentation here.


addMockFunctionsToSchema

The addMockFunctionsToSchema method is re-exported from apollo-server as a convenience.

Given an instance of a GraphQLSchema and a mock object, modifies the schema (in place) to return mock data for any valid query that is sent to the server.

If preserveResolvers is set to true, existing resolve functions will not be overwritten to provide mock data. This can be used to mock some parts of the server and not others.

Parameters

  • options: <Object>

    • schema: <GraphQLSchema> (required)

    Pass an executable schema (GraphQLSchema) to be mocked.

    • mocks: <Object>

    Should be a map of types to mock resolver functions, e.g.:

    {
      Type: () => true,
    }

    When mocks is not defined, the default scalar types (e.g. Int, Float, String, etc.) will be mocked.

    • preserveResolvers: <Boolean>

    When true, resolvers which were already defined will not be over-written with the mock resolver functions specified with mocks.

Usage

const { addMockFunctionsToSchema } = require('apollo-server');

// We'll make an assumption that an executable schema
// is already available from the `./schema` file.
const executableSchema = require('./schema');

addMockFunctionsToSchema({
  schema: executableSchema,
  mocks: {
    // Mocks the `Int` scalar type to always return `12345`.
    Int: () => 12345,

    // Mocks the `Movies` type to always return 'Titanic'.
    Movies: () => 'Titanic',
  },
  preserveResolvers: false,
});

graphql-tools exports

The graphql-tools library provides helpful functions (such as makeExecutableSchema above) for creating and manipulating GraphQL schemas. Apollo Server uses many of these functions internally, and it re-exports all of them to support advanced use cases.

Apollo Server uses graphql-tools version 4. For documentation of version 4 functions, see graphql-tools.

For documentation of the latest version of graphql-tools, see the official graphql-tools documentation.

Edit on GitHub