Registry / http-networking / graphql-ws

graphql-ws

JSON →
library0.4.4jsnpmunverified

graphql-ws is a JavaScript/TypeScript library that provides a coherent, zero-dependency, and lazy implementation of the GraphQL over WebSocket Protocol for both server and client applications. The current stable version is 6.0.8, with a development cadence that includes frequent patch releases for bug fixes and minor enhancements. Major versions, like v6, typically introduce targeted breaking changes related to API adjustments or adapter integrations. A crucial differentiator is its strict adherence to the modern GraphQL over WebSocket Protocol, which makes it explicitly incompatible with the older, deprecated `subscriptions-transport-ws` library and its distinct protocol. The library offers flexible integration with various Node.js WebSocket server implementations such as `ws`, Fastify's `@fastify/websocket`, and `crossws`, catering to diverse server environments.

npm install graphql-ws
INSTALL
IMPORT
SIG · GRAPHQL-WS
G
graphql-ws
http-networkingjavascriptv0.4.4
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
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
musl
node 18226 runs
build_error
glibc
node 18226 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);
Debug
Known issues
breakingStarting from v6, for the `@fastify/websocket` adapter, the `connection` property in `ctx.extra` has been renamed to `socket`. This change requires updating any server-side code that accesses the raw WebSocket instance via the context.
fix
If using `@fastify/websocket` adapter, change `ctx.extra.connection` to `ctx.extra.socket` within your `makeHandler` options.
affects: >=6.0.0
breakingThe import paths for adapters like `useServer` (for `ws`) and `makeHandler` (for `@fastify/websocket`) changed from `graphql-ws/lib/use/<adapter>` to `graphql-ws/use/<adapter>` in v6.
fix
Update your import statements to remove the `/lib` segment: `import { useServer } from 'graphql-ws/use/ws';`
affects: >=6.0.0
breakinggraphql-ws is explicitly not compatible with the older, deprecated `subscriptions-transport-ws` library due to different WebSocket subprotocols. Mixing them will lead to connection failures.
fix
Ensure both server and client use `graphql-ws` and adhere to the GraphQL over WebSocket Protocol. Do not attempt to use `subscriptions-transport-ws` with `graphql-ws`.
affects: All versions
breakingMinimum Node.js version supported is 20. Attempts to run on older Node.js versions will result in runtime errors.
fix
Upgrade your Node.js runtime environment to version 20 or higher.
affects: >=6.0.0
gotchaThe `uWebSockets.js` library was removed from `graphql-ws`'s peer dependencies in v6.0.7 because it's no longer on NPM. While it can still be used if installed manually, `npm` might report warnings or issues if not handled carefully.
fix
If you intend to use `graphql-ws` with `uWebSockets.js`, install `uWebSockets.js` manually alongside `graphql-ws`. Otherwise, migrate to a supported peer dependency like `ws`, `@fastify/websocket`, or `crossws`.
affects: >=6.0.7
gotchaThe `onSubscribe`, `onOperation`, `onError`, `onNext`, and `onComplete` hooks in `useServer` no longer receive the full message object, only the ID and the relevant payload part. This simplifies the API and avoids redundant serialization.
fix
Adjust callback signatures for these hooks to expect only `id` and the relevant `payload` portion, rather than the complete `SubscribeMessage` or `ExecutionResult`.
affects: >=6.0.0
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.
fix
Ensure 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.
fix
Verify 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.
fix
Update 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.
fix
Ensure 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.
Upgrade
Version history
0.4.4latest on npm
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).
Agent activity
10 hits · last 30 days
node
8
Resources