Simple, pluggable, zero-dependency, GraphQL over HTTP spec compliant server, client and audit suite.
Simple, pluggable, zero-dependency, GraphQL over HTTP spec compliant server, client and audit suite.
yarn add graphql-httpimport { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';
/**
* Construct a GraphQL schema and define the necessary resolvers.
*
* type Query {
* hello: String
* }
*/
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world',
},
},
}),
});httpimport http from 'http';
import { createHandler } from 'graphql-http/lib/use/http';
import { schema } from './previous-step';
// Create the GraphQL over HTTP Node request handler
const handler = createHandler({ schema });
// Create a HTTP server using the listener on `/graphql`
const server = http.createServer((req, res) => {
if (req.url.startsWith('/graphql')) {
handler(req, res);
} else {
res.writeHead(404).end();
}
});
server.listen(4000);
console.log('Listening to port 4000');http2Browsers might complain about self-signed SSL/TLS certificates. Help can be found on StackOverflow.
$ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
-keyout localhost-privkey.pem -out localhost-cert.pem…expressimport express from 'express'; // yarn add express
import { createHandler } from 'graphql-http/lib/use/express';
import { schema } from './previous-step';
// Create an express instance serving all methods on `/graphql`
// where the GraphQL over HTTP express request handler is
const app = express();
app.all('/graphql', createHandler({ schema }));
app.listen({ port: 4000 });
console.log('Listening to port 4000');fastifyimport Fastify from 'fastify'; // yarn add fastify
import { createHandler } from 'graphql-http/lib/use/fastify';
import { schema } from './previous-step';
// Create a fastify instance serving all methods on `/graphql`
// where the GraphQL over HTTP fastify request handler is
const fastify = Fastify();
fastify.all('/graphql', createHandler({ schema }));
fastify.listen({ port: 4000 });
console.log('Listening to port 4000');Koaimport Koa from 'koa'; // yarn add koa
import mount from 'koa-mount'; // yarn add koa-mount
import { createHandler } from 'graphql-http/lib/use/koa';
import { schema } from './previous-step';
const app = new Koa();
app.use(mount('/graphql', createHandler({ schema })));
app.listen({ port: 4000 });
console.log('Listening to port 4000');uWebSockets.jsimport uWS from 'uWebSockets.js'; // yarn add uWebSockets.js@uNetworking/uWebSockets.js#
import { createHandler } from 'graphql-http/lib/use/uWebSockets';
import { schema } from './previous-step';
uWS
.App()
.any('/graphql', createHandler({ schema }))
.listen(4000, () => {
console.log('Listening to port 4000');
});Deno…Bunimport { createHandler } from 'graphql-http/lib/use/fetch'; // bun install graphql-http
import { schema } from './previous-step';
// Create the GraphQL over HTTP native fetch handler
const handler = createHandler({ schema });
// Start serving on `/graphql` using the handler
export default {
port: 4000, // Listening to port 4000
fetch(req) {
const [path, _search] = req.url.split('?');
if (path.endsWith('/graphql')) {
return handler(req);
} else {
return new Response(null, { status: 404 });
}
},
};Netlify Functionsimport { createHandler } from 'graphql-http/lib/use/@netlify/functions'; // yarn add @netlify/functions
import { schema } from './previous-step';
// Create the GraphQL over HTTP native fetch handler
export const handler = createHandler({ schema });import { createClient } from 'graphql-http';
const client = createClient({
url: 'http://localhost:4000/graphql',
});
(async () => {
let cancel = () => {
/* abort the request if it is in-flight */
};
const result = await new Promise((resolve, reject) => {
let result;
cancel = client.subscribe(
{
query: '{ hello }',
},
{
next: (data) => (result = data),
error: reject,
complete: () => resolve(result),
},
);
});
expect(result).toEqual({ hello: 'world' });
})();Thanks to ruru, serving GraphiQL is as easy as running:
npx ruru -SP -p 4001 -e http://localhost:4000/graphqlOpen http://localhost:4001 in the browser to use it.
Client usage with Promise
…Client usage with Observable
…Client usage with Relay
…Client usage with Apollo
…Client usage with request retries
…Client usage in browser
GraphQL over HTTP
Client usage in Node
const fetch = require('node-fetch'); // yarn add node-fetch
const { AbortController } = require('node-abort-controller'); // (node
Client usage in Deno
```js
import { createClient } from 'https://esm.sh/graphql-http';
const client = createClient({
url: 'http://deno.earth:4000/graphql',
});
// consider other recipes for usage inspirationClient usage in Bun
import { createClient } from 'graphql-http'; // bun install graphql-http
const client = createClient({
url: 'http://bun.bread:4000/graphql',
});
// consider other recipes for usage inspirationServer handler migration from express-graphql
import express from 'express';
import { schema } from './my-graphql-schema';
-import { graphqlHTTP } from 'express-graphql';
+import { createHandler } from 'graphql-http/lib/use/express';
const app = express();
app.use(
'/graphql',
- graphqlHTTP({ schema }),
+ createHandler({ schema }),
);
app.listen(4000);Server handler usage with authentication
Authenticate the user within graphql-http during GraphQL execution context assembly. This is a approach is less safe compared to early authentication (see early authentication in Node) because some GraphQL preparations or operations are executed even if the user is not unauthorized.
import { createHandler } from 'graphql-http';
import {
schema,
getUserFromCookies,
getUserFromAuthorizationHeader,
} from './my-graphql';
const handler = createHandler({
schema,
context: async (req) => {
// process token, authenticate user and attach it to your graphql context
const userId = await getUserFromCookies(req.headers.cookie);
// or
const userId = await getUserFromAuthorizationHeader(
req.headers.authorization,
);
// respond with 401 if the user was not authenticated
if (!userId) {
return [null, { status: 401, statusText: 'Unauthorized' }];
}
// otherwise attach the user to the graphql context
return { userId };
},
});Server handler usage with custom context value
import { createHandler } from 'graphql-http';
import { schema, getDynamicContext } from './my-graphql';
const handler = createHandler({
schema,
context: async (req, args) => {
return getDynamicContext(req, args);
},
// or static context by supplying the value directly
});Server handler usage with custom execution arguments
import { parse } from 'graphql';
import { createHandler } from 'graphql-http';
import { getSchemaForRequest, myValidationRules } from './my-graphql';
const handler = createHandler({
onSubscribe: async (req, params) => {
const schema = await getSchemaForRequest(req);
const args = {
schema,
operationName: params.operationName,
document: parse(params.query),
variableValues: params.variables,
};
return args;
},
});Server handler usage in Node with early authentication (recommended)
Authenticate the user early, before reaching graphql-http. This is the recommended approach because no GraphQL preparations or operations are executed if the user is not authorized.
import { createHandler } from 'graphql-http';
import {
schema,
getUserFromCookies,
getUserFromAuthorizationHeader,
} from './my-graphql';
const handler = createHandler({
schema,
context: async (req) => {
// user is authenticated early (see below), simply attach it to the graphql context
return { userId: req.raw.userId };
},
});
const server = http.createServer(async (req, res) => {
if (!req.url.startsWith('/graphql')) {
return res.writeHead(404).end();
}
try {
// process token, authenticate user and attach it to the request
req.userId = await getUserFromCookies(req.headers.cookie);
// or
req.userId = await getUserFromAuthorizationHeader(
req.headers.authorization,
);
// respond with 401 if the user was not authenticated
if (!req.userId) {
return res.writeHead(401, 'Unauthorized').end();
}
const [body, init] = await handler({
url: req.url,
method: req.method,
headers: req.headers,
body: () =>
new Promise((resolve) => {
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => resolve(body));
}),
raw: req,
});
res.writeHead(init.status, init.statusText, init.headers).end(body);
} catch (err) {
res.writeHead(500).end(err.message);
}
});
server.listen(4000);
console.log('Listening to port 4000');Server handler usage with graphql-upload and http
import http from 'http';
import { createHandler } from 'graphql-http/lib/use/http';
import processRequest from 'graphql-upload/processRequest.mjs'; // yarn add graphql-upload
import { schema } from './my-graphql';
const handler = createHandler({
schema,
async parseRequestParams(req) {
const params = await processRequest(req.raw, req.context.res);
if (Array.isArray(params)) {
throw new Error('Batching is not supported');
}
return {
...params,
// variables must be an object as per the GraphQL over HTTP spec
variables: Object(params.variables),
};
},
});
const server = http.createServer((req, res) => {
if (req.url.startsWith('/graphql')) {
handler(req, res);
} else {
res.writeHead(404).end();
}
});
server.listen(4000);
console.log('Listening to port 4000');Server handler usage with graphql-upload and express
import express from 'express'; // yarn add express
import { createHandler } from 'graphql-http/lib/use/express';
import processRequest from 'graphql-upload/processRequest.mjs'; // yarn add graphql-upload
import { schema } from './my-graphql';
const app = express();
app.all(
'/graphql',
createHandler({
schema,
async parseRequestParams(req) {
const params = await processRequest(req.raw, req.context.res);
if (Array.isArray(params)) {
throw new Error('Batching is not supported');
}
return {
...params,
// variables must be an object as per the GraphQL over HTTP spec
variables: Object(params.variables),
};
},
}),
);
app.listen({ port: 4000 });
console.log('Listening to port 4000');Audit for servers usage in Jest environment
import { fetch } from '@whatwg-node/fetch';
import { serverAudits } from 'graphql-http';
forNo open issues yet, or sync has not completed.