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
1const server = new ApolloServer({
2 typeDefs,
3 resolvers
4});
Options
Name / Type |
Description |
---|---|
Schema options |
|
|
Document or documents that represent your server's GraphQL schema, generated by applying the Required unless you provide For an example, see Define your GraphQL schema . |
|
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 For details, see Resolvers . |
|
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 |
|
A function that returns an object containing For more details, see Adding data sources to Apollo Server . |
| If The default value is |
| 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 This field is most commonly used with Apollo Federation , which uses a special Note that if you are using file uploads , you need to add the |
| If you're using automated persisted queries (APQ) , you can provide an object with a Provide |
| Provide a Provide |
|
A value or function called with the parsed 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. |
|
By default, Apollo Server 2 integrates an outdated version of the We recommend instead that you pass If you must use the upload feature with Apollo Server 2, then you can do so on Node 14 by passing |
Networking options |
|
|
An This option is used only by the |
|
An |
|
Provide this function to transform the structure of error objects before they're sent to a client. The function takes a |
|
Provide this function to transform the structure of GraphQL response objects before they're sent to a client. The function takes a |
| 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:
|
|
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 |
|
|
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 |
|
By default (when running in Node and when the Set this option to You can also manually call |
|
The amount of time to wait after This option is used only by the The default value is |
Debugging options |
|
|
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 Note that |
| If Defaults to |
|
An object to use for logging in place of If you provide this value, Apollo Server automatically logs all messages of all severity levels ( This logger is automatically added to the |
|
If |
|
If The default value is |
Experimental options
These options are experimental. They might be removed or change at any time, even within a patch release.
Name / Type |
Description |
---|---|
|
Sets the approximate size (in MiB) of the server's 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:
Middleware | Context fields |
---|---|
AWS Lambda |
{
|
Azure Functions |
{
|
Cloudflare |
{ req:
|
Express |
{
|
Fastify |
{
|
Google Cloud Functions |
{ req:
|
hapi |
{
|
Koa |
{ ctx:
|
Micro |
{ req:
|
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 |
---|---|
|
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. |
listen
This method is provided only by the
apollo-server
package. If you're integrating with Node.js middleware via a different package (such asapollo-server-express
), instead see bothstart
andapplyMiddleware
.
Instructs Apollo Server to begin listening for incoming requests:
1server.listen({
2 port: 4001,
3});
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 |
---|---|
|
The URL that the server is listening on. |
|
The server instance that's listening at |
|
The path of the server's subscriptions endpoint. |
|
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, calllisten
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:
If your server is a federated gateway , it attempts to fetch its schema. If the fetch fails,
start
throws an error.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
1const express = require('express');
2const { ApolloServer } = require('apollo-server-express');
3const { typeDefs, resolvers } = require('./schema');
4
5async function startApolloServer() {
6 const server = new ApolloServer({
7 typeDefs,
8 resolvers,
9 });
10 await server.start();
11
12 const app = express();
13
14 // Additional middleware can be mounted at this point to run before Apollo.
15 app.use('*', jwtCheck, requireAuth, checkScope);
16
17 // Mount Apollo middleware here.
18 server.applyMiddleware({ app, path: '/specialUrl' });
19 await new Promise(resolve => app.listen({ port: 4000 }, resolve));
20 console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
21 return { server, app };
22}
Options
Name / Type |
Description |
---|---|
|
Required. The server middleware instance to integrate with Apollo Server. |
|
The path for Apollo Server to listen on. The default value is |
|
Middleware-specific configuration options for CORS. See available options for your middleware: express | hapi | koa Provide The default value is |
|
Middleware-specific configuration options for body parsing. See available options for your middleware: express | koa Provide The default value is |
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:
1const { gql } = require('apollo-server');
2
3const typeDefs = gql`
4 type Author {
5 name
6 }
7`;
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.:
JavaScript1{ 2 Type: () => true, 3}
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 withmocks
.
Usage
1const { addMockFunctionsToSchema } = require('apollo-server');
2
3// We'll make an assumption that an executable schema
4// is already available from the `./schema` file.
5const executableSchema = require('./schema');
6
7addMockFunctionsToSchema({
8 schema: executableSchema,
9 mocks: {
10 // Mocks the `Int` scalar type to always return `12345`.
11 Int: () => 12345,
12
13 // Mocks the `Movies` type to always return 'Titanic'.
14 Movies: () => 'Titanic',
15 },
16 preserveResolvers: false,
17});
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 officialgraphql-tools
documentation .