Back to Apollo Server

API Reference: expressMiddleware

docs/source/api/express-middleware.mdx

1.4.15.3 KB
Original Source

import TopLevelAwait from "../shared/top-level-await.mdx"

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

Apollo Server integrates with these Express versions through official integrations:

  • Express v4: Install with npm install @as-integrations/express4
  • Express v5: Install with npm install @as-integrations/express5

You must also install Express itself. Both packages export a function named expressMiddleware with the same API.

<Note>

In Apollo Server 4, you can also import the Express v4 integration from @apollo/server/express without installing a second package. This does not support Express v5, and it was removed in Apollo Server 5. We recommend installing the separate package to make upgrading Apollo Server and Express easier.

</Note>

expressMiddleware

<TopLevelAwait />

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:

<MultiCodeBlock>
ts
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express5';
import cors from 'cors';
import express from 'express';

const app = express();

const server = new ApolloServer<MyContext>({
  typeDefs,
  resolvers,
});
// Note you must call `start()` on the `ApolloServer`
// instance before passing the instance to `expressMiddleware`
await server.start();

// Specify the path where we'd like to mount our server
//highlight-start
app.use(
  '/graphql',
  cors<cors.CorsRequest>(),
  express.json(),
  expressMiddleware(server),
);
//highlight-end
</MultiCodeBlock>

⚠️ 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:

<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>
context

Function

</td> <td>

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.

</td> </tr> </tbody> </table>

Example

Below is a full example of setting up expressMiddleware:

<MultiCodeBlock>
ts
// npm install @apollo/server @as-integrations/express5 express graphql cors
import { ApolloServer } from '@apollo/server';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { expressMiddleware } from '@as-integrations/express5';
import express from 'express';
import http from 'http';
import cors from 'cors';
import { typeDefs, resolvers } from './schema';

interface MyContext {
  token?: string;
}

// Required logic for integrating with Express
const app = express();
// Our httpServer handles incoming requests to our Express app.
// Below, we tell Apollo Server to "drain" this httpServer,
// enabling our servers to shut down gracefully.
const httpServer = http.createServer(app);

// Same ApolloServer initialization as before, plus the drain plugin
// for our httpServer.
const server = new ApolloServer<MyContext>({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
// Ensure we wait for our server to start
await server.start();

// Set up our Express middleware to handle CORS, body parsing,
// and our expressMiddleware function.
app.use(
  '/',
  cors<cors.CorsRequest>(),
  express.json(),
  // expressMiddleware accepts the same arguments:
  // an Apollo Server instance and optional configuration options
  expressMiddleware(server, {
    context: async ({ req }) => ({ token: req.headers.token }),
  }),
);

// Modified server startup
await new Promise<void>((resolve) =>
  httpServer.listen({ port: 4000 }, resolve),
);
console.log(`🚀 Server ready at http://localhost:4000/`);
</MultiCodeBlock>