March 2, 2021

Using Express with GraphQL – How to create a GraphQL server with Node.js/Express

Khalil Stemmler

Khalil Stemmler

One of the fastest ways to get up and running with GraphQL is to install Apollo Server as middleware on your new or existing HTTP server.

In this short post, we demonstrate how to use Apollo Server to create a GraphQL server with Express.js using the apollo-server-express package. At the end, we’ll discuss the tradeoffs of this approach.

Using Apollo Server with Express

Let’s start with the dependencies.

Install dependencies

You’ll need the apollo-server-express and graphql packages.

npm install apollo-server-express graphql --save

Example

The way we set up a GraphQL server using apollo-server-express is very similar to the barebones approach of using the apollo-server package.

The only difference is that we apply the Apollo Server instance as middleware to an Express HTTP instance with server.applyMiddleware({ app }).

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);


Your GraphQL API should be running at http://localhost:4000/graphql.

Tradeoffs of using Apollo Server as GraphQL middleware

Advantages

One neat thing about using apollo-server-express instead of apollo-server is that we can serve both REST and GraphQL at the same time using Express.

Serving a GraphQL server within Express also maintains our ability to use Node.js middleware for common problems like rate-limiting, security, and authentication.

Downsides

Using apollo-server-express involves a little bit more boilerplate than merely using apollo-server. However, since apollo-server is just a wrapper around apollo-server-express, there shouldn’t be any performance concerns.

Conclusion

We learned how to set up a GraphQL server with apollo-server-express and discussed some of the tradeoffs. If you’re using a different middleware library like Restify, Hapi, Koa, or Lambdas, check out our docs for details on the other GraphQL API integrations.

Written by

Khalil Stemmler

Khalil Stemmler

Read more by Khalil Stemmler