Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
createClient
✓ import { createClient } from 'graphql-ws';
✗ const createClient = require('graphql-ws').createClient;
Primarily for client-side usage to connect to a GraphQL WebSocket server. For Node.js client environments, you might need to specify `webSocketImpl: WebSocket` if `WebSocket` is not globally available.
useServer
✓ import { useServer } from 'graphql-ws/lib/use/ws';
✗ import { useServer } from 'graphql-ws/use/ws'; // Incorrect path pre-v6
Used for integrating graphql-ws with the `ws` WebSocket server library. In v6 and later, the import path for adapters changed from `/lib/use/` to `/use/`.
makeHandler
✓ import { makeHandler } from 'graphql-ws/lib/use/@fastify/websocket';
✗ import { makeHandler } from 'graphql-ws/use/@fastify/websocket'; // Incorrect path pre-v6
Used for integrating graphql-ws with Fastify and its `@fastify/websocket` plugin. Similar to `useServer`, the import path structure changed in v6.
Demonstrates setting up a basic GraphQL server with subscriptions using `ws` and `graphql-ws`, along with a client that connects and subscribes to a real-time greeting stream. Requires `ws`, `graphql-subscriptions`, `@graphql-tools/schema`, and `graphql` as peer dependencies.
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { PubSub } from 'graphql-subscriptions';
import { createClient } from 'graphql-ws';
// --- Server Setup ---
const pubsub = new PubSub();
const HELLO_EVENT = 'hello_event';
const typeDefs = `
type Query {
hello: String
}
type Subscription {
greetings: String
}
`;
const resolvers = {
Query: {
hello: () => 'world',
},
Subscription: {
greetings: {
subscribe: () => pubsub.asyncIterator(HELLO_EVENT),
resolve: (payload) => payload.greetings,
},
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = createServer((req, res) => {
res.writeHead(404);
res.end();
});
const wsServer = new WebSocketServer({
server,
path: '/graphql',
});
useServer(
{
schema,
context: async (ctx) => {
// Example: access the websocket instance through ctx.extra.socket in v6+
// const socket = ctx.extra.socket;
return { currentUser: 'someUser' };
}
},
wsServer
);
server.listen(4000, () => {
console.log('GraphQL server running on http://localhost:4000/graphql');
console.log('WebSocket server running on ws://localhost:4000/graphql');
let count = 0;
setInterval(() => {
pubsub.publish(HELLO_EVENT, { greetings: `Hello from server! (${count++})` });
}, 2000);
});
// --- Client Setup ---
const client = createClient({
url: 'ws://localhost:4000/graphql',
webSocketImpl: WebSocket, // Required for Node.js environments; in browser, it's global
on: {
connected: () => console.log('Client connected to server.'),
closed: (event) => console.log(`Client disconnected: ${event.code} - ${event.reason}`),
error: (err) => console.error('Client error:', err),
},
});
async function subscribeToGreetings() {
const onNext = ({ data }) => {
console.log('Received greeting:', data.greetings);
};
const onError = (err) => {
console.error('Subscription error:', err);
};
const onComplete = () => {
console.log('Subscription complete.');
};
const unsubscribe = client.subscribe(
{
query: `subscription { greetings }`,
},
{
next: onNext,
error: onError,
complete: onComplete,
}
);
setTimeout(() => {
unsubscribe();
console.log('Unsubscribed from greetings.');
client.dispose(); // Close the WebSocket connection
server.close(); // Close the HTTP/WebSocket server
}, 10000);
}
// Run 'npm install ws graphql-subscriptions @graphql-tools/schema graphql' first
subscribeToGreetings().catch(console.error);
Errors
Common errors & fixes
WebSocket connection to 'ws://localhost:4000/graphql' failed: WebSocket opening handshake timed out
The WebSocket server is not running, not listening on the specified port/path, or a firewall is blocking the connection.
fixEnsure your GraphQL WebSocket server is actively running and accessible at `ws://localhost:4000/graphql`. Check server logs for errors and firewall configurations.
WebSocket connection to 'ws://localhost:4000/graphql' failed: Error during WebSocket handshake: Unexpected response code: 400
The server received a WebSocket connection request but rejected it, often due to an incorrect subprotocol or an invalid connection initialization payload from the client. This can also occur if the HTTP server is serving the same path as the WebSocket server without proper upgrade handling.
fixVerify that your client is using the correct subprotocol (`graphql-ws`) and sending a valid `ConnectionInit` message. On the server, ensure proper WebSocket upgrade logic is in place for the specified path, and check `onConnect` hooks for rejection conditions.
Cannot find module 'graphql-ws/lib/use/ws' or its corresponding type declarations.
This error typically occurs in v6+ when an old import path for adapters is used. The `/lib` segment was removed from the import paths.
fixUpdate the import path to `import { useServer } from 'graphql-ws/use/ws';` (remove `/lib`). TypeError: (0 , graphql_ws__WEBPACK_IMPORTED_MODULE_0__.createClient) is not a function
This usually indicates a CommonJS `require()` style import is being used in an ESM context, or vice-versa, leading to incorrect module resolution, especially with `graphql-ws`'s dual package setup.
fixEnsure you are using `import { createClient } from 'graphql-ws';` in ESM contexts. If strictly in CommonJS (though less common for client), use dynamic import or check your bundler/TypeScript configuration for module interop issues. Audit
Dependencies
@fastify/websocketoptionalOptional peer dependency for integrating with Fastify servers for WebSocket handling.
crosswsoptionalOptional peer dependency for integrating with crossws, a universal WebSocket adapter.
graphqlrequiredRequired peer dependency for GraphQL execution, supporting versions ^15.10.1 || ^16.
wsoptionalOptional peer dependency for integrating with the 'ws' WebSocket server (Node.js native WebSocket).