API Reference: expressMiddleware


This API reference documents Apollo Server 4's Express integration, the expressMiddleware function.

expressMiddleware

In the examples below, we use top-level await calls to start our server asynchronously. Check out our Getting Started guide to see how we configured our project to support this.

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

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() function (available in Express v4.16.0 onwards) and the cors package to set up your Express app, as shown below.

See Configuring CORS for guidance on configuring the CORS behavior of your project.

The expressMiddleware function accepts two arguments. The first required argument is an instance of ApolloServer that has been started by calling its start method:

TypeScript
1import { ApolloServer } from '@apollo/server';
2import { expressMiddleware } from '@apollo/server/express4';
3import cors from 'cors';
4import express from 'express';
5
6const app = express();
7
8const server = new ApolloServer<MyContext>({
9  typeDefs,
10  resolvers,
11});
12// Note you must call `start()` on the `ApolloServer`
13// instance before passing the instance to `expressMiddleware`
14await server.start();
15
16// Specify the path where we'd like to mount our server
17//highlight-start
18app.use(
19  '/graphql',
20  cors<cors.CorsRequest>(),
21  express.json(),
22  expressMiddleware(server),
23);
24//highlight-end

⚠️ To ensure your server gracefully shuts down, we recommend using the ApolloServerPluginDrainHttpServer plugin. See below for an example .

The expressMiddleware function's second optional argument is an object for configuring ApolloServer, which can contain the following options:

Name /
Type
Description
context
Function
An optional asynchronous context initialization function .The context function should return an object that all your server's resolvers share during an operation's execution. This enables resolvers to share helpful context values, such as a database connection.The context function receives req and res options which are express.Request and express.Response objects.

Example

Below is a full example of setting up expressMiddleware:

TypeScript
1// npm install @apollo/server express graphql cors
2import { ApolloServer } from '@apollo/server';
3import { expressMiddleware } from '@apollo/server/express4';
4import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
5import express from 'express';
6import http from 'http';
7import cors from 'cors';
8import { typeDefs, resolvers } from './schema';
9
10interface MyContext {
11  token?: string;
12}
13
14// Required logic for integrating with Express
15const app = express();
16// Our httpServer handles incoming requests to our Express app.
17// Below, we tell Apollo Server to "drain" this httpServer,
18// enabling our servers to shut down gracefully.
19const httpServer = http.createServer(app);
20
21// Same ApolloServer initialization as before, plus the drain plugin
22// for our httpServer.
23const server = new ApolloServer<MyContext>({
24  typeDefs,
25  resolvers,
26  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
27});
28// Ensure we wait for our server to start
29await server.start();
30
31// Set up our Express middleware to handle CORS, body parsing,
32// and our expressMiddleware function.
33app.use(
34  '/',
35  cors<cors.CorsRequest>(),
36  express.json(),
37  // expressMiddleware accepts the same arguments:
38  // an Apollo Server instance and optional configuration options
39  expressMiddleware(server, {
40    context: async ({ req }) => ({ token: req.headers.token }),
41  }),
42);
43
44// Modified server startup
45await new Promise<void>((resolve) =>
46  httpServer.listen({ port: 4000 }, resolve),
47);
48console.log(`🚀 Server ready at http://localhost:4000/`);