-
#7916
4686454
Thanks @andrewmcgivery! - AddhideSchemaDetailsFromClientErrors
option to ApolloServer to allow hiding 'did you mean' suggestions from validation errors.Even with introspection disabled, it is possible to "fuzzy test" a graph manually or with automated tools to try to determine the shape of your schema. This is accomplished by taking advantage of the default behavior where a misspelt field in an operation will be met with a validation error that includes a helpful "did you mean" as part of the error text.
For example, with this option set to
true
, an error would readCannot query field "help" on type "Query".
whereas with this option set tofalse
it would readCannot query field "help" on type "Query". Did you mean "hello"?
.We recommend enabling this option in production to avoid leaking information about your schema to malicious actors.
To enable, set this option to
true
in yourApolloServer
options:const server = new ApolloServer({ typeDefs, resolvers, hideSchemaDetailsFromClientErrors: true, });
-
#7821
b2e15e7
Thanks @renovate! - Non-major dependency updates -
#7900
86d7111
Thanks @trevor-scheer! - Inline a small dependency that was causing build issues for ESM projects
- #7871
18a3827
Thanks @tninesling! - Subscription heartbeats are initialized prior to awaiting subscribe(). This allows long-running setup to happen in the returned Promise without the subscription being terminated prior to resolution.
- #7866
5f335a5
Thanks @tninesling! - Catch errors thrown by subscription generators, and gracefully clean up the subscription instead of crashing.
- #7849
c7e514c
Thanks @TylerBloom! - In the subscription callback server plugin, terminating a subscription now immediately closes the internal async generator. This avoids that generator existing after termination and until the next message is received.
- #7843
72f568e
Thanks @bscherlein! - Improves timing of thewillResolveField
end hook on fields which return Promises resolving to Arrays. This makes the use of thesetCacheHint
method more reliable.
-
#7786
869ec98
Thanks @ganemone! - Restore missing v1skipValidation
option asdangerouslyDisableValidation
. Note that enabling this option exposes your server to potential security and unexpected runtime issues. Apollo will not support issues that arise as a result of using this option. -
#7803
e9a0d6e
Thanks @favna! - allowstringifyResult
to return aPromise<string>
Users who implemented the
stringifyResult
hook can now expect error responses to be formatted with the hook as well. Please take care when updating to this version to ensure this is the desired behavior, or implement the desired behavior accordingly in yourstringifyResult
hook. This was considered a non-breaking change as we consider that it was an oversight in the original PR that introducedstringifyResult
hook.
-
#7793
9bd7748
Thanks @bnjjj! - General availability of subscription callback protocol -
#7799
63dc50f
Thanks @stijnbe! - Fix type of ApolloServerPluginUsageReporting reportTimer -
#7740
fe68c1b
Thanks @barnisanov! - Uninstalledbody-parser
and usedexpress
built-inbody-parser
functionality instead(mainly the json middleware)
-
#7741
07585fe39
Thanks @mayakoneval! - Pin major releases of embeddable Explorer & Sandbox code. -
#7769
4fac1628c
Thanks @cwikla! - Change SchemaReporter.pollTimer from being a NodeJS.Timer to a NodeJS.Timeout
-
#7747
ddce036e1
Thanks @trevor-scheer! - The minimum version ofgraphql
officially supported by Apollo Server 4 as a peer dependency, v16.6.0, contains a serious bug that can crash your Node server. This bug is fixed in the immediate next version,[email protected]
, and we strongly encourage you to upgrade your installation ofgraphql
to at least v16.7.0 to avoid this bug. (For backwards compatibility reasons, we cannot change Apollo Server 4's minimum peer dependency, but will change it when we release Apollo Server 5.)Apollo Server 4 contained a particular line of code that makes triggering this crashing bug much more likely. This line was already removed in Apollo Server v3.8.2 (see #6398) but the fix was accidentally not included in Apollo Server 4. We are now including this change in Apollo Server 4, which will reduce the likelihood of hitting this crashing bug for users of
graphql
v16.6.0. That said, taking this@apollo/server
upgrade does not prevent this bug from being triggered in other ways, and the real fix to this crashing bug is to upgradegraphql
.
-
a1c725eaf
Thanks @trevor-scheer! - Ensure API keys are valid header values on startupApollo Server previously performed no sanitization or validation of API keys on startup. In the case that an API key was provided which contained characters that are invalid as header values, Apollo Server could inadvertently log the API key in cleartext.
This only affected users who:
- Provide an API key with characters that are invalid as header values
- Use either schema or usage reporting
- Use the default fetcher provided by Apollo Server or configure their own
node-fetch
fetcher
Apollo Server now trims whitespace from API keys and validates that they are valid header values. If an invalid API key is provided, Apollo Server will throw an error on startup.
For more details, see the security advisory: https://github.com/apollographql/apollo-server/security/advisories/GHSA-j5g3-5c8r-7qfx
-
#7699
62e7d940d
Thanks @trevor-scheer! - Fix error path attachment for list itemsPreviously, when errors occurred while resolving a list item, the trace builder would fail to place the error at the correct path and just default to the root node with a warning message:
Could not find node with path x.y.1, defaulting to put errors on root node.
This change places these errors at their correct paths and removes the log.
- #7672
ebfde0007
Thanks @trevor-scheer! - Add missingnonce
onscript
tag for non-embedded landing page
-
#7617
4ff81ca50
Thanks @trevor-scheer! - Introduce newApolloServerPluginSubscriptionCallback
plugin. This plugin implements the subscription callback protocol which is used by Apollo Router. This feature implements subscriptions over HTTP via a callback URL which Apollo Router registers with Apollo Server. This feature is currently in preview and is subject to change.You can enable callback subscriptions like so:
import { ApolloServerPluginSubscriptionCallback } from '@apollo/server/plugin/subscriptionCallback'; import { ApolloServer } from '@apollo/server'; const server = new ApolloServer({ // ... plugins: [ApolloServerPluginSubscriptionCallback()], });
Note that there is currently no tracing or metrics mechanism in place for callback subscriptions. Additionally, this plugin "intercepts" callback subscription requests and bypasses some of Apollo Server's internals. The result of this is that certain plugin hooks (notably
executionDidStart
andwillResolveField
) will not be called when handling callback subscription requests or when sending subscription events.For more information on the subscription callback protocol, visit the docs: https://www.apollographql.com/docs/router/executing-operations/subscription-callback-protocol/
- #7636
42fc65cb2
Thanks @trevor-scheer! - Update test suite for compatibility with Node v20
-
#7634
f8a8ea08f
Thanks @dfperry5! - Updating the ApolloServer constructor to take in a stringifyResult function that will allow a consumer to pass in a function that formats the result of an http query.Usage:
const server = new ApolloServer({ typeDefs, resolvers, stringifyResult: (value: FormattedExecutionResult) => { return JSON.stringify(value, null, 2); }, });
-
#7614
4fadf3ddc
Thanks @Cellule! - Publish TypeScript typings for CommonJS modules output.This allows TypeScript projects that use CommonJS modules with
moduleResolution: "node16"
ormoduleResolution: "nodeNext"
to correctly resolves the typings of apollo's packages as CommonJS instead of ESM. -
Updated dependencies [
4fadf3ddc
]:- @apollo/[email protected]
- @apollo/[email protected]
- @apollo/[email protected]
-
0adaf80d1
Thanks @trevor-scheer! - Address Content Security Policy issuesThe previous implementation of CSP nonces within the landing pages did not take full advantage of the security benefit of using them. Nonces should only be used once per request, whereas Apollo Server was generating one nonce and reusing it for the lifetime of the instance. The reuse of nonces degrades the security benefit of using them but does not pose a security risk on its own. The CSP provides a defense-in-depth measure against a potential XSS, so in the absence of a known XSS vulnerability there is likely no risk to the user.
The mentioned fix also coincidentally addresses an issue with using crypto functions on startup within Cloudflare Workers. Crypto functions are now called during requests only, which resolves the error that Cloudflare Workers were facing. A recent change introduced a
precomputedNonce
configuration option to mitigate this issue, but it was an incorrect approach given the nature of CSP nonces. This configuration option is now deprecated and should not be used for any reason since it suffers from the previously mentioned issue of reusing nonces.Additionally, this change adds other applicable CSPs for the scripts, styles, images, manifest, and iframes that the landing pages load.
A final consequence of this change is an extension of the
renderLandingPage
plugin hook. This hook can now return an object with anhtml
property which returns aPromise<string>
in addition to astring
(which was the only option before).
-
#7601
75b668d9e
Thanks @trevor-scheer! - Provide a new configuration option for landing page pluginsprecomputedNonce
which allows users to provide a nonce and avoid calling intouuid
functions on startup. This is useful for Cloudflare Workers where random number generation is not available on startup (only during requests). Unless you are using Cloudflare Workers, you can ignore this change.The example below assumes you've provided a
PRECOMPUTED_NONCE
variable in yourwrangler.toml
file.Example usage:
const server = new ApolloServer({ // ... plugins: [ ApolloServerPluginLandingPageLocalDefault({ precomputedNonce: PRECOMPUTED_NONCE, }), ], });
- #7599
c3f04d050
Thanks @trevor-scheer! - Update@apollo/utils.usagereporting
dependency. Previously, installing@apollo/gateway
and@apollo/server
could result in duplicate / differently versioned installs of@apollo/usage-reporting-protobuf
. This is because the@apollo/server-gateway-interface
package was updated to use the latest protobuf, but the@apollo/utils.usagereporting
package was not. After this change, users should always end up with a single install of the protobuf package when installing both@apollo/server
and@apollo/gateway
latest versions.
- #7539
5d3c45be9
Thanks @mayakoneval! - 🐛 Bug Fix for Apollo Server Landing Pages on Safari. A Content Security Policy was added to our landing page html so that Safari can run the inline scripts we use to call the Embedded Sandbox & Explorer.
-
#7504
22a5be934
Thanks @mayakoneval! - In the Apollo Server Landing Page Local config, you can now opt out of the telemetry that Apollo Studio runs in the embedded Sandbox & Explorer landing pages. This telemetry includes Google Analytics for event tracking and Sentry for error tracking.Example of the new config option:
const server = new ApolloServer({ typeDefs, resolvers, plugins: [ process.env.NODE_ENV === 'production' ? ApolloServerPluginLandingPageProductionDefault({ graphRef: 'my-graph-id@my-graph-variant', embed: { runTelemetry: false }, }) : ApolloServerPluginLandingPageLocalDefault({ embed: { runTelemetry: false }, }), ], });
-
#7465
1e808146a
Thanks @trevor-scheer! - Introduce new opt-in configuration option to mitigate v4 status code regressionApollo Server v4 accidentally started responding to requests with an invalid
variables
object with a 200 status code, where v3 previously responded with a 400. In order to not break current behavior (potentially breaking users who have creatively worked around this issue) and offer a mitigation, we've added the following configuration option which we recommend for all users.new ApolloServer({ // ... status400ForVariableCoercionErrors: true, });
Specifically, this regression affects cases where input variable coercion fails. Variables of an incorrect type (i.e.
String
instead ofInt
) or unexpectedlynull
are examples that fail variable coercion. Additionally, missing or incorrect fields on input objects as well as custom scalars that throw during validation will also fail variable coercion. For more specifics on variable coercion, see the "Input Coercion" sections in the GraphQL spec.This will become the default behavior in Apollo Server v5 and the configuration option will be ignored / no longer needed.
-
#7454
f6e3ae021
Thanks @trevor-scheer! - Start building packages with TS 5.x, which should have no effect for users -
#7433
e0db95b96
Thanks @KGAdamCook! - Previously, when users provided their owndocumentStore
, Apollo Server used a random prefix per schema in order to guarantee there was no shared state from one schema to the next. Now Apollo Server uses a hash of the schema, which enables the provided document store to be shared if you choose to do so.
-
#7431
7cc163ac8
Thanks @mayakoneval! - In the Apollo Server Landing Page Local config, you can now automatically turn off autopolling on your endpoints as well as pass headers used to introspect your schema, embed an operation from a collection, and configure whether the endpoint input box is editable. In the Apollo Server Landing Page Prod config, you can embed an operation from a collection & we fixed a bug introduced in release 4.4.0Example of all new config options:
const server = new ApolloServer({ typeDefs, resolvers, plugins: [ process.env.NODE_ENV === 'production' ? ApolloServerPluginLandingPageProductionDefault({ graphRef: 'my-graph-id@my-graph-variant', collectionId: 'abcdef', operationId: '12345' embed: true, footer: false, }) : ApolloServerPluginLandingPageLocalDefault({ collectionId: 'abcdef', operationId: '12345' embed: { initialState: { pollForSchemaUpdates: false, sharedHeaders: { "HeaderNeededForIntrospection": "ValueForIntrospection" }, }, endpointIsEditable: true, }, footer: false, }), ], });
-
#7430
b694bb1dd
Thanks @mayakoneval! - We now send your @apollo/server version to the embedded Explorer & Sandbox used in the landing pages for analytics.
-
#7432
8cbc61406
Thanks @mayakoneval! - Bug fix: TL;DR revert a previous change that stops passing includeCookies from the prod landing page config.Who was affected?
Any Apollo Server instance that passes a
graphRef
to a production landing page with a non-defaultincludeCookies
value that does not match theInclude cookies
setting on your registered variant on studio.apollographql.com.How were they affected?
From release 4.4.0 to this patch release, folks affected would have seen their Explorer requests being sent with cookies included only if they had set
Include cookies
on their variant. Cookies would not have been included by default.
- Updated dependencies [
021460e95
]:- @apollo/[email protected]
-
#7331
9de18b34c
Thanks @trevor-scheer! - Unpinnode-abort-controller
and update to latest unbreaking patch -
#7136
8c635d104
Thanks @trevor-scheer! - Errors reported by subgraphs (with no trace data in the response) are now accurately reflected in the numeric error stats.Operations that receive errors from subgraphs (with no trace data in the response) are no longer sent as incomplete, error-less traces.
If you are upgrading to or beyond this version, you may notice a change in your error stats in Apollo Studio. Previously, configuring
fieldLevelInstrumentation
inadvertently affected the counting of error stats in the usage reporting plugin (wheneverfieldLevelInstrumentation
was set to or resolved to 0, errors would not be counted). With this change, errors are counted accurately regardless of thefieldLevelInstrumentation
setting.Note: in order for this fix to take effect, your
@apollo/gateway
version must be updated to v2.3.1 or later.
-
#7314
f246ddb71
Thanks @trevor-scheer! - Add an__identity
property toHeaderMap
class to disallow standardMap
s (in TypeScript).This ensures that typechecking occurs on fields which are declared to accept a
HeaderMap
(notably, thehttpGraphQLRequest.headers
option toApolloServer.executeHTTPGraphQLRequest
and thehttp.headers
option toApolloServer.executeOperation
). This might be a breaking change for integration authors, but should be easily fixed by switching fromnew Map<string, string>()
tonew HeaderMap()
. -
#7326
e25cb58ff
Thanks @trevor-scheer! - Pinnode-abort-controller
version to avoid breaking change. Apollo Server users can enter a broken state if they update their package-lock.json due to a breaking change in a minor release of the mentioned package. -
Updated dependencies [
e0f959a63
]:- @apollo/[email protected]
-
#7313
ec28b4b33
Thanks @vtipparam! - Allow case insensitive lookup on headers. Use HeaderMap instead of plain Map for headers in expressMiddleware. -
#7311
322b5ebbc
Thanks @axe-me! - Export intermediate ApolloServerOptions* types -
#7274
3b0ec8529
Thanks @patrick91! - The subgraph spec has evolved in Federation v2 such that the type of_Service.sdl
(formerly nullable) is now non-nullable. Apollo Server now detects both cases correctly in order to determine whether to:- install / enable the
ApolloServerPluginInlineTrace
plugin - throw on startup if
ApolloServerPluginSchemaReporting
should not be installed - warn when
ApolloServerPluginUsageReporting
is installed and configured with the__onlyIfSchemaIsNotSubgraph
option
- install / enable the
- #7241
d7e9b9759
Thanks @glasser! - If the cache you provide to thepersistedQueries.cache
option is created withPrefixingKeyValueCache.cacheDangerouslyDoesNotNeedPrefixesForIsolation
(new in@apollo/[email protected]
), theapq:
prefix will not be added to cache keys. Providing such a cache tonew ApolloServer()
throws an error.
-
#7232
3a4823e0d
Thanks @glasser! - Refactor the implementation ofApolloServerPluginDrainHttpServer
's grace period. This is intended to be a no-op. -
#7229
d057e2ffc
Thanks @dnalborczyk! - Improve compatibility with Cloudflare workers by avoiding the use of the Nodeutil
package. This change is intended to be a no-op. -
#7228
f97e55304
Thanks @dnalborczyk! - Improve compatibility with Cloudflare workers by avoiding the use of the Nodeurl
package. This change is intended to be a no-op. -
#7241
d7e9b9759
Thanks @glasser! - For ease of upgrade from the recommended configuration of Apollo Server v3.9+, you can now passnew ApolloServer({ cache: 'bounded' })
, which is equivalent to not providing thecache
option (as a bounded cache is now the default in AS4).
- #7203
2042ee761
Thanks @glasser! - Fix v4.2.0 (#7171) regression where"operationName": null
,"variables": null
, and"extensions": null
in POST bodies were improperly rejected.
-
#7187
3fd7b5f26
Thanks @trevor-scheer! - Update@apollo/utils.keyvaluecache
dependency to the latest patch which correctly specifies its version oflru-cache
. -
Updated dependencies [
3fd7b5f26
]:- @apollo/[email protected]
-
#7171
37b3b7fb5
Thanks @glasser! - If a POST body contains a non-stringoperationName
or a non-objectvariables
orextensions
, fail with status code 400 instead of ignoring the field.In addition to being a reasonable idea, this provides more compliance with the "GraphQL over HTTP" spec.
This is a backwards incompatible change, but we are still early in the Apollo Server 4 adoption cycle and this is in line with the change already made in Apollo Server 4 to reject requests providing
variables
orextensions
as strings. If this causes major problems for users who have already upgraded to Apollo Server 4 in production, we can consider reverting or partially reverting this change. -
#7184
b1548c1d6
Thanks @glasser! - Don't automatically install the usage reporting plugin in servers that appear to be hosting a federated subgraph (based on the existence of a field_Service.sdl: String
). This is generally a misconfiguration. If an API key and graph ref are provided to the subgraph, log a warning and do not enable the usage reporting plugin. If the usage reporting plugin is explicitly installed in a subgraph, log a warning but keep it enabled.
-
#7170
4ce738193
Thanks @trevor-scheer! - Update @apollo/utils packages to v2 (dropping node 12 support) -
#7172
7ff96f533
Thanks @trevor-scheer! - startStandaloneServer: Restore body-parser request limit to 50mb (as it was in theapollo-server
package in Apollo Server 3) -
#7183
46af8255c
Thanks @glasser! - Apollo Server tries to detect if execution errors are variable coercion errors in order to give them acode
extension ofBAD_USER_INPUT
rather thanINTERNAL_SERVER_ERROR
. Previously this would unconditionally set thecode
; now, it only sets thecode
if nocode
is already set, so that (for example) custom scalarparseValue
methods can throw errors with specificcode
s. (Note that a separate graphql-js bug can lead to these extensions being lost; see graphql/graphql-js#3785 for details.) -
Updated dependencies [
4ce738193
,45856e1dd
]:- @apollo/[email protected]
-
#7118
c835637be
Thanks @glasser! - Provide newGraphQLRequestContext.requestIsBatched
field to gateways, because we did add it in a backport to AS3 and the gateway interface is based on AS3. -
Updated dependencies [
c835637be
]:- @apollo/[email protected]
-
2a2d1e3b4
Thanks @glasser! - Thecache-control
HTTP response header set by the cache control plugin now properly reflects the cache policy of all operations in a batched HTTP request. (If you write thecache-control
response header via a different mechanism to a format that the plugin would not produce, the plugin no longer writes the header.) For more information, see advisory GHSA-8r69-3cvp-wxc3. -
2a2d1e3b4
Thanks @glasser! - Plugins processing multiple operations in a batched HTTP request now have a sharedrequestContext.request.http
object. Changes to HTTP response headers and HTTP status code made by plugins operating on one operation can be immediately seen by plugins operating on other operations in the same HTTP request. -
2a2d1e3b4
Thanks @glasser! - New fieldGraphQLRequestContext.requestIsBatched
available to plugins.
-
#7104
15d8d65e0
Thanks @glasser! - NewApolloServerPluginSchemaReportingDisabled
plugin which can override theAPOLLO_SCHEMA_REPORTING
environment variable. -
#7101
e4e7738be
Thanks @glasser! - Manage memory more efficiently in the usage reporting plugin by allowing large objects to be garbage collected more quickly. -
#7101
e4e7738be
Thanks @glasser! - The usage reporting plugin now defaults to a 30 second timeout for each attempt to send reports to Apollo Server instead of no timeout; the timeout can be adjusted with the newrequestTimeoutMs
option toApolloServerPluginUsageReporting
. (Apollo's servers already enforced a 30 second timeout, so this is unlikely to break any existing use cases.) -
#7104
15d8d65e0
Thanks @glasser! - It is now an error to combine a "disabled" plugin such asApolloServerPluginUsageReportingDisabled
with its enabled counterpart such asApolloServerPluginUsageReporting
.
This version has no changes; @apollo/server
and @apollo/server-integration-test
are published with matching version numbers and we published a new version of @apollo/server-integration-test
.
-
#7073
e7f524eac
Thanks @glasser! - Never interpretGET
requests as batched. In previous versions of Apollo Server 4, aGET
request whose body was a JSON array with N elements would be interpreted as a batch of the operation specified in the query string repeated N times. Now we just ignore the body forGET
requests (like in Apollo Server 3), and never treat them as batched. -
#7071
0ed389ce8
Thanks @glasser! - Fix v4 regression: gateway implementations should be able to set HTTP response headers and the status code.
- #7035
b3f400063
Thanks @barryhagan! - Errors resulting from an attempt to use introspection when it is not enabled now have an additionalvalidationErrorCode: 'INTROSPECTION_DISABLED'
extension; this value is part of a new enumApolloServerValidationErrorCode
exported from@apollo/server/errors
.
-
#7049
3daee02c6
Thanks @glasser! - Raise minimumengines
requirement from Node.js v14.0.0 to v14.16.0. This is the minimum version of Node 14 supported by theengines
requirement of[email protected]
. -
#7049
3daee02c6
Thanks @glasser! - Require Node.js v14 rather than v12. This change was intended for v4.0.0 and the documentation already stated this requirement, but was left off of the package.jsonengines
field in@apollo/server
inadvertently.
Apollo Server contains quite a few breaking changes: most notably, a brand new package name! Read our migration guide for more details on how to update your app.
The minimum versions of these dependencies have been bumped to provide an improved foundation for the development of future features.
- Dropped support for Node.js v12, which is no longer under long-term support from the Node.js Foundation.
- Dropped support for versions of the
graphql
library prior tov16.6.0
.- Upgrading
graphql
may require you to upgrade other libraries that are installed in your project. For example, if you use Apollo Server with Apollo Gateway, you should upgrade Apollo Gateway to at least v0.50.1 or any v2.x version for fullgraphql
16 support before upgrading to Apollo Server 4.
- Upgrading
- If you use Apollo Server with TypeScript, you must use TypeScript v4.7.0 or newer.
Apollo Server 4 is distributed in the @apollo/server
package. This package replaces apollo-server
, apollo-server-core
, apollo-server-express
, apollo-server-errors
, apollo-server-types
, and apollo-server-plugin-base
.
The @apollo/server
package exports the ApolloServer
class. In Apollo Server 3, individual web framework integrations had their own subclasses of ApolloServer
. In Apollo Server 4, there is a single ApolloServer
class; web framework integrations define their own functions which use a new stable integration API on ApolloServer
to execute operations.
Other functionality is exported from "deep imports" on @apollo/server
. startStandaloneServer
(the replacement for the batteries-included apollo-server
package) is exported from @apollo/server/standalone
. expressMiddleware
(the replacement for apollo-server-express
) is exported from @apollo/server/express4
. Plugins such as ApolloServerPluginUsageReporting
are exported from paths such as @apollo/server/plugin/usageReporting
.
The @apollo/server
package is built natively as both an ECMAScript Module (ESM) and as a CommonJS module (CJS); Apollo Server 3 was only built as CJS. This allows ESM-native bundlers to create more efficient bundles.
Other packages have been renamed:
apollo-datasource-rest
is now@apollo/datasource-rest
.apollo-server-plugin-response-cache
is now@apollo/server-plugin-response-cache
.apollo-server-plugin-operation-registry
is now@apollo/server-plugin-operation-registry
.apollo-reporting-protobuf
(an internal implementation detail for the usage reporting plugin) is now@apollo/usage-reporting-protobuf
.
Prior to Apollo Server 4, the only way to integrate a web framework with Apollo Server was for the Apollo Server project to add an official apollo-server-x
subclass maintained as part of the core project. Apollo Server 4 makes it easy for users to integrate with their favorite web framework, and so we have removed most of the framework integrations from the core project so that framework integrations can be maintained by users who are passionate about that framework. Because of this, the core project no longer directly maintains integrations for Fastify, Hapi, Koa, Micro, AWS Lambda,Google Cloud Functions, Azure Functions, or Cloudflare. We expect that community integrations will eventually be created for most of these frameworks and serverless environments.
Apollo Server's support for the Express web framework no longer also supports its older predecessor Connect.
- The
dataSources
constructor option essentially added a post-processing step to your app's context function, creatingDataSource
subclasses and adding them to adataSources
field on your context value. This meant the TypeScript type thecontext
function returns was different from the context type your resolvers and plugins receive. Additionally, this design obfuscated thatDataSource
objects are created once per request (i.e., like the rest of the context object). Apollo Server 4 removes thedataSources
constructor option. You can now treatDataSources
like any other part of yourcontext
object. See the migration guide for details on how to move yourdataSources
function into yourcontext
function. - The
modules
constructor option was just a slightly different way of writingtypeDefs
andresolvers
(although it surprisingly used entirely different logic under the hood). This option has been removed. - The
mocks
andmockEntireSchema
constructor options wrapped an outdated version of the@graphql-tools/mocks
library to provide mocking functionality. These constructor options have been removed; you can instead directly incorporate the@graphql-tools/mock
package into your app, enabling you to get the most up-to-date mocking features. - The
debug
constructor option (which defaulted totrue
unless theNODE_ENV
environment variable is eitherproduction
ortest
) mostly controlled whether GraphQL errors responses included stack traces, but it also affected the default log level on the default logger. Thedebug
constructor option has been removed and is replaced withincludeStacktraceInErrorResponses
, which does exactly what it says it does. - The
formatResponse
constructor option has been removed; its functionality can be replaced by thewillSendResponse
plugin hook. - The
executor
constructor option has been removed; the ability to replacegraphql-js
's execution functionality is still available via thegateway
option.
- Apollo Server 4 no longer responds to health checks on the path
/.well-known/apollo/server-health
. You can run a trivial GraphQL operation as a health check, or you can add a custom health check via your web framework. - Apollo Server 4 no longer cares what URL path is used to access its functionality. Instead of specifying the
path
option to various Apollo Server methods, just use your web framework's routing feature to mount the Apollo Server integration at the appropriate path. - Apollo Server 4's Express middleware no longer wraps the
body-parser
andcors
middleware; it is your responsibility to install and set up these middleware yourself when using a framework integration. (The standalone HTTP server sets up body parsing and CORS for you, but without the ability to configure their details.) - Apollo Server no longer re-exports the
gql
tag function fromgraphql-tag
. If you want to usegql
, install thegraphql-tag
package. - Apollo Server no longer defines its own
ApolloError
class andtoApolloError
function. Instead, useGraphQLError
from thegraphql
package. - Apollo Server no longer exports error subclasses representing the errors that it creates, such as
SyntaxError
. Instead, it exports an enumApolloServerErrorCode
that you can use to recognize errors created by Apollo Server. - Apollo Server no longer exports the
ForbiddenError
andAuthenticationError
classes. Instead, you can define your own error codes for these errors or other errors. - The undocumented
__resolveObject
pseudo-resolver is no longer supported. - The
requestAgent
option toApolloServerPluginUsageReporting
has been removed. - In the JSON body of a
POST
request, thevariables
andextensions
fields must be objects, not JSON-encoded strings. - The core Apollo Server packages no longer provide a landing page plugin for the unmaintained GraphQL Playground UI. We have published an Apollo Server 4-compatible landing page plugin in the package
@apollo/server-plugin-landing-page-graphql-playground
, but do not intend to maintain it further after this one-time publish.
- The
context
function is now provided to your integration function (such asstartStandaloneServer
orexpressMiddleware
) rather than to thenew ApolloServer
constructor. - The
executeOperation
method now directly accepts a context value, rather than accepting the arguments to yourcontext
function. - The
formatError
hook now receives the original thrown error in addition to the formatted error. - Formatted errors no longer contain the
extensions.exception
field containing all enumerable properties of the originally thrown error. If you want to include more information in an error, specify them asextensions
when creating aGraphQLError
. Thestacktrace
field is provided directly onextensions
rather than nested underexception
. - All errors responses are consistently rendered as
application/json
JSON responses, and theformatError
hook is used consistently. - Other changes to error handling outside of resolvers are described in the migration guide.
- The
parseOptions
constructor option only affects the parsing of incoming operations, not the parsing oftypeDefs
.
- The field
GraphQLRequestContext.context
has been renamed tocontextValue
. - The field
GraphQLRequestContext.logger
is now readonly. - The fields
GraphQLRequestContext.schemaHash
andGraphQLRequestContext.debug
have been removed. - The type
GraphQLServiceContext
has been renamed toGraphQLServerContext
, and the fieldsschemaHash
,persistedQueries
, andserverlessFramework
have been removed; the latter has been semi-replaced bystartedInBackground
. - The
http
field on theGraphQLRequest
object (available to plugins asrequestContext.request
and as an argument toserver.executeOperation
) is no longer based on the Fetch API'sRequest
object. It no longer contains an URL path, and itsheaders
field is aMap
rather than aHeaders
object. - The structure of the
GraphQLResponse
object (available to plugins asrequestContext.response
and as the return value fromserver.executeOperation
) has changed in several ways. - The
plugins
constructor argument does not take factory functions. requestDidStart
hooks are called in parallel rather than in series.- A few changes have been made which may affect custom
gateway
andGraphQLDataSource
implementations.
- CSRF prevention is on by default.
- HTTP batching is disabled by default.
- The default in-memory cache is bounded.
- The local landing page defaults to the embedded Apollo Sandbox; this provides a user interface for executing GraphQL operations which doesn't require any additional CORS configuration.
- The usage reporting and inline trace plugins mask errors in their reports by default: error messages are replaced with
<masked>
and error extensions are replaced with a single extensionmaskedBy
. This can be configured with thesendErrors
option toApolloServerPluginUsageReporting
and theincludeErrors
option toApolloServerPluginInlineTrace
. TherewriteError
option to these plugins has been removed; its functionality is subsumed by the new options.
- The TypeScript types for the
validationRules
constructor option are more accurate. - We now use the
@apollo/utils.fetcher
package to define the shape of the Fetch API, instead ofapollo-server-env
. This package only supports argument structures that are likely to be compatible across implementations of the Fetch API. - The
CacheScope
,CacheHint
,CacheAnnotation
,CachePolicy
, andResolveInfoCacheControl
types are now exported from the@apollo/cache-control-types
package.CacheScope
is now a pure TypeScript type rather than an enum. - The type for
ApolloServer
's constructor options argument is nowApolloServerOptions
, notConfig
orApolloServerExpressConfig
. - Some other types have been renamed or removed; see the migration guide for details.
- In TypeScript, you can now declare your server's context value type using generic type syntax, like
new ApolloServer<MyContextType>
. This ensures that the type returned by your context function matches the context type provided to your resolvers and plugins. ApolloServer
now has a well-documented API for integrating with web frameworks, featuring the newexecuteHTTPGraphQLRequest
method.ApolloServer
now has explicit support for the "serverless" style of startup error handling. Serverless frameworks generally do not allow handlers to do "async" work during startup, so any failure to load the schema or runserverWillStart
handlers can't prevent requests from being served. Apollo Server 4 provides aserver.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests()
method as an alternative toawait server.start()
for use in contexts like serverless environments.- You can add a plugin to a server with
server.addPlugin()
. Plugins can only be added before the server isstart
ed. This allows you to pass the server itself as an argument to the plugin. ApolloServer
has new public readonlycache
andlogger
fields.- When combined with
graphql
v17 (only available as pre-releases as of September 2022), Apollo Server now has experimental support for incremental delivery directives such as@defer
and@stream
. - Apollo Server 4 adds new plugin hooks
startupDidFail
,contextCreationDidFail
,invalidRequestWasReceived
,unexpectedErrorProcessingRequest
,didEncounterSubsequentErrors
, andwillSendSubsequentPayload
. - If Apollo Server receives an operation while the server is shutting down, it now logs a warning telling you to properly configure HTTP server draining.
- Apollo Server now supports responses with
content-type: application/graphql-response+json
when requested by clients via theaccept
header, as described in the GraphQL over HTTP specification proposal.
The first version of Apollo Server published in the @apollo/server
package is v4.0.0. Before this release, all Apollo Server packages tracked their changes in a single file, which can be found at CHANGELOG_historical.md
.