Join us for GraphQL Summit, October 10-12 in San Diego. Use promo code ODYSSEY for $400 off your pass.
Docs
Launch GraphOS Studio
Apollo Server 2 is officially deprecated, with end-of-life scheduled for 22 October 2023. Additionally, certain features are end-of-life as of 31 December 2023. Learn more about these deprecations and upgrading.

Integrating with Node.js middleware

Use Apollo Server with Express, Koa, and more


Apollo Server integrates easily with several popular Node.js middleware libraries. To integrate, first install the appropriate package from the table below instead of the core apollo-server package:

MiddlewarePackage
Expressapollo-server-express
AWS Lambdaapollo-server-lambda
Koaapollo-server-koa
hapiapollo-server-hapi
Microapollo-server-micro
Fastifyapollo-server-fastify
Google Cloud Functionsapollo-server-cloud-functions
Azure Functionsapollo-server-azure-functions
Cloudflareapollo-server-cloudflare

If you've already installed the core apollo-server package, you can npm uninstall it after installing an integration package.

Applying middleware

When integrating with middleware, first you initialize Apollo Server just like you always do, and then you call applyMiddleware.

Here's a basic Express example that serves Hello! from every path except /graphql, which serves a GraphQL endpoint with Apollo Server:

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');
async function startApolloServer() {
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers,
});
await server.start();
server.applyMiddleware({ app });
app.use((req, res) => {
res.status(200);
res.send('Hello!');
res.end();
});
await new Promise(resolve => app.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
return { server, app };
}

The parameter you provide to applyMiddleware is your middleware's top-level representation of your application. In Express applications, this is commonly named app.

When you pass your app to applyMiddleware, Apollo Server automatically configures various middleware (including body parsing, the GraphQL Playground frontend, and CORS support), so you don't need to apply them with a mechanism like app.use.

Note: When integrating with hapi, call applyMiddleware with await.

Previous
Terminating SSL
Next
Plugins
Edit on GitHubEditForumsDiscord