graphql-shared-ws
v1.0.2
Published
graphql-ws clients sharing a single web socket connection across browsing contexts (such as tabs, windows, or iframes).
Downloads
1,081
Maintainers
Readme
✨ Features
- 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.
📦 Installation
npm install graphql-shared-ws💻 Usage
🚀 Initialize and subscribe
import { 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,
}
)📦 Migration from graphql-ws library
🚀 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.
🔌 API Reference
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.
⚡ Optimizations
📦 SharedWorker size
- 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.
🗂️ Subscription indexing
- 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.
👥 Community & Support
💬 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.
