Skip to content

Commit 8135ad9

Browse files
authored
Merge pull request #7690 from obrien-k/express
Recommend express.json() instead of body-parser
2 parents 040808b + c142fca commit 8135ad9

10 files changed

+29
-40
lines changed

docs/source/api/apollo-server.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ await server.start();
519519
app.use(
520520
'/graphql',
521521
cors<cors.CorsRequest>(),
522-
json(),
522+
express.json(),
523523
expressMiddleware(server),
524524
);
525525
```

docs/source/api/express-middleware.mdx

+4-6
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ This API reference documents Apollo Server 4's [Express](https://expressjs.com/)
1313

1414
The `expressMiddleware` function enables you to attach Apollo Server to an Express server.
1515

16-
The `expressMiddleware` function expects you to set up HTTP body parsing and CORS headers for your web framework. Specifically, you should install the [`body-parser`](https://www.npmjs.com/package/body-parser) and [`cors`](https://www.npmjs.com/package/cors) packages and use them to set up your Express app, as shown below.
16+
The `expressMiddleware` function expects you to set up HTTP body parsing and CORS headers for your web framework. Specifically, you can use the native [`express.json()`](https://expressjs.com/en/api.html#express.json) function (available in Express `v4.16.0` onwards) and the [`cors`](https://www.npmjs.com/package/cors) package to set up your Express app, as shown below.
1717

1818
> See [Configuring CORS](../security/cors#specifying-origins) for guidance on configuring the CORS behavior of your project.
1919
@@ -25,7 +25,6 @@ The `expressMiddleware` function accepts two arguments. The first **required** a
2525
import { ApolloServer } from '@apollo/server';
2626
import { expressMiddleware } from '@apollo/server/express4';
2727
import cors from 'cors';
28-
import { json } from 'body-parser';
2928
import express from 'express';
3029

3130
const app = express();
@@ -43,7 +42,7 @@ await server.start();
4342
app.use(
4443
'/graphql',
4544
cors<cors.CorsRequest>(),
46-
json(),
45+
express.json(),
4746
expressMiddleware(server),
4847
);
4948
//highlight-end
@@ -96,14 +95,13 @@ Below is a full example of setting up `expressMiddleware`:
9695
<MultiCodeBlock>
9796

9897
```ts
99-
// npm install @apollo/server express graphql cors body-parser
98+
// npm install @apollo/server express graphql cors
10099
import { ApolloServer } from '@apollo/server';
101100
import { expressMiddleware } from '@apollo/server/express4';
102101
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
103102
import express from 'express';
104103
import http from 'http';
105104
import cors from 'cors';
106-
import bodyParser from 'body-parser';
107105
import { typeDefs, resolvers } from './schema';
108106

109107
interface MyContext {
@@ -132,7 +130,7 @@ await server.start();
132130
app.use(
133131
'/',
134132
cors<cors.CorsRequest>(),
135-
bodyParser.json(),
133+
express.json(),
136134
// expressMiddleware accepts the same arguments:
137135
// an Apollo Server instance and optional configuration options
138136
expressMiddleware(server, {

docs/source/api/plugin/drain-http-server.mdx

+1-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHt
3636
import express from 'express';
3737
import http from 'http';
3838
import cors from 'cors';
39-
import { json } from 'body-parser';
4039
import { typeDefs, resolvers } from './schema';
4140

4241
interface MyContext {
@@ -59,7 +58,7 @@ await server.start();
5958
app.use(
6059
'/graphql',
6160
cors<cors.CorsRequest>(),
62-
json(),
61+
express.json(),
6362
expressMiddleware(server, {
6463
context: async ({ req }) => ({ token: req.headers.token }),
6564
}),

docs/source/api/standalone.mdx

+3-4
Original file line numberDiff line numberDiff line change
@@ -150,25 +150,24 @@ console.log(`🚀 Server ready at ${url}`);
150150
```
151151
</MultiCodeBlock>
152152

153-
To swap to using `expressMiddleware`, you'll first need to install the following packages so you'll be able to set up HTTP body parsing and CORS for your server:
153+
To swap to using `expressMiddleware`, you'll first need to install the following packages so you'll be able to set up CORS for your server:
154154

155155
```bash
156-
npm install express cors body-parser
156+
npm install express cors
157157
```
158158

159159
Next, we can modify our code to match the following:
160160

161161
<MultiCodeBlock>
162162

163163
```ts
164-
// npm install @apollo/server express graphql cors body-parser
164+
// npm install @apollo/server express graphql cors
165165
import { ApolloServer } from '@apollo/server';
166166
import { expressMiddleware } from '@apollo/server/express4';
167167
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
168168
import express from 'express';
169169
import http from 'http';
170170
import cors from 'cors';
171-
import bodyParser from 'body-parser';
172171
import { typeDefs, resolvers } from './schema';
173172

174173
interface MyContext {

docs/source/data/subscriptions.mdx

+1-2
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,6 @@ import express from 'express';
146146
import { makeExecutableSchema } from '@graphql-tools/schema';
147147
import { WebSocketServer } from 'ws';
148148
import { useServer } from 'graphql-ws/lib/use/ws';
149-
import bodyParser from 'body-parser';
150149
import cors from 'cors';
151150
import resolvers from './resolvers';
152151
import typeDefs from './typeDefs';
@@ -192,7 +191,7 @@ await server.start();
192191
app.use(
193192
'/graphql',
194193
cors<cors.CorsRequest>(),
195-
bodyParser.json(),
194+
express.json(),
196195
expressMiddleware(server),
197196
);
198197

docs/source/deployment/lambda.mdx

+2-4
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,6 @@ const { ApolloServer } = require('@apollo/server');
473473
const { expressMiddleware } = require('@apollo/server/express4');
474474
const serverlessExpress = require('@vendia/serverless-express');
475475
const express = require('express');
476-
const { json } = require('body-parser');
477476
const cors = require('cors');
478477
479478
const server = new ApolloServer({
@@ -486,7 +485,7 @@ server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
486485
const app = express();
487486
app.use(
488487
cors(),
489-
json(),
488+
express.json(),
490489
expressMiddleware(server, {
491490
// The Express request and response objects are passed into
492491
// your context initialization function
@@ -523,7 +522,6 @@ const { ApolloServer } = require('@apollo/server');
523522
const { expressMiddleware } = require('@apollo/server/express4');
524523
const serverlessExpress = require('@vendia/serverless-express');
525524
const express = require('express');
526-
const { json } = require('body-parser');
527525
const cors = require('cors');
528526
529527
const server = new ApolloServer({
@@ -534,7 +532,7 @@ const server = new ApolloServer({
534532
server.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
535533
536534
const app = express();
537-
app.use(cors(), json(), expressMiddleware(server));
535+
app.use(cors(), express.json(), expressMiddleware(server));
538536
539537
exports.graphqlHandler = serverlessExpress({ app });
540538
```

docs/source/migration.mdx

+8-10
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ If there is no Apollo Server integration for your favorite framework _yet_, help
6464
Below are a few high-level changes for using framework integrations:
6565

6666
- You can pass your [`context` initialization function](#context-initialization-function) directly to your framework's integration function (e.g., `expressMiddleware` or `startStandaloneServer`) instead of the `ApolloServer` constructor.
67-
- You are responsible for [setting up HTTP body parsing and CORS](#body-parser-and-cors) using your framework integration's standard functionality.
67+
- You are responsible for [setting up HTTP body parsing and CORS](#http-body-parsing-and-cors) using your framework integration's standard functionality.
6868
- If you want your server to listen on a specific URL path, pass that path directly to your framework's router instead of using the [`path` option](#path-parsing). If you did not specify a URL path, the default in Apollo Server 3 was `/graphql`, so to preserve existing behavior, you should specify that path explicitly.
6969

7070
The following sections show how servers using `apollo-server` or `apollo-server-express` can update to Apollo Server 4.
@@ -189,9 +189,9 @@ If you used the `apollo-server-express` package in Apollo Server 3, use the `exp
189189

190190
To migrate from Apollo Server 3's `apollo-server-express` package to using the `expressMiddleware` function, do the following:
191191

192-
1. Install the `@apollo/server`, `cors`, and `body-parser` packages.
192+
1. Install the `@apollo/server` and `cors` packages.
193193
2. Import symbols from `@apollo/server` (i.e., instead of from `apollo-server-express` and `apollo-server-core`).
194-
3. Add `cors` and `bodyParser.json()` to your server setup.
194+
3. Add `cors` to your server setup.
195195
4. Remove the Apollo Server 3 `apollo-server-express` and `apollo-server-core` packages.
196196
5. If you are using `apollo-server-express`'s default `/graphql` URL path (i.e., not specifying another URL with the [path option](/apollo-server/v3/api/apollo-server/#path)), you can mount `expressMiddleware` at `/graphql` to maintain behavior. To use another URL path, mount your server (with `app.use`) at the specified path.
197197

@@ -232,15 +232,13 @@ looks like this in Apollo Server 4:
232232
<MultiCodeBlock>
233233

234234
```ts title="apollo-server-4.ts"
235-
// npm install @apollo/server express graphql cors body-parser
235+
// npm install @apollo/server express graphql cors
236236
import { ApolloServer } from '@apollo/server';
237237
import { expressMiddleware } from '@apollo/server/express4';
238238
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
239239
import express from 'express';
240240
import http from 'http';
241241
import cors from 'cors';
242-
import pkg from 'body-parser';
243-
const { json } = pkg;
244242
import { typeDefs, resolvers } from './schema';
245243

246244
interface MyContext {
@@ -257,7 +255,7 @@ const server = new ApolloServer<MyContext>({
257255
await server.start();
258256
app.use('/graphql',
259257
cors<cors.CorsRequest>(),
260-
json(),
258+
express.json(),
261259
expressMiddleware(server, {
262260
context: async ({ req }) => ({ token: req.headers.token }),
263261
}),
@@ -910,11 +908,11 @@ In Apollo Server 4, you should use your framework's routing feature to mount you
910908

911909
> Apollo Server 3's batteries-included `apollo-server` package, replaced by `startStandaloneServer` in Apollo Server 4, serves all URLs (i.e., rather than only listening on `/graphql`).
912910
913-
### `body-parser` and `cors`
911+
### HTTP body parsing and CORS
914912

915913
In Apollo Server 3, framework integrations automatically set up HTTP body parsing and CORS response headers. You can customize your integration's CORS or body parsing functionality using the Apollo Server API; these configuration options [vary by integration](/apollo-server/v3/api/apollo-server#cors-1).
916914

917-
In Apollo Server 4, it's your responsibility to set up HTTP body parsing and CORS headers for your web framework. Specifically, when using [`expressMiddleware`](#migrate-from-apollo-server-express), you should install the `body-parser` and `cors` npm packages and use them in your Express app, just like with any other JSON-based API server. If you passed a `cors` option to `applyMiddleware` or `getMiddleware`, pass the same value to the `cors` function. If you passed a `bodyParserConfig` option to `applyMiddleware` or `getMiddleware`, pass the same value to the `body-parser` package's `json` function.
915+
In Apollo Server 4, it's your responsibility to set up HTTP body parsing and CORS headers for your web framework. Specifically, when using [`expressMiddleware`](#migrate-from-apollo-server-express), you can use the native [`express.json()`](https://expressjs.com/en/api.html#express.json) function (available in Express `v4.16.0` onwards) for body parsing and the `cors` npm package for CORS headers. You can install use the `cors` package in your Express app, just like with any other JSON-based API server. If you passed a `cors` option to `applyMiddleware` or `getMiddleware`, pass the same value to the `cors` function. If you passed a `bodyParserConfig` option to `applyMiddleware` or `getMiddleware`, pass the same value to the [`express.json()`](https://expressjs.com/en/api.html#express.json) function.
918916

919917
Note that [`startStandaloneServer`](#migrate-from-apollo-server) sets up body parsing and CORS functionality for you, but you can't configure this behavior. In Apollo Server 3, you could configure the batteries-included `apollo-server`'s CORS behavior via the `cors` constructor option. In Apollo Server 4, if you need to configure CORS behavior, use `expressMiddleware` rather than `startStandaloneServer`.
920918

@@ -1106,7 +1104,7 @@ Whereas this query would be invalid:
11061104
If you'd like to restore the previous behavior, you can `JSON.parse` the `variables` and `extensions` fields after your framework has parsed the request body. In Express that might look like:
11071105

11081106
```ts
1109-
app.use(json());
1107+
app.use(express.json());
11101108
app.use((req, res, next) => {
11111109
if (typeof req.body?.variables === 'string') {
11121110
try {

docs/source/monitoring/health-checks.mdx

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Health checks
33
description: Determining the health status of Apollo Server
44
---
55

6-
> **Apollo Server 4 no longer [supports built-in health checks](../migration/#health-checks)**. Instead, we recommend performing [GraphQL-level health checks](#graphql-level-health-checks) to ensure your server successfully serves traffic _and_ performs GraphQL operations.
6+
> **Apollo Server 4 no longer [supports built-in health checks](../migration/#health-checks)**. Instead, we recommend performing [GraphQL-level health checks](#graphql-level-health-checks) to ensure your server successfully serves traffic _and_ performs GraphQL operations.
77
88
Load balancers often use health checks to determine if a server is available and ready to serve traffic.
99

@@ -21,7 +21,7 @@ Note that this health check will run an actual GraphQL operation. If your server
2121

2222
> Sending an `apollo-require-preflight: true` header alongside your health check ensures that Apollo Server's [CSRF prevention](../security/cors/#preventing-cross-site-request-forgery-csrf) feature won't block it.
2323
24-
If you want to create a health check for your HTTP server that is _unrelated_ to the health of the GraphQL execution engine (i.e., such as [Apollo Server 3's health check feature](/apollo-server/v3/monitoring/health-checks)), you can add a `GET` handler that always succeeds to your web framework.
24+
If you want to create a health check for your HTTP server that is _unrelated_ to the health of the GraphQL execution engine (i.e., such as [Apollo Server 3's health check feature](/apollo-server/v3/monitoring/health-checks)), you can add a `GET` handler that always succeeds to your web framework.
2525

2626
Below is an example of an HTTP server health check with [`expressMiddleware`](../api/express-middleware/):
2727

@@ -39,7 +39,7 @@ const server = new ApolloServer({
3939
await server.start();
4040
app.use('/graphql',
4141
cors<cors.CorsRequest>(),
42-
json(),
42+
express.json(),
4343
expressMiddleware(server)
4444
);
4545
await new Promise<void>(resolve => app.listen({ port: 4000 }, resolve));
@@ -56,4 +56,4 @@ app.get('/health', (req, res) => {
5656

5757
</MultiCodeBlock>
5858

59-
> If you are using `startStandaloneServer`, you must first [swap to using the `expressMiddleware` function](../api/standalone/#swapping-to-expressmiddleware) before creating an HTTP server health check.
59+
> If you are using `startStandaloneServer`, you must first [swap to using the `expressMiddleware` function](../api/standalone/#swapping-to-expressmiddleware) before creating an HTTP server health check.

docs/source/security/cors.mdx

+4-5
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ If you create a public API or an API to embed in websites you don't control your
8686
If your application doesn't fit into any of the above categories, [`startStandaloneServer`](../api/standalone)'s CORS behavior should suit your use case. You can always choose to swap to another Apollo Server integration later to [customize your CORS configuration](#configuring-cors-options-for-apollo-server).
8787

8888
## Configuring CORS options for Apollo Server
89-
> 📣 **New in Apollo Server 4**: if you are using an Apollo Server integration (e.g., [`expressMiddleware`](../api/express-middleware)), you are responsible for [setting up CORS for your web framework](../migration#body-parser-and-cors).
89+
> 📣 **New in Apollo Server 4**: if you are using an Apollo Server integration (e.g., [`expressMiddleware`](../api/express-middleware)), you are responsible for [setting up CORS for your web framework](../migration#http-body-parsing-and-cors).
9090
9191
Apollo Server's standalone server (i.e., [`startStandaloneServer`](../api/standalone)) serves the `Access-Control-Allow-Origin` HTTP header with the wildcard value (`*`). This allows scripts on any origin to make requests, _without cookies_, to the server and read its responses.
9292

@@ -104,7 +104,6 @@ import { expressMiddleware } from '@apollo/server/express4';
104104
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
105105
import express from 'express';
106106
import http from 'http';
107-
import { json } from 'body-parser';
108107
import { typeDefs, resolvers } from './schema';
109108
// highlight-start
110109
import cors from 'cors';
@@ -125,7 +124,7 @@ app.use(
125124
// highlight-start
126125
cors<cors.CorsRequest>({ origin: ['https://www.your-app.example', 'https://studio.apollographql.com'] }),
127126
// highlight-end
128-
json(),
127+
express.json(),
129128
expressMiddleware(server),
130129
);
131130

@@ -137,7 +136,7 @@ console.log(`🚀 Server ready at http://localhost:4000/graphql`);
137136

138137
> Invoking the `cors` function with no arguments sets your server's `Access-Control-Allow-Origin` HTTP header to the wildcard value (`*`), allowing scripts on any origin to make requests. So, your server would have the same CORS behavior as `startStandaloneServer`.
139138
140-
Using the `cors` package directly, we can configure the `Access-Control-Allow-Origin` header using the [`origin` option](https://github.com/expressjs/cors#configuration-options). The example above enables CORS requests from `https://www.your-app.example`, along with `https://studio.apollographql.com`.
139+
Using the `cors` package directly, we can configure the `Access-Control-Allow-Origin` header using the [`origin` option](https://github.com/expressjs/cors#configuration-options). The example above enables CORS requests from `https://www.your-app.example`, along with `https://studio.apollographql.com`.
141140

142141
> If you want to use [Apollo Studio Explorer](https://www.apollographql.com/docs/studio/explorer/explorer/) as a GraphQL web IDE, you should include `https://studio.apollographql.com` in your list of valid origins. However, if you plan to embed the [Explorer](https://www.apollographql.com/docs/studio/explorer/embed-explorer/) or use [Apollo Sandbox](https://www.apollographql.com/docs/studio/explorer/sandbox), you *don't* need to specify Studio's URL in your CORS origins because requests will go through the page embedding Studio.
143142
@@ -170,7 +169,7 @@ app.use(
170169
credentials: true,
171170
}),
172171
// highlight-end
173-
json(),
172+
express.json(),
174173
expressMiddleware(server),
175174
);
176175
```

docs/source/security/terminating-ssl.mdx

+1-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHt
2121
import typeDefs from './graphql/schema';
2222
import resolvers from './graphql/resolvers';
2323
import cors from 'cors';
24-
import bodyParser from 'body-parser';
2524
import express from 'express';
2625
import http from 'http';
2726
import https from 'https';
@@ -47,7 +46,7 @@ const app = express();
4746
app.use(
4847
'/graphql',
4948
cors<cors.CorsRequest>(),
50-
bodyParser.json(),
49+
express.json(),
5150
expressMiddleware(server),
5251
);
5352

0 commit comments

Comments
 (0)