Skip to content

apollo-server-integrations/apollo-server-integration-cloudflare-workers

Repository files navigation

@as-integrations/cloudflare-workers

NPM version

An integration to use Cloudflare Workers as a hosting service with Apollo Server.

Quickstart

Install

npm add @apollo/server @as-integrations/cloudflare-workers graphql

Usage

You must enable Node.js compatibility feature by adding the following flag in the file wrangler.toml:

compatibility_flags = ["nodejs_compat"] # wrangler v4
# node_compat = true  # or wrangler v3
import { ApolloServer } from '@apollo/server';
import { startServerAndCreateCloudflareWorkersHandler } from '@as-integrations/cloudflare-workers';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';

const typeDefs = `#graphql
  type Query {
    example: String!
  }
`;

const resolvers = {
  Query: {
    example: () => {
      return 'Hello universe!';
    },
  }
}

interface Context {
  token: string
}

const server = new ApolloServer<Context>({
  typeDefs,
  resolvers,
  introspection: true,
  plugins: [
    ApolloServerPluginLandingPageLocalDefault({ footer: false }),
  ],
});

export interface Env {
  // ...
}

export default {
  fetch: startServerAndCreateCloudflareWorkersHandler<Env, Context>(server, {
    context: async ({ env, request, ctx }) => {
      return { token: 'secret' };
    },
  }),
};

Additional Bonus

Cloudflare Boilerplate

If you’re looking for an alternative boilerplate, Cloudflare offers an official implementation built with Hono. You can explore it at cloudflare/workers-graphql-server.

Deno Support

This example works with Deno because it follows Web API standards and supports fetch. With Deno’s built-in Deno.serve, you can run it with minimal changes.

Important Notes:

  • If using Node.js packages, add an import map to deno.json or use the npm: prefix.
# instead of:
import { ApolloServer } from '@apollo/server';

# we use:
import { ApolloServer } from 'npm:@apollo/server';
  • For more control, modify the setup:
type Env = {};
type Context = { token: string };

const handler = startServerAndCreateCloudflareWorkersHandler<Env, Context>(server, {
  context: async () => ({ token: 'secret' }),
});

Deno.serve({ port: 3000 }, (req) => handler(req, {} satisfies Env, { token: '' } satisfies Context));