Deploying a serverless GraphQL endpoint with Apollo Server and Next.js

Next.js allows you to create API Routes within your application. When deployed to Vercel, these routes are created as Serverless Functions, so they will alway run on the server side.

Using Apollo Server, we are going to setup a serverless GraphQL endpoint. This endpoint can then run any backend code and call other APIs or a database (DynamoDB, SQL…).

We will consider that you have already set up your Next.js project.

1. Install Apollo Server

First of all, let's install apollo-server-micro.

npm install apollo-server-micro

This package is a Micro integration for Apollo Server. It is shipped as part of every Apollo Server release, so it is not a third-party package.

Micro is a webserver for microservices. Serverless Functions do not require Micro anymore but they have the same API, so they will be able to talk to Apollo Server with this integration.

2. Create the /api/graphql endpoint

Create a new file at pages/api/graphql.js :

import { ApolloServer, gql } from 'apollo-server-micro';

// This data will be returned by our test endpoint
const products = [
  {
    id: 1,
    name: 'Cookie',
    price: 300,
  },
  {
    id: 2,
    name: 'Brownie',
    price: 350,
  },
];

// Construct a schema using GraphQL schema language
const typeDefs = gql`
  type Product {
    id: Int
    name: String
    price: Int
  }

  type Query {
    products: [Product]
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    products: () => {
      return products;
    },
  },
};

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

export default server.createHandler({
  path: '/api/graphql',
});

export const config = {
  api: {
    bodyParser: false,
  },
};

Here is what is happening here:

And that's all! You can now query your API by calling the /api/graphql endpoint.

In development mode, the GraphQL Playground can be reached by opening http://localhost:3000/api/graphql in your browser!

GraphQL Playground Screenshot