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 should install the body-parser
and cors
packages and use them 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 start
ed:
import { ApolloServer } from '@apollo/server';import { expressMiddleware } from '@apollo/server/express4';import cors from 'cors';import { json } from 'body-parser';import express from 'express';const app = express();const server = new ApolloServer<MyContext>({typeDefs,resolvers,});// Note you must call `server.start()` on the `ApolloServer`// instance before passing the instance to `expressMiddleware`await server.start();// Specify the path where we'd like to mount our serverapp.use('/graphql', cors<cors.CorsRequest>(), json(), expressMiddleware(server));
import { ApolloServer } from '@apollo/server';import { expressMiddleware } from '@apollo/server/express4';import cors from 'cors';import { json } from 'body-parser';import express from 'express';const app = express();const server = new ApolloServer({typeDefs,resolvers,});// Note you must call `server.start()` on the `ApolloServer`// instance before passing the instance to `expressMiddleware`await server.start();// Specify the path where we'd like to mount our serverapp.use('/graphql', cors(), json(), expressMiddleware(server));
⚠️ 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 |
---|---|
| An optional asynchronous The The |
Example
Below is a full example of setting up expressMiddleware
:
// npm install @apollo/server express graphql cors body-parserimport { ApolloServer } from '@apollo/server';import { expressMiddleware } from '@apollo/server/express4';import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';import express from 'express';import http from 'http';import cors from 'cors';import bodyParser from 'body-parser';import { typeDefs, resolvers } from './schema';interface MyContext {token?: string;}// Required logic for integrating with Expressconst 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 startawait server.start();// Set up our Express middleware to handle CORS, body parsing,// and our expressMiddleware function.app.use('/',cors<cors.CorsRequest>(),bodyParser.json(),// expressMiddleware accepts the same arguments:// an Apollo Server instance and optional configuration optionsexpressMiddleware(server, {context: async ({ req }) => ({ token: req.headers.token }),}),);// Modified server startupawait new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at http://localhost:4000/`);
// npm install @apollo/server express graphql cors body-parserimport { ApolloServer } from '@apollo/server';import { expressMiddleware } from '@apollo/server/express4';import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';import express from 'express';import http from 'http';import cors from 'cors';import bodyParser from 'body-parser';import { typeDefs, resolvers } from './schema';// Required logic for integrating with Expressconst 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({typeDefs,resolvers,plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],});// Ensure we wait for our server to startawait server.start();// Set up our Express middleware to handle CORS, body parsing,// and our expressMiddleware function.app.use('/',cors(),bodyParser.json(),// expressMiddleware accepts the same arguments:// an Apollo Server instance and optional configuration optionsexpressMiddleware(server, {context: async ({ req }) => ({ token: req.headers.token }),}),);// Modified server startupawait new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at http://localhost:4000/`);