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.



Returns an initialized ApolloServer instance.

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

const server = new ApolloServer({
Name /

Schema options


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.


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.


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.



If true, enables schema introspection by clients.

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



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



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.


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.


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.


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.



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

Networking options



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

Supported fields are described in EngineReportingOptions.


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.



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



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.

Debugging options


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.



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.



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.


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.



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 /


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 }
  req: express.Request,
  res: express.Response
  request: FastifyRequest,
  reply: FastifyReply
Google Cloud Functions{ req: Request, res: Response }
  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 /


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



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.



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



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


Instructs Apollo Server to begin listening for requests.

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.

  • options: <Object>

    When using the apollo-server package, calling listen on an instantiated ApolloServer will start the server by passing the specified (optional) options to a Node.js http.Server. For a full reference of the supported options, see the documentation for net.Server.listen.


Promise that resolves to an object containing the following properties:

  • url: <String>
  • subscriptionsPath: <String>
  • server: <http.Server>


The applyMiddleware method is provided by the apollo-server-{integration} packages that use middleware, such as hapi and express. This method connects ApolloServer to a specific HTTP framework.

  • options: <Object>

    • app: <HttpServer> (required)

    Pass an instance of the server integration here.

    • path : <String>

    Specify a custom path. It defaults to /graphql if no path is specified.

    Pass the integration-specific cors options. False removes the cors middleware and true uses the defaults.

    • bodyParserConfig: <Object | boolean> (express, koa)

    Pass the body-parser options. False removes the body parser middleware and true uses the defaults.


The applyMiddleware method from apollo-server-express registration of middleware as shown in the example below:

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

const server = new ApolloServer({
  // These will be defined for both new or existing servers

const app = express();
// Additional middleware can be mounted at this point to run before Apollo.
app.use('*', jwtCheck, requireAuth, checkScope);

server.applyMiddleware({ app, path: '/specialUrl' }); // app is from an existing express app. Mount Apollo middleware here. If no path is specified, it defaults to `/graphql`.


Similar to the applyMiddleware method above, though rather than applying the composition of the various Apollo Server middlewares which comprise a full-featured Apollo Server deployment (e.g. middleware for HTTP body parsing, GraphQL Playground, uploads and subscriptions) the getMiddleware simply returns the middleware.

The getMiddleware method takes the same arguments as applyMiddleware except app should not be passed. Instead, the result of getMiddleware must be added as a middleware directly to an existing application (e.g. with app.use(...)).

For example, for apollo-server-express, this means that rather than passing applyMiddleware an app which was already initiated from calling express(), and applyMiddleware "using" (i.e. app.use), the implementor will instead call app.use(...) on the result of getMiddleware with the same arguments.


The gql is a template literal tag. Template literals were introduced in recent versions of ECMAScript to provide embedded expressions (i.e. `A string with interpolated ${variables}`) and template literal tags exist to provide additional functionality for what would otherwise be a normal template literal.

In the case of GraphQL, the gql tag is used to surround GraphQL operation and schema language (which are represented as Strings), and makes it easier to differentiate from ordinary strings. This is particularly useful when performing static analysis on GraphQL language (e.g. to enable syntax highlighting, code generation, etc.) and avoids need for tools to "guess" if a string contains GraphQL language.


Import the gql template literal tag into the current context from the apollo-server or apollo-server-{integration} modules:

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

Then, place GraphQL schema definitions (SDL), queries or other operations into the gql template literal tag. Keep in mind that template literals use the grave accent (`) and not normal quotation marks (e.g. not " or '):

const typeDefs = gql`
  type Author {


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


  • options : <Object>

    • typeDefs: <GraphQLSchema> (required)
    • resolvers : <Object> : <Array<Object>>
    • logger : <Object>
    • allowUndefinedInResolve = false
    • resolverValidationOptions = {}
    • directiveResolvers = null
    • schemaDirectives = null
    • parseOptions = {}
    • inheritResolversFromInterfaces = false


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.


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


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

  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,


  • apiKey: string (required)

API key for the service. Obtain an API key from Apollo Studio by logging in and creating a service. You can also specify an API key with the APOLLO_KEY environment variable. If you specify both, the apiKey option takes precedence.

  • logger: Logger

    By default, this will inherit from the logger provided to ApolloServer which defaults to console when not provided. If specified within the EngineReportingOptions it can be used to send engine reporting to a separate logger. If provided, the implementation must provide the methods which satisfy the requirements of the Logger interface (i.e. it must provide debug, info, warn and error methods).

  • calculateSignature: (ast: DocumentNode, operationName: string) => string

    Specify the function for creating a signature for a query.

    See apollo-graphql's signature.ts for more information on how the default signature is generated.

  • reportIntervalMs: number

    How often to send reports to Apollo Studio, in milliseconds. We'll also send reports when the report reaches a size threshold specified by maxUncompressedReportSize.

  • maxUncompressedReportSize: number

    In addition to interval-based reporting, Apollo Server sends a report to Apollo Studio whenever the report's size exceeds this value in bytes (default: 4MB). Note that this is a rough limit. The size of the report's header and some other top-level bytes are ignored. The report size is limited to the sum of the lengths of serialized traces and signatures.

  • endpointUrl: string

    The URL of the Apollo Studio report ingress server.

  • requestAgent: http.Agent | https.Agent | false

    HTTP(s) agent to be used for Apollo Studio metrics reporting. This accepts either an http.Agent or https.Agent and behaves the same as the agent parameter to Node.js' http.request.

  • debugPrintReports: boolean

    If set, prints all reports as JSON when they are sent.

  • maxAttempts: number

    Reporting is retried with exponential backoff up to this many times (including the original request). Defaults to 5.

  • minimumRetryDelayMs: number

    Minimum backoff for retries. Defaults to 100ms.

  • reportErrorFunction: (err: Error) => void

    By default, any errors encountered while sending reports to Apollo Studio are logged to standard error. Specify this function to process errors in a different way.

  • sendVariableValues: { transform: (options: { variables: Record<string, any>, operationString?: string } ) => Record<string, any> } | { exceptNames: Array<String> } | { onlyNames: Array<String> } | { none: true } | { all: true }

    By default, Apollo Server does not send the values of any GraphQL variables to Apollo's servers, because variable values often contain the private data of your app's users. If you'd like variable values to be included in traces, set this option. This option can take several forms:

    • { none: true }: Don't send any variable values. (DEFAULT)
    • { all: true }: Send all variable values.
    • { transform: ({ variables, operationString}) => { ... } }: A custom function for modifying variable values. Keys added by the custom function will be removed, and keys removed will be added back with an empty value. For security reasons, if an error occurs within this function, all variable values will be replaced with [PREDICATE_FUNCTION_ERROR].
    • { exceptNames: [...] }: A case-sensitive list of names of variables whose values should not be sent to Apollo servers.
    • { onlyNames: [...] }: A case-sensitive list of names of variables whose values will be sent to Apollo servers.

    Defaults to not sending any variable values if both this parameter and the deprecated privateVariables are not set. The report will indicate each private variable key whose value was redacted by { none: true } or { exceptNames: [...] }.

  • privateVariables: Array<String> | boolean

    Will be deprecated in 3.0. Use the option sendVariableValues instead. Passing an array into privateVariables is equivalent to passing in { exceptNames: array } to sendVariableValues, and passing in true or false is equivalent to passing { none: true } or { all: true }, respectively.

    Note: An error will be thrown if both this deprecated option and its replacement, sendVariableValues are defined. In order to preserve the old default of privateVariables, which sends all variables and their values, pass in the sendVariableValues option: new ApolloServer({engine: {sendVariableValues: {all: true}}}).

  • sendHeaders: { exceptNames: Array<String> } | { onlyNames: Array<String> } | { all: boolean } | { none: boolean } By default, Apollo Server does not send the list of HTTP request headers and values to Apollo's servers, to protect private data of your app's users. If you'd like this information included in traces, set this option. This option can take several forms:

    • { none: true }: Drop all HTTP request headers. (DEFAULT)
    • { all: true }: Send the values of all HTTP request headers.
    • { exceptNames: [...] }: A case-insensitive list of names of HTTP headers whose values should not be sent to Apollo servers.
    • { onlyNames: [...] }: A case-insensitive list of names of HTTP headers whose values will be sent to Apollo servers.

    Defaults to not sending any request header names and values if both this parameter and the deprecated privateHeaders are not set. Unlike with sendVariableValues, names of dropped headers are not reported. The headers 'authorization', 'cookie', and 'set-cookie' are never reported.

  • privateHeaders: Array<String> | boolean

    Will be deprecated in 3.0. Use the sendHeaders option instead. Passing an array into privateHeaders is equivalent to passing { exceptNames: array } into sendHeaders, and passing true or false is equivalent to passing in { none: true } and { all: true }, respectively.

    Note: An error will be thrown if both this deprecated option and its replacement, sendHeaders, are defined. In order to preserve the old default of privateHeaders, which sends all request headers and their values, pass in the sendHeaders option: new ApolloServer({engine: {sendHeaders: {all: true}}}).

  • handleSignals: boolean

    By default, EngineReportingAgent listens for the 'SIGINT' and 'SIGTERM' signals, stops, sends a final report, and re-sends the signal to itself. Set this to false to disable. You can manually invoke 'stop()' and 'sendReport()' on other signals if you'd like. Note that 'sendReport()' does not run synchronously so it cannot work usefully in an 'exit' handler.

  • rewriteError: (err: GraphQLError) => GraphQLError | null

    By default, all errors are reported to Apollo Studio. This function can be used to exclude specific errors from being reported. This function receives a copy of the GraphQLError and can manipulate it before it's reported. The modified error (e.g., after changing the err.message property) should be returned, or the function can return null to avoid reporting the error entirely. It is not permissible to return undefined. Note that most GraphQLError fields, like path, will be copied from the original error to the new error: this way, you can just return new GraphQLError("message") without having to explicitly keep it associated with the same node. Specifically, only the message and extensions properties on the returned GraphQLError are observed. If extensions aren't specified, the original extensions are used.

  • schemaTag: String

    Will be deprecated in 3.0. Use the option graphVariant instead.

    A human-readable name to tag this variant of a schema (i.e. staging, EU). Setting this value will cause metrics to be segmented in the Apollo Platform's UI. Additionally schema validation with a schema tag will only check metrics associated with the same string.

  • graphVariant: String

    A human-readable name for the variant of a schema (such as staging or production). Setting this value will cause metrics to be segmented in Apollo Studio. Additionally, schema validation with a graph variant only checks metrics associated with the same variant.

  • reportTiming: Boolean | async (GraphQLRequestContextDidResolveOperation | GraphQLRequestContextDidEncounterErrors) => Boolean

    Specify whether to instrument an operation to send traces and metrics to Apollo. This may resolve to a boolean or a async function returning a promise resolving to a boolean. If the option resolves to false for an operation the operation will not be instrumented and no metrics information will be sent to Apollo.

    The function will receive a GraphQLRequestContextDidResolveOperation with client and operation information or a GraphQLRequestContextDiDEncounterErrors in the case an operation failed to resolve properly. This allows the choice of whether to include a given request in trace and metric reporting to be made on a per-request basis. The default value is true.

  • generateClientInfo: (GraphQLRequestContext) => ClientInfo AS 2.2

    Creates a client context(ClientInfo) based on the request pipeline's context, which contains values like the request, response, cache, and context. This generated client information will be provided to Apollo Studio and can be used to filter metrics. Set clientName to identify a particular client. Use clientVersion to specify a version for a client name. The default function will use the clientInfo field inside of GraphQL Query extensions.

    For advanced use cases when you already have an opaque string to identify your client (e.g. an API key, x509 certificate, or team codename), use the clientReferenceId field to add a reference to its internal identity. This client reference ID will not be displayed in the UI but will be available for cross-correspondence, so names and reference ids should have a one to one relationship.

    Warning: If you specify a clientReferenceId, Apollo Studio treats the clientName as a secondary lookup, so changing a clientName may result in an unwanted experience.

  • reportSchema: boolean

    Enables the automatic schema reporting feature of Apollo Server, which will cause it to periodically report the server's schema (when changes are detected) along with details about the runtime environment to Apollo Graph Manager. This feature removes the need to register schemas manually via apollo service:push in CI/CD pipelines.

  • overrideReportedSchema: string

    By default, the schema reported to Apollo Studio will be normalized, which might shift ordering and comments and remove whitespace. This option can be used to override the default schema. Any schema provided will not undergo normalization, which can be helpful to preserve details that normalization removes.

  • schemaReportingInitialDelayMaxMs: number

    By default, the schema reporter will wait a random amount of time between 0 and 10 seconds before making its first report at reporter startup. A longer range of times leads to more staggered starts, which reduces bandwidth since it makes it less likely that multiple servers will get asked to upload the same schema. However, in certain constrained environments (e.g. AWS Lambda), this wait time may be less desirable. This option can be used to change the maximum amount of time that the reporter will wait until it starts sending reports.

Edit on GitHub