title | sidebar_title | api_reference |
---|---|---|
API Reference: apollo-server |
apollo-server |
true |
This API reference documents the exports from the apollo-server
package.
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({
typeDefs,
resolvers
});
Name | Type | Description |
---|---|---|
Schema options |
||
|
Required. Document or documents that represent your server's GraphQL schema, generated by applying the For an example, see Define your GraphQL schema. |
|
|
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. |
|
|
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 |
|
|
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 the 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. |
|
Networking options |
||
|
An object containing configuration options for connecting Apollo Server to Apollo Studio. Supported fields are described in EngineReportingOptions. |
|
|
An This option is used only by the |
|
|
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 |
|
Lifecycle options |
||
|
By default (when running in Node and when the |
|
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_approximateDocumentStoreSizeMiB
number
- This option is experimental. It might be removed or change at any time, even within a patch release.
Sets the approximate size (in MiB) of the server's
DocumentNode
cache. The server checks the SHA-256 hash of each incoming operation against cachedDocumentNode
s, 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.
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: |
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. |
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 asapollo-server-express
, instead seeapplyMiddleware
.
-
options
: <Object
>When using the
apollo-server
package, callinglisten
on an instantiatedApolloServer
will start the server by passing the specified (optional)options
to a Node.jshttp.Server
. For a full reference of the supportedoptions
, see the documentation fornet.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. -
cors
: <Object
|boolean
> (express, hapi, koa)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
typeDefs,
resolvers,
});
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 String
s), 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 {
name
}
`;
The makeExecutableSchema
method is re-exported from apollo-server as a convenience.
options
: <Object
>typeDefs
: <GraphQLSchema
> (required)resolvers
: <Object
> : <Array<Object>
>logger
: <Object
>allowUndefinedInResolve
= falseresolverValidationOptions
= {}directiveResolvers
= nullschemaDirectives
= nullparseOptions
= {}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 withmocks
.
-
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,
});
These are the supported fields of the engine
object you provide to the ApolloServer
constructor to configure communication with Apollo Studio.
Name | Type | Description |
---|---|---|
Base config | ||
apiKey |
String |
The graph API key that Apollo Server should use to authenticate with Apollo Studio. Instead of using this field, we recommend providing your API key by setting it as the value of the |
graphVariant |
String |
The variant of your graph to associate this server's schema and metrics with. Instead of using this field, we recommend specifying a variant by setting its name as the value of the |
logger |
Logger |
If you provide this object, Apollo Server sends it all log messages related to Apollo Studio communication, instead of sending them to the default logger. The object must implement all methods of the |
Schema reporting | ||
reportSchema |
Boolean |
If The default value is |
schemaReportingInitialDelayMaxMs |
Number |
On startup, Apollo Server waits a random amount of time between 0 milliseconds and this value before it begins reporting its schema. This randomness is useful for staggering schema reports when you deploy multiple server instances simultaneously. The default value is 10 seconds ( |
overrideReportedSchema |
String |
By default, Apollo Server normalizes its schema before reporting it to Apollo Studio. Doing so helps make sure that no-op changes to a schema's whitespace or field order aren't incorrectly identified as an updated schema. If normalization removes details that you want to preserve, you can provide an SDL string directly to this option. If you do, it is reported directly to Studio instead of the server's normalized schema. |
Metrics reporting | ||
reportIntervalMs |
Number |
The interval at which Apollo Server should send batched trace reports to Studio, in milliseconds. Regardless of this value, Apollo Server sends a trace report whenever the size of a pending batch exceeds the value of |
maxUncompressedReportSize |
Number |
Apollo Server sends a trace report whenever the size of a pending batched trace report exceeds this value (in bytes), regardless of its standard reporting interval. The default value is 4MB ( |
maxAttempts |
Number |
The maximum number of times Apollo Server should attempt to report each trace report, performing exponential backoff between attempts. The default value is |
minimumRetryDelayMs |
Number |
The minimum amount of backoff (in milliseconds) Apollo Server should perform before retrying a failed trace report. The default value is |
reportTiming |
async Function or Boolean |
Provide this async function to determine whether to report metrics to Apollo Studio on an operation-by-operation basis. This function is called once per operation. It is passed either a By default, Apollo Server reports metrics for all operations if reporting is enabled. |
sendHeaders |
Object |
Provide this object to configure which request header names and values are included in trace data that's sent to Apollo Studio. Valid options are described in Valid The default value is |
sendVariableValues |
Object |
Provide this object to configure which GraphQL variable values are included in trace data that's sent to Apollo Studio. Valid options are described in Valid The default value is |
debugPrintReports |
Boolean |
If The default value is |
reportErrorFunction |
Function |
If you provide this function, Apollo Server calls it whenever it encounters an error while reporting metrics. The details of the error are passed to the function. By default, Apollo Server logs these errors to stderr. |
rewriteError |
Function |
Specify this function to modify GraphQL operation errors before Apollo Server reports those errors to Apollo Studio. The function takes a The only properties of the reported error you can modify are its |
requestAgent |
http.Agent or https.Agent or false |
An HTTP(S) agent to use for metrics reporting. Can be either an http.Agent or an https.Agent . It behaves the same as the agent parameter to http.request . |
generateClientInfo |
Function |
Specify this function to provide Apollo Studio with client details for each processed operation. Apollo Studio uses this information to segment metrics by client. The function is passed a By default, Apollo Server attempts to obtain For advanced use cases when you already use an opaque string to identify your client (such as an API key, x509 certificate, or team codename), use the Warning: If you specify a |
calculateSignature |
Function |
A custom function to use to calculate the "signature" of the schema that operations are running against. This enables Apollo Studio to detect when two non-identical schema strings represent the exact same underlying model. For an example, see the default signature function, which sorts types and fields, removes extraneous whitespace, and removes unused definitions. |
handleSignals |
Boolean |
For backwards compatibility only; specifying |
You can provide an object with one of the following structures as the value of the sendHeaders
option in EngineReportingOptions
.
Regardless of your configuration, Apollo Server never sends the values of the following headers to Apollo Studio:
authorization
cookie
set-cookie
Object | Description |
---|---|
{ none: true } |
If you provide this object, no request header names or values are sent to Apollo Studio. This is the default behavior. |
{ all: true } |
If you provide this object, all GraphQL header names and values are sent to Apollo Studio, except for the protected headers listed above. |
{ onlyNames: ["apple", "orange"]} |
If you provide an object with this structure, only names and values of the request headers with names that appear in the array are sent to Apollo Studio. Case-insensitive. |
{ exceptNames: ["apple", "orange"]} |
If you provide an object with this structure, all GraphQL header values except values of headers with names that appear in the array are sent to Apollo Studio. Case-insensitive. |
You can provide an object with one of the following structures as the value of the sendVariableValues
option in EngineReportingOptions
.
Object | Description |
---|---|
{ none: true } |
If you provide this object, no GraphQL variable values are sent to Apollo Studio. This is the default behavior. |
{ all: true } |
If you provide this object, all GraphQL variable values are sent to Apollo Studio. |
{ onlyNames: ["apple", "orange"]} |
If you provide an object with this structure, only values of the GraphQL variables with names that appear in the array are sent to Apollo Studio. Case-sensitive. |
{ exceptNames: ["apple", "orange"]} |
If you provide an object with this structure, all GraphQL variable values except values of variables with names that appear in the array are sent to Apollo Studio. Case-sensitive. |
{ transform: ({ variables, operationString)} => { ... } } |
The value of For security reasons, if an error occurs in the |