Apollo Server Integration for Express v5
Introduction
This package integrates Apollo Server v4 with version 5 of the Express web framework, by exporting a middleware that executes GraphQL operations.
It is identical to the middleware exported at @apollo/server/express5 from the core @apollo/server v4 package, updated to support Express v5 instead of Express v4.
Requirements
Installation
npm install @apollo/server graphql express@5 @as-integrations/express5 cors
Usage
Set up Express & Apollo Server like you usually would, and then connect the two by using the expressMiddleware middleware:
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express5';
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;
}
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});
await server.start();
app.use(
'/',
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/`);
Note: You must call and await server.start() before using the integration.