docs/source/api/plugin/drain-http-server.mdx
import TopLevelAwait from "../../shared/top-level-await.mdx"
This article documents the options for the ApolloServerPluginDrainHttpServer plugin, which you can import from @apollo/server/plugin/drainHttpServer.
This plugin is designed for use with expressMiddleware and other framework integrations built on top of Node http.Servers. We highly recommend using this plugin to ensure your server shuts down gracefully.
You do not need to use this plugin with the
startStandaloneServerfunction; it automatically handles server draining.
When you use this plugin, Apollo Server will drain your HTTP server when you call the stop() method (which is also called for you when the SIGTERM and SIGINT signals are received, unless disabled with the stopOnTerminationSignals constructor option).
Specifically, it will:
This plugin is exported from the @apollo/server package. Here's a basic example of how to use it with Express:
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;
}
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);
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
app.use(
'/graphql',
cors<cors.CorsRequest>(),
express.json(),
expressMiddleware(server, {
context: async ({ req }) => ({ token: req.headers.token }),
}),
);
await new Promise<void>((resolve) =>
httpServer.listen({ port: 4000 }, resolve),
);
console.log(`🚀 Server ready at http://localhost:4000/graphql`);
httpServerThe server to drain; required.
</td> </tr> <tr> <td>stopGracePeriodMillisnumber
How long to wait before forcefully closing non-idle connections. Defaults to 10_000 (ten seconds).