GraphQL over WebSocket clients sharing a single socket across browsing contexts such as browser tabs, windows, and iframes while avoiding duplicate subscription channels
- Share a single WebSocket across browser tabs, windows, and iframes.
- GraphQL subscriptions are indexed by their payloads, preventing duplicate requests and responses across browsing contexts.
- A swap-in graphql-ws wrapper with an identical API.
npm install graphql-shared-wsimport { createSharedClient } from 'graphql-shared-ws'
// create a client.
const sharedClient = createSharedClient({
url: 'wss://example.com/api/graphql',
})
// make a GraphQL subscription
sharedClient.subscribe(
{
query: `
subscription listenToMessages {
messageBroadcasted
}
`,
},
{
next: (n) => {
console.log(`Last broadcasted message =`, n.data.messageBroadcasted)
},
complete: () => {
console.log('subscription closed.')
},
error: console.error,
}
)🚀 You only need to update the import statements, unless you are using a custom WebSocket implementation.
// Before migration
import { createClient } from 'graphql-ws'
// After migration
import { createSharedClient as createClient } from 'graphql-shared-ws'If you are using custom WebSocket implementation, refer to this custom WebSocket guide.
This library implements the exact same API as graphql-ws, except for the webSocketImpl field. For complete usage guides, configuration options, and type definitions, please refer to the official graphql-ws documentation. If you are using a custom WebSocket implementation, refer to the custom WebSocket guide.
- The SharedWorker script is 📦 bundled, 🌳 tree-shaken, 📉 minified, 🗜️ gzipped, 🔠 base64 encoded and 📥 inlined within this library.
- All the SharedWorker registration logic (including decoding and decompression) are automatically handled by and within this library itself.
- The base64-encoded SharedWorker script is only 6 KB.
- GraphQL subscriptions are indexed by their payloads across browsing contexts (across browser tabs, windows, iframes, etc...).
- When a user opens multiple tabs, network load remains identical to having just a single tab open.
- Making duplicate subscriptions across different UI components will not trigger extra network requests.
-
💬 Have an idea? Suggest new features in GitHub Discussions.
-
🚀 Support me or my projects through donations.
-
💼 Need custom work or consultation? I am available for hire! Reach out via email.