Koa GraphQL Middleware

raw JSON →
0.12.0 verified Thu Apr 23 auth: no javascript maintenance

koa-graphql is a middleware designed for Koa.js applications, enabling the quick and efficient setup of a GraphQL HTTP server. It serves as a direct port of the well-established `express-graphql` package, bringing its comprehensive features for handling GraphQL queries, mutations, and subscriptions to the Koa ecosystem. The current stable version, 0.12.0, was released in November 2021. While the project doesn't have a rapid release cadence, it provides a robust and stable foundation for integrating GraphQL into Koa-based APIs. Its key differentiators include seamless integration with Koa's middleware paradigm, out-of-the-box GraphiQL IDE support (including subscription capabilities), and extensive options for custom schema execution and error formatting. It supports both `graphql` v14 and v15 as peer dependencies, ensuring compatibility with a range of GraphQL projects and is maintained by the GraphQL community.

error TypeError: (0 , koa_graphql_1.default) is not a function
cause Attempting to use `graphqlHTTP` as a default import/require after version 0.12.0, where it became a named export.
fix
Change your import statement to use named destructuring: import { graphqlHTTP } from 'koa-graphql'; for ESM or const { graphqlHTTP } = require('koa-graphql'); for CommonJS.
error Error: Cannot find module 'graphql' from '.../node_modules/koa-graphql'
cause The `graphql` package is a peer dependency and must be installed explicitly in your project.
fix
Install the graphql package: npm install graphql (or yarn add graphql). Ensure the installed version is compatible with koa-graphql (e.g., ^14.7.0 || ^15.3.0).
error TypeError: app.use is not a function or app.use is not a GeneratorFunction
cause This error can occur when using `koa-graphql` with Koa 1.x without converting the middleware, as Koa 1.x uses generator functions while Koa 2.x+ uses async/await.
fix
Install koa-convert and wrap the graphqlHTTP middleware: app.use(mount('/graphql', convert.back(graphqlHTTP(...))));
error GraphiQL: Subscription client not found or not initialized. Check console for error messages.
cause The GraphiQL interface is configured for subscriptions, but the necessary WebSocket server or client (e.g., `subscriptions-transport-ws` or `graphql-ws`) is not correctly set up or initialized.
fix
Ensure you have the correct subscription client installed (subscriptions-transport-ws or graphql-ws), an http server listening, and a SubscriptionServer instance configured as shown in the package's documentation for subscription support.
breaking The `graphqlHTTP` function changed from a default export to a named export. Code using `import graphqlHTTP from 'koa-graphql'` or `const graphqlHTTP = require('koa-graphql')` will break.
fix Update imports to use named destructuring: `import { graphqlHTTP } from 'koa-graphql';` or `const { graphqlHTTP } = require('koa-graphql');`
breaking Flowtype support was entirely removed, and the project converted all remaining files to TypeScript. This affects users relying on Flow for type checking.
fix Migrate type checking to TypeScript or use an older version of `koa-graphql` if Flowtype is critical for your project.
gotcha `koa-graphql` has `graphql` as a peer dependency. Your project must explicitly install a compatible version of `graphql`.
fix Ensure `graphql` is installed with a compatible version, e.g., `npm install graphql@'^14.7.0 || ^15.3.0'`.
gotcha For Koa 1 applications, `koa-graphql` middleware needs to be converted using `koa-convert` due to API changes between Koa 1 and Koa 2+.
fix Wrap the `graphqlHTTP` middleware with `convert.back()`: `app.use(mount('/graphql', convert.back(graphqlHTTP(...))));`
gotcha Enabling GraphQL subscriptions in GraphiQL requires additional setup, including creating an `http` server and a `SubscriptionServer` instance with `subscriptions-transport-ws` or `graphql-ws`.
fix Follow the 'Setup with Subscription Support' example in the documentation to correctly initialize the WebSocket server and pass the `subscriptionEndpoint` to GraphiQL options.
npm install koa-graphql
yarn add koa-graphql
pnpm add koa-graphql

This quickstart sets up a basic Koa server with a GraphQL endpoint using `koa-graphql`. It defines a simple schema with 'hello', 'echo', and 'add' operations, enables the GraphiQL IDE for interactive testing, and listens on port 4000.

import Koa from 'koa';
import mount from 'koa-mount';
import { graphqlHTTP } from 'koa-graphql';
import { buildSchema } from 'graphql';

// Define your GraphQL Schema using GraphQL Schema Language
const schema = buildSchema(`
  type Query {
    hello: String
    echo(message: String!): String
  }

  type Mutation {
    add(a: Int!, b: Int!): Int
  }
`);

// Define a root resolver to handle queries and mutations
const rootValue = {
  hello: () => 'Hello from koa-graphql!',
  echo: ({ message }: { message: string }) => message,
  add: ({ a, b }: { a: number; b: number }) => a + b,
};

const app = new Koa();

// Mount the GraphQL middleware
app.use(
  mount(
    '/graphql',
    graphqlHTTP({
      schema: schema,
      rootValue: rootValue, // Provide the root resolver
      graphiql: true, // Enable the GraphiQL IDE for easy testing
    }),
  ),
);

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`GraphQL server running on http://localhost:${PORT}/graphql`);
  console.log(`Access GraphiQL IDE at http://localhost:${PORT}/graphql`);
});