- This package is moved to
@as-integrations/cloudlare-workers
- Please migrate to use
@as-integrations/cloudlare-workers
instead
This is Apollo Server v4 integration for Cloudflare Workers. It provides:
kv-cache.ts
-KVCache
: Cache on Cloudflare KV storagestart-server.ts
-startServerAndCreateCloudflareHandler
: Handle incoming request and return an instance ofResponse
with-cors
-withCors
: Add configure for CORS middleware
- Source: https://github.com/kimyvgy/worker-apollo-server-template
- Live demo: https://worker-apollo-server.webee-asia.workers.dev/
npm install apollo-server-integration-cloudflare-workers
- Initialize an Apollo Server instance:
import { ApolloServer } from '@apollo/server';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
const server = new ApolloServer<ContextValue>({
typeDefs,
resolvers,
introspection: true,
plugins: [
ApolloServerPluginLandingPageLocalDefault({ footer: false }),
// ApolloServerPluginLandingPageProductionDefault({
// graphRef: 'my-graph-id@my-graph-variant',
// footer: false,
// })
],
});
- Call
startServerAndCreateCloudflareHandler(server, options)
:
import type { GraphQLRequestHandler, CorsOptions } from 'apollo-server-integration-cloudflare-workers';
import { startServerAndCreateCloudflareHandler, KVCache } from 'apollo-server-integration-cloudflare-workers';
const handleGraphQLRequest: GraphQLRequestHandler = startServerAndCreateCloudflareHandler(server, {
context: async ({ request }) => {
const cache = options.kvCache ? new KVCache() : server.cache;
const dataSources: ApolloDataSources = {
pokemonAPI: new PokemonAPI({ cache }),
};
return { dataSources };
},
// Enable CORS headers on GraphQL requests
// Set to `true` for defaults or pass an object to configure each header
// cors: {
// allowCredentials: 'true',
// allowHeaders: 'Content-type',
// allowOrigin: '*',
// allowMethods: 'GET, POST, PUT',
// },
cors: true,
});
addEventListener((e) => handleGraphQLRequest(e.request));