Skip to Content
Gqlts

Subscriptions

Generated clients expose subscription when the schema has a subscription root. Subscription calls return observables and use graphql-ws internally.

Subscribe

import { createClient, everything } from './generated'; const client = createClient({ url: 'https://api.example.com/graphql', subscription: { url: 'wss://api.example.com/graphql', }, }); const { unsubscribe } = client .subscription({ userUpdated: { ...everything, }, }) .subscribe({ next: (event) => console.log(event.data?.userUpdated), error: console.error, });

Subscription URL

If subscription.url is omitted, Gqlts derives it from the top-level url by replacing the protocol prefix:

const client = createClient({ url: 'http://localhost:4000/graphql', }); // subscriptions use ws://localhost:4000/graphql

Pass subscription.url when the WebSocket endpoint differs from the HTTP endpoint.

const client = createClient({ url: 'https://api.example.com/graphql', subscription: { url: 'wss://ws.example.com/graphql', }, });

WebSocket implementation

Browsers usually provide a global WebSocket. Node.js and Bun runtimes may also provide one, depending on version and environment. When they do not, pass an implementation explicitly.

import WebSocket from 'ws'; import { createClient } from './generated'; const client = createClient({ url: 'http://localhost:4000/graphql', webSocketImpl: WebSocket, });

SSR and Next.js

Avoid reading window.WebSocket during module initialization. In SSR, create subscriptions only in browser-only code paths or in server runtimes that provide a valid WebSocket implementation.

The runtime validates explicit webSocketImpl values before passing them to graphql-ws, so invalid SSR placeholders are ignored instead of breaking client creation.