Docs
Launch GraphOS Studio

API Reference: ApolloServer


This article the ApolloServer class from the @apollo/server package. You can use the ApolloServer class to create an instance of that you can then pass to a web framework integration function (e.g., startStandaloneServer or expressMiddleware).

Check out our Getting Started guide for an example of setting up !

constructor

Returns an initialized ApolloServer instance.

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

Example

import { ApolloServer } from '@apollo/server';
const server = new ApolloServer({
typeDefs,
resolvers,
});
import { ApolloServer } from '@apollo/server';
const server = new ApolloServer({
typeDefs,
resolvers,
});

Options

Name /
Type
Description

Specifying a schema

typeDefs

string, DocumentNode, or Array<DocumentNode>

A valid Schema Definition Language () string, , or documents that represent your server's . To generate documents, you can apply the gql tag (from graphql-tag) to valid strings.

Required unless you provide a schema or a gateway.

For an example, see Define your GraphQL schema.

resolvers

Object or Array

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

While technically optional, if you are providing typeDefs, it is strongly recommended that you provide resolvers as well.

For details, see Resolvers.

schema

Object

An executable . Under the hood, automatically generates this 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
gateway

Object

You can use this to integrate your server with Apollo Gateway.

Schema options

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.

fieldResolver

GraphQLFieldResolver

A custom that will replace 's default field resolvers.

rootValue

Any or Function

A value or function called with the parsed Document, creating the root value passed to the executor.

Providing a function is useful if you want to use a different root value depending on the 's details, such as whether it's a or .

validationRules

Array<Function>

An array containing custom functions to use as additional validation rules when validating against the schema. Note that these rules should depend only on the operation and the schema, not on anything else specific to an individual request, as the result of successful validation is cached across requests.

documentStore

KeyValueCache<DocumentNode> or null

A key-value cache that uses to store previously encountered (as DocumentNodes). It does not store results.

Whenever receives an incoming , it checks whether that exact operation is present in its documentStore. If it's present, can safely skip parsing and validating the , 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 . 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.

Protocol options

persistedQueries

Object or false

If you're using automated persisted queries (APQ), you can provide an object with cache and/or ttl to customize how stores the mapping between hashes and strings, or provide false to disable entirely.

csrfPrevention

boolean or Object

By default, the CSRF prevention feature is enabled to protect from CSRF and XS-Search attacks.

This feature can prevent certain GET requests from executing if those requests don't specify certain headers. You can configure the headers that allow execution by passing a configuration object to this option (e.g., csrfPrevention: { requestHeaders: ['special-header'] }).

If your server has clients that send GET requests and those clients aren't one of Apollo's client libraries (Web, iOS, Kotlin), you might need to modify the configuration of those clients to use this feature. For more details, see the CSRF prevention documentation.

You can disable this recommended security feature by passing false to csrfPrevention.

formatError

Function

Provide this function to transform the structure of error objects before they're sent to a client.

The formatError hook receives two : the first is a GraphQLFormattedError (to be sent with the response), and the second is the original error (wrapped in GraphQLError if thrown by a resolver). This function should return a GraphQLFormattedError object.

apollo

Object

An object containing configuration options for connecting to Apollo Studio. Each 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 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 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 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 .
allowBatchedHttpRequests

boolean

Controls whether to allow Batching Queries in a single HTTP Request. Defaults to false. If a request comes in formatted as an array rather than as a single request object, an error will be thrown ( i.e., Operation batching disabled) unless batching is enabled.

Lifecycle options

cache

KeyValueCache

A KeyValueCache which uses for several features, including and full response caching. This cache is also available to Apollo Server's plugins.

The default cache is an InMemoryLRUCache with a default size of roughly 30MiB. (For backwards-compatibility with 3, specifying cache: 'bounded' also selects this default bounded cache.)

To learn more about configuring 's cache, see Configuring cache backends.

plugins

Array

An array of plugins to install in your server instance.

You can also add plugins to your server before you start it using the addPlugin method. This might be useful in the event that your plugin needs to access the ApolloServer instance.

comes with several plugins that it installs automatically in their default configuration if certain conditions are met. For example, the usage reporting plugin is installed if you provide a API key and a . Apollo Server skips this automatic installation if you manually provide the plugin (in the plugins array or with the addPlugin method), or if you provide the plugin's corresponding "disabled" plugin (such as ApolloServerPluginUsageReportingDisabled() for ApolloServerPluginUsageReporting). For details, see the API references for these plugins: usage reporting, schema reporting, landing page, cache control, and inline trace.

stopOnTerminationSignals

boolean

By default, whenever 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. Subsequent SIGINT and SIGTERM signals are ignored while awaits this.stop(). Note that this does not happen when NODE_ENV equals test or when is running in mode.

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

includeStacktraceInErrorResponses

boolean

If true, stack traces are included in responses when errors occur.

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, automatically logs all messages of all severity levels (debug through error). 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 plugin functions.

parseOptions

Object

An object that specifies how your server parses . See graphql-js for the available configuration options.

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 (such as introspection). 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.

status400ForVariableCoercionErrors

boolean

Set this option to true. It mitigates a regression introduced in v4 where the server returns a 200 status code (instead of 400) when a client provides invalid . Learn more.

v5 will always behave as if this option is true (and will ignore any provided value).

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

You might find this option interesting for performance reasons if you handle validation at build time and enforce that only known, validated operations are allowed to be executed at runtime. Note that validation of operations is cached in 's store.

start

The async start method instructs to prepare to handle incoming .

Call start only if you are using a framework integration for a non- environment (e.g., expressMiddleware).

  • If you're using a framework integration (such as Lambda), you shouldn't call this method before passing your server into the integration function. Your integration function will take care of starting your server for you.

  • If you're using startStandaloneServer you do not need to start your server before passing it directly to startStandaloneServer.

Always call await server.start() before passing your server into your integration function and starting to accept requests:

const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
});
await server.start();
app.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server));
const server = new ApolloServer({
typeDefs,
resolvers,
});
await server.start();
app.use('/graphql', cors(), express.json(), expressMiddleware(server));

This allows you to react to startup failures by crashing your process instead of starting to serve traffic.

If you are testing your server using executeOperation (i.e., you're not actually starting an HTTP server), you don't need to call start() because executeOperation will do that for you.

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.

startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests

Serverless integrations handle starting an instance in the background by calling the startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests method. This method is synchronous and doesn't need to be awaited. This means any errors that occur happen in the background, so you can't immediately handle them. See Building integrations for more details.

This method triggers the same actions as the start() method.

addPlugin

You can use the addPlugin method to add plugins before your server is started. This is helpful when you want to add a plugin that accepts your initialized ApolloServer instance itself, like so:

const server = new ApolloServer({
typeDefs,
plugins: [makeFirstPlugin()],
});
server.addPlugin(makeSecondPlugin(server));
const server = new ApolloServer({
typeDefs,
plugins: [makeFirstPlugin()],
});
server.addPlugin(makeSecondPlugin(server));

assertStarted

Framework integrations should call server.assertStarted() to ensure a server has started before accepting requests. See Building integrations for more details.

stop

ApolloServer.stop() is an async method that tells all of 's background tasks to complete. Specifically, it:

  • Calls and awaits all drainServer plugin handlers. These should generally:
    • Stop listening for new connections
    • Close idle connections (i.e., connections with no current HTTP request)
    • Close active connections whenever they become idle
    • Wait for all connections to be closed
    • After a grace period, if any connections remain active, forcefully close them. If you're using startStandaloneServer, this happens by default. 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 .
  • 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 after you've called startStandaloneServer with your ApolloServer instance).

In some circumstances, 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 's request pipeline without sending an HTTP request.

const response = await server.executeOperation({
query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
variables: { name: 'world' },
});

The executeOperation method takes two :

  • The first is an object describing the to be executed.
    • Supported are listed in the table below.
  • The second is the optional options object. This object includes the 's optional contextValue. This is only optional if your server doesn't expect a context value (i.e., your server uses the default context because you didn't explicitly provide another one).
const response = await server.executeOperation({
query: 'query SayHelloWorld($name: String) { hello(name: $name) }',
variables: { name: 'world' },
}, {
contextValue: { userId: 'test' },
});

The response object returned from executeOperation is a GraphQLResponse, which has body and http .

4 supports incremental delivery such as @defer and @stream (when combined with an appropriate version of graphql-js), and so the structure of response.body can represent either a single result or multiple results. response.body.kind is either 'single' or 'incremental'. If it is 'single', then incremental delivery has not been used, and response.body.singleResult is an object with data, errors, and extensions . If it is 'incremental', then response.body.initialResult is the initial result of the , and response.body.subsequentResults is an async iterator that will yield subsequent results. (The precise structure of initialResult and subsequentResults is defined by graphql-js and may change between the current pre-release of graphql-js v17 and its final release; if you write code that processes these values before graphql-js v17 has been released you may have to adapt it when the API is finalized.)

The http contains an optional numeric status code and a headers map specifying any HTTP status code and headers that should be set.

Below are the available for the first of executeOperation:

Fields

NameDescription
query

string or DocumentNode

Required. The to run. Note that you must use the query even if the is a . This may also be a TypedQueryDocumentNode, in which case TypeScript types for the variables option and response.body.singleResult.data will be automatically inferred.

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 definition, you must provide this option to indicate which operation to execute.

extensions

object

The extensions object is usually used to pass request metadata within your server from one touch point to another (e.g., from a request to a plugin) during the lifecycle of a request. In this scenario, this object represents the request sent in an actual request.

http

HTTPGraphQLRequest

An object implementing the HTTPGraphQLRequest interface, containing information that pertains to the incoming HTTP request.

executeHTTPGraphQLRequest

The executeHTTPGraphQLRequest method is the main entry point for web framework integrations. You can pass a HTTPGraphQLRequest object to the executeHTTPGraphQLRequest method to execute a request:

const result = await server.executeHTTPGraphQLRequest({
httpGraphQLRequest: OurHttpGraphQLRequest,
context: async () => ({
// token: ...,
}),
});
const result = await server.executeHTTPGraphQLRequest({
httpGraphQLRequest: OurHttpGraphQLRequest,
context: async () => ({
// token: ...,
}),
});

For details and examples, see Building Integrations.

cache

A public readonly on ApolloServer that enables you to access your server's cache.

logger

A public readonly on ApolloServer that enables you to access your server's logger.

Previous
Health checks
Next
startStandaloneServer
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company