Docs
Launch GraphOS Studio

API Reference: expressMiddleware


This API reference documents 4's

integration, the expressMiddleware function.

expressMiddleware

NOTE

In the examples below, we use top-level

calls to start our server asynchronously. If you'd like to see how we set this up, check out the
Getting Started
guide for details.

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

function (available in Express v4.16.0 onwards) and the
cors
package to set up your Express app, as shown below.

See

for guidance on configuring the CORS behavior of your project.

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

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
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
app.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server));
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import cors from 'cors';
import express from 'express';
const app = express();
const server = new ApolloServer({
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
app.use('/graphql', cors(), express.json(), expressMiddleware(server));

⚠️ To ensure your server gracefully shuts down, we recommend using the

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

.

The context function should return an object that all your server's share during an '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

and
express.Response
objects.

Example

Below is a full example of setting up expressMiddleware:

// npm install @apollo/server express graphql cors
import { 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 { 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/`);
// npm install @apollo/server express graphql cors
import { 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 { typeDefs, resolvers } from './schema';
// 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({
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(),
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((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000/`);
Previous
startStandaloneServer
Next
Overview
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company