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

Required. Document or documents that represent your server's GraphQL schema, generated by applying the gql tag to valid Schema Definition Language (SDL) strings.

For an example, see Define your GraphQL schema.

resolvers

Object or Array

Required. A map of functions that populate data for individual schema fields. Can also be an array of multiple maps that are merged.

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.

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 the typeDefs and resolvers you provide.

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.

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.

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.

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

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

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 an apollo-server-{integration} package.

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

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

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

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