Share one GraphQL WebSocket connection across all browsing contexts, such as browser tabs, windows, and iframes.
It indexes GraphQL subscriptions by payload to avoid duplicate subscription channels across browsing contexts.
It is built on top of graphql-shared-ws, a drop-in wrapper around graphql-ws, and uses a SharedWorker to coordinate a single underlying WebSocket connection across browser tabs, windows, and iframes.
💡 If you are using TanStack Query (React Query) or graphql-ws, refer to the official graphql-shared-ws documentation.
npm install apollo-shared-ws
pnpm add apollo-shared-ws
pnpm add apollo-shared-ws --filter="./packages/my-workspace"
pnpm add apollo-shared-ws -w
yarn add apollo-shared-ws
yarn workspace <workspace-name> add apollo-shared-ws
yarn add -W apollo-shared-ws
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { ApolloClient, ApolloLink, InMemoryCache } from '@apollo/client'
import { setupRestartSubscription } from 'apollo-shared-ws'
import { createSharedClient } from 'graphql-shared-ws'
import { authLink } from './util/authLink'
const wsLink = new GraphQLWsLink(
// use 'createSharedClient'.
createSharedClient({
url: 'wss://localhost:443/api/graphql',
connectionParams: {
headers: {
authorization: 'auth-token-1234',
},
},
})
)
const apolloClient =
// use setupRestartSubscription to enable subscription restarts.
// wrap ApolloClient with setupRestartSubscription(...)
setupRestartSubscription(
new ApolloClient({
link: ApolloLink.from([authLink, wsLink]),
cache: new InMemoryCache(),
})
)
If you are using ApolloLink.split, refer to this documentation.
It uses SharedWorkers to host a single shared WebSocket connection and indexes subscription payloads to avoid duplicate GraphQL subscription channels across browsing contexts.
🌐 Support for SharedWorkers depends on the browser and may be restricted by privacy settings or unsupported environments.
This package includes a lightweight migration helper for Apollo Client projects.
Run the following commands sequentially:
npm i --save-dev ts-morph
npx gql-shr-ws-link-migrate --help
npx gql-shr-ws-link-migrate
This automation:
webSocketImpl: SharedWebSocket to createClient(...) callssetupRestartSubscription(...)This is helpful for simple migration cases, but it has limitations. For example, Subscription.restart is not automatically migrated when ApolloLink.split is used.
💬 Have an idea? Suggest new features in GitHub Discussions.
🚀 Want to support the project? Visit this link.
💼 Need custom work or consultation? I am available for hire! Reach out via email.