GraphQL over HTTP Protocol Implementation

1.22.4 · active · verified Sun Apr 19

graphql-http is a robust, zero-dependency JavaScript library that provides a spec-compliant implementation of GraphQL over HTTP for both server and client applications. It is currently at version 1.22.4 and receives regular updates, primarily focusing on bug fixes, performance improvements, and new platform integrations, as evidenced by its recent release cadence. The library distinguishes itself through its strict adherence to the official GraphQL over HTTP specification, offering a pluggable architecture that integrates seamlessly with various Node.js HTTP frameworks like `http`, `http2`, `Express`, `Fastify`, `Koa`, and serverless environments. It also includes an audit suite to verify compliance, making it a reliable choice for building standard-compliant GraphQL endpoints without the overhead of larger frameworks like Apollo Server, or for creating custom GraphQL clients.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic GraphQL server using `graphql-http` with Express, defining a simple schema, and demonstrating how to integrate the `createHandler` along with essential body parsing middleware and an optional request context.

import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';
import express from 'express';
import { createHandler } from 'graphql-http/lib/use/express';

// Define a simple GraphQL schema for demonstration
const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      hello: {
        type: GraphQLString,
        resolve: () => 'world',
      },
      echo: {
        type: GraphQLString,
        args: { message: { type: GraphQLString } },
        resolve: (source, { message }) => `You said: ${message}`,
      },
    },
  }),
});

const app = express();

// Middleware to parse JSON bodies for GraphQL POST requests
app.use(express.json());

// Create an Express-specific GraphQL over HTTP handler
app.all('/graphql', createHandler({
  schema,
  // Optional: Add a context factory to pass request-specific data to resolvers
  context: (req) => ({
    userId: req.headers['x-user-id'] ?? 'guest',
    // Any other request-scoped data
  }),
}));

const port = process.env.PORT ? parseInt(process.env.PORT) : 4000;
app.listen(port, () => {
  console.log(`GraphQL server running at http://localhost:${port}/graphql`);
  console.log(`
To test, run in another terminal:
  curl -X POST -H "Content-Type: application/json" \
    --data '{"query":"query { hello }"}' \
    http://localhost:${port}/graphql
`);
  console.log(`  curl -X POST -H "Content-Type: application/json" \
    --data '{"query":"query { echo(message: \"Hello GraphQL\") }"}' \
    http://localhost:${port}/graphql
`);
});

view raw JSON →