API Reference: apollo-server
This API reference documents the exports from the apollo-server
package.
class ApolloServer
class ApolloServer
The core of an Apollo Server implementation. For an example, see
Methods
constructor
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
| Document or documents that represent your server's GraphQL schema, generated by applying the Required unless you provide For an example, see |
resolvers
| 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 |
context
| 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.
For more details, see |
dataSources
| A function that returns an object containing For more details, see |
introspection
| If The default value is |
schemaDirectives
| A map of all |
schema
| 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 Note that if you are using |
persistedQueries
| If you're using Provide |
subscriptions
| Provide a Provide |
rootValue
| 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. |
validationRules
| An object containing custom functions to use as additional |
uploads
| By default, Apollo Server 2 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 | |
cors
| An This option is used only by the |
cacheControl
| An |
formatError
| Provide this function to transform the structure of error objects before they're sent to a client. The function takes a |
formatResponse
| Provide this function to transform the structure of GraphQL response objects before they're sent to a client. The function takes a |
apollo
| An object containing configuration options for connecting Apollo Server to
|
engine
| Deprecated as of Apollo Server v2.18. New projects should instead use Apollo Server's Studio connection plugins. For details, see An object containing configuration options for connecting Apollo Server to |
Lifecycle options | |
plugins
| An array of 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 |
stopOnTerminationSignals
| By default (when running in Node and when the Set this option to You can also manually call |
stopGracePeriodMillis
| The amount of time to wait after This option is used only by the The default value is |
Debugging options | |
playground
| If truthy, the server hosts The default value is Note that |
debug
| If Defaults to |
logger | 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 |
mocks
| If |
mockEntireSchema
| 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 |
---|---|
experimental_approximateDocumentStoreMiB
| 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
context
fieldsThe context
object passed between Apollo Server resolvers automatically includes certain fields, depending on which
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
ApolloServer
constructor:
Name / Type | Description |
---|---|
path
| Required. The URL for the server's subscription-specific endpoint. |
keepAlive
| 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
| A lifecycle hook that's called whenever a subscription connection is initiated by a client. |
onDisconnect
| A lifecycle hook that's called whenever a subscription connection is terminated by a client. |
listen
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
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 net.Server.listen
Returns a Promise
that resolves to an object containing the following properties:
Name / Type | Description |
---|---|
url
| The URL that the server is listening on. |
server | The server instance that's listening at |
subscriptionsPath
| The path of the server's subscriptions endpoint. |
subscriptionsUrl
| The full URL of the server's subscriptions endpoint. |
start
start
The async start
method instructs Apollo Server to prepare to handle incoming operations.
Call start
only if you are using a apollo-server-express
).
- If you're using the core
apollo-server
library, callinstead.listen
- 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 of your installed plugins. If any of these handlers throw an error,
serverWillStart
handlersstart
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
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
apollo-server-express
. You should call await server.start()
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
| Required. The server middleware instance to integrate with Apollo Server. |
path
| The path for Apollo Server to listen on. The default value is |
cors
| Middleware-specific configuration options for CORS. See available options for your middleware: Provide The default value is |
bodyParserConfig
| Middleware-specific configuration options for body parsing. See available options for your middleware: Provide The default value is |
getMiddleware
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
app
option.
stop
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
If your server is a 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
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 apollo-server
, you should stop your HTTP server before calling ApolloServer.stop()
.
gql
gql
A
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
makeExecutableSchema
Builds a schema from provided type definitions and resolvers.
The ApolloServer
constructortypeDefs
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.
addMockFunctionsToSchema
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 withmocks
.
-
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
graphql-tools
exportsThe graphql-tools
library provides helpful functions (such as makeExecutableSchema
Apollo Server uses graphql-tools
version 4. For documentation of version 4 functions, see
For documentation of the latest version of graphql-tools
, see the graphql-tools
documentation