Skip to Content
UsageUsing Subscriptions

Using Subscriptions

Gqlts has a built-in subscription client that returns an observable, Additional options are passed down to graphql-ws


import { createClient, everything } from './generated' const client = createClient({ url: 'ws://my-url', headers: { Authorization: 'Bearer ...', }, }) const { unsubscribe } = await client .subscription({ user: { ...everything, }, }) .subscribe({ next: (x) => console.log('next', x), 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

In browsers, graphql-ws can use the global WebSocket. In Node or Bun, use the runtime global if one exists, or pass a WebSocket implementation explicitly.

const client = createClient({ url: 'http://localhost:4000/graphql', webSocketImpl: WebSocket, })

For Node versions or runtimes without a global WebSocket, install ws and pass it:

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

Next.js and SSR

Avoid reading window.WebSocket during module initialization. In SSR, only create or subscribe to the websocket client in browser-only 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.

Last updated on