WebSocket Link

Execute subscriptions (or other operations) over WebSocket with the subscriptions-transport-ws library


⚠️ We no longer recommend using WebSocketLink or the subscriptions-transport-ws library, because the library is not actively maintained. To execute subscriptions, We instead recommend using the newer graphql-ws library with the accompanying GraphQLWsLink.

Whichever library you use, make sure you use the same library in your server and any clients you support. For more information, see Choosing a subscription library.

We recommend reading Apollo Link overview before learning about individual links.

The WebSocketLink is a terminating link that's used most commonly with GraphQL subscriptions (which usually communicate over WebSocket), although you can send queries and mutations over WebSocket as well.

WebSocketLink requires the subscriptions-transport-ws library. Install it in your project like so:

shell
1npm install subscriptions-transport-ws

Constructor

JavaScript
1import { WebSocketLink } from "@apollo/client/link/ws";
2import { SubscriptionClient } from "subscriptions-transport-ws";
3
4const link = new WebSocketLink(
5  new SubscriptionClient("ws://localhost:4000/graphql", {
6    reconnect: true
7  })
8);

Options

The WebSocketLink constructor takes either a SubscriptionClient object or an options object with the following fields. (These options are passed directly to the SubscriptionClient constructor.)

Name /
Type
Description
uri

String

Required. The URL of the WebSocket endpoint to connect to (e.g., ws://localhost:4000/subscriptions).

options

Object

Options for configuring the WebSocket connection.

See supported options

webSocketImpl

Object

A W3C-compliant WebSocket implementation to use. Provide this if your environment does not provide native WebSocket support (for example, in Node.js).

Usage

See Subscriptions.

Feedback

Edit on GitHub

Forums