Skip to content

Commit 3f32357

Browse files
committed
New GraphQLWsLink for graphql-ws subscriptions library
Apollo Client currently contains `WebSocketLink` in `@apollo/client/link/ws` which uses the `subscriptions-transport-ws` library. That library is no longer actively maintained, and there is an improved fork called `graphql-ws`. The two libraries use different protocols so a different client link is required for `graphql-ws`. (While the WebSocket protocol does allow for subprotocol negotiation, neither server implementation supports this in a practical way.) This PR adds a new link `GraphQLWsLink` in `@apollo/client/link/subscriptions`. Its constructor arguments are the same as the `createClient` function in `graphql-ws` (or it can take a `Client` object returned from that function), and you need to install the optional peer dep `graphql-ws` instead of `subscriptions-transport-ws`. Once you've created the link, it works exactly like the old `WebSocketLink`. This PR changes the main subscriptions doc page to mostly document the new link, with an extra section at the bottom for the old link. The core GraphQLWsLink code is based on MIT-licensed code from the README of the graphql-ws repository. Fixes #8345. Part of apollographql/apollo-server#6058
1 parent 45421dc commit 3f32357

File tree

13 files changed

+330
-37
lines changed

13 files changed

+330
-37
lines changed

config/entryPoints.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const entryPoints = [
1212
{ dirs: ['link', 'persisted-queries'] },
1313
{ dirs: ['link', 'retry'] },
1414
{ dirs: ['link', 'schema'] },
15+
{ dirs: ['link', 'subscriptions'] },
1516
{ dirs: ['link', 'utils'] },
1617
{ dirs: ['link', 'ws'] },
1718
{ dirs: ['react'] },

docs/gatsby-config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ module.exports = {
109109
'api/link/apollo-link-rest',
110110
'api/link/apollo-link-retry',
111111
'api/link/apollo-link-schema',
112+
'api/link/apollo-link-subscriptions',
112113
'api/link/apollo-link-ws',
113114
'api/link/community-links'
114115
],
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
title: Subscriptions Link
3+
sidebar_title: Subscriptions (newer protocol)
4+
description: Execute subscriptions (or other GraphQL operations) over WebSocket with the `graphql-ws` library
5+
api_reference: true
6+
---
7+
8+
> We recommend reading [Apollo Link overview](./introduction/) before learning about individual links.
9+
10+
The `GraphQLWsLink` is a [terminating link](./introduction/#the-terminating-link) that's used most commonly with GraphQL [subscriptions](../../data/subscriptions/) (which usually communicate over WebSocket), although you can send queries and mutations over WebSocket as well.
11+
12+
`GraphQLWsLink` requires the [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) library. Install it in your project like so:
13+
14+
```shell
15+
npm install graphql-ws
16+
```
17+
18+
> **Note**: This link works with the newer `graphql-ws` library. If your server uses the older `subscriptions-transport-ws`, you should use the [`WebSocketLink` link from `@apollo/client/link/ws](./apollo-link-ws) instead.
19+
20+
## Constructor
21+
22+
```js
23+
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
24+
25+
const link = new GraphQLWsLink({
26+
url: "ws://localhost:3000/subscriptions",
27+
});
28+
```
29+
30+
### Options
31+
32+
The `GraphQLWsLink` constructor takes a single object. This can either be a `Client` returned from the `graphql-ws` `createClient` function, or an options object that will be passed directly to the `createClient` function.
33+
34+
If you are passing an options object, the one required option is `url`, which is the URL (typically starting with `ws://` or `wss://`, which are the equivalents of `http://` and `https://` respectively) to your WebSocket server.
35+
36+
Full documentation of supported options can be found in [the `graphql-ws` docs for `ClientOptions`](https://github.com/enisdenjo/graphql-ws/blob/master/docs/interfaces/client.ClientOptions.md).
37+
38+
<table class="field-table">
39+
40+
## Usage
41+
42+
See [Subscriptions](../../data/subscriptions/).

docs/source/api/link/apollo-link-ws.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: WebSocket Link
3-
sidebar_title: WebSocket
4-
description: Execute subscriptions (or other GraphQL operations) over WebSocket
3+
sidebar_title: WebSocket (newer protocol)
4+
description: Execute subscriptions (or other GraphQL operations) over WebSocket with the `subscriptions-transport-ws` library
55
api_reference: true
66
---
77

@@ -15,6 +15,8 @@ The `WebSocketLink` is a [terminating link](./introduction/#the-terminating-link
1515
npm install subscriptions-transport-ws
1616
```
1717

18+
> **Note**: The `subscriptions-transport-ws` library is not actively maintained. We recommend the use of the `graphql-ws` library instead. These libraries layer different protocols on top of WebSockets, so you do need to ensure you are using the same library in your server and any clients that you support. To use `graphql-ws` from Apollo Client, use the [`GraphQLWsLink` link from `@apollo/client/link/subscriptions](./apollo-link-subscriptions) instead.
19+
1820
## Constructor
1921

2022
```js
@@ -23,8 +25,8 @@ import { WebSocketLink } from "@apollo/client/link/ws";
2325
const link = new WebSocketLink({
2426
uri: "ws://localhost:3000/subscriptions",
2527
options: {
26-
reconnect: true
27-
}
28+
reconnect: true,
29+
},
2830
});
2931
```
3032

docs/source/api/react/hoc.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ data.fetchMore({
471471

472472
### `data.subscribeToMore(options)`
473473

474-
This function will set up a subscription, triggering updates whenever the server sends a subscription publication. This requires subscriptions to be set up on the server to properly work. Check out the [subscriptions guide](../../data/subscriptions/) and the [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws) and [graphql-subscriptions](https://github.com/apollographql/graphql-subscriptions) for more information on getting this set up.
474+
This function will set up a subscription, triggering updates whenever the server sends a subscription publication. This requires subscriptions to be set up on the server to properly work. Check out the [subscriptions guide](../../data/subscriptions/) for more information on getting this set up.
475475

476476
This function returns an `unsubscribe` function handler which can be used to unsubscribe later.
477477

docs/source/data/subscriptions.mdx

Lines changed: 58 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ You _should_ use subscriptions for the following:
2222

2323
* **Low-latency, real-time updates**. For example, a chat application's client wants to receive new messages as soon as they're available.
2424

25+
## Choice of subscription protocol
26+
27+
The GraphQL spec does not define a specific way to send subscription requests. The first popular JavaScript library to implement subscriptions over WebSocket is called `subscriptions-transport-ws`. This library is no longer actively maintained; its successor is a library called `graphql-ws`. The two packages _do not use the same protocol_, so you need to make sure that your server and clients all use the same library.
28+
29+
Apollo Client supports both `graphql-ws` and `subscriptions-transport-ws`. We recommend you use the newer library `graphql-ws` and this page shows how to use it. If you need to use `subscriptions-transport-ws` because your server still uses that protocol, the differences are described [at the bottom of this page](#the-older-subscriptions-transport-ws-library).
30+
31+
> **Note**: When looking at the source code of an implementation to determine which protocol it supports, you will find that the libraries uses different strings as the "WebSocket subprotocol". Confusingly, `subscriptions-transport-ws` uses the `graphql-ws` subprotocol and `graphql-ws` uses the `graphql-transport-ws` subprotocol! In these docs, when we say "`graphql-ws`" we are referring to the _library_ `graphql-ws`, not the subprotocol `graphql-ws`, which is the other project.
32+
2533
## Defining a subscription
2634

2735
You define a subscription on both the server side and the client side, just like you do for queries and mutations.
@@ -70,57 +78,51 @@ Whenever your GraphQL server _does_ push data to a subscribing client, that data
7078

7179
## Setting up the transport
7280

73-
Because subscriptions usually maintain a persistent connection, they shouldn't use the default HTTP transport that Apollo Client uses for queries and mutations. Instead, Apollo Client subscriptions most commonly communicate over WebSocket, via the community-maintained [`subscriptions-transport-ws`](https://github.com/apollographql/subscriptions-transport-ws) library.
81+
Because subscriptions usually maintain a persistent connection, they shouldn't use the default HTTP transport that Apollo Client uses for queries and mutations. Instead, Apollo Client subscriptions most commonly communicate over WebSocket, via the [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) library. (As mentioned [above](#choice-of-subscription-protocol), some servers use an older library called `subscriptions-transport-ws`; see [below](#the-older-subscriptions-transport-ws-library) for the changes necessary to use that library with Apollo Client.)
7482

7583
### 1. Install required libraries
7684

7785
[Apollo Link](../api/link/introduction/) is a library that helps you customize Apollo Client's network communication. You can use it to define a **link chain** that modifies your operations and routes them to the appropriate destination.
7886

79-
To execute subscriptions over WebSocket, you can add a `WebSocketLink` to your link chain. This link requires the `subscriptions-transport-ws` library. Install it like so:
87+
To execute subscriptions over WebSocket, you can add a `GraphQLWsLink` to your link chain. This link requires the `graphql-ws` library. Install it like so:
8088

8189
```bash
82-
npm install subscriptions-transport-ws
90+
npm install graphql-ws
8391
```
8492

85-
### 2. Initialize a `WebSocketLink`
93+
### 2. Initialize a `GraphQLWsLink`
8694

87-
Import and initialize a `WebSocketLink` object in the same project file where you initialize `ApolloClient`:
95+
Import and initialize a `GraphQLWsLink` object in the same project file where you initialize `ApolloClient`:
8896

8997
```js:title=index.js
90-
import { WebSocketLink } from '@apollo/client/link/ws';
98+
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
9199

92-
const wsLink = new WebSocketLink({
93-
uri: 'ws://localhost:4000/subscriptions',
94-
options: {
95-
reconnect: true
96-
}
100+
const wsLink = new GraphQLWsLink({
101+
url: 'ws://localhost:4000/subscriptions',
97102
});
98103
```
99104

100-
Replace the value of the `uri` option with your GraphQL server's subscription-specific WebSocket endpoint. If you're using Apollo Server, see [Setting a subscription endpoint](https://www.apollographql.com/docs/apollo-server/data/subscriptions/#setting-a-subscription-endpoint).
105+
Replace the value of the `url` option with your GraphQL server's subscription-specific WebSocket endpoint. If you're using Apollo Server, see [Setting a subscription endpoint](https://www.apollographql.com/docs/apollo-server/data/subscriptions/#setting-a-subscription-endpoint).
101106

102107
### 3. Split communication by operation (recommended)
103108

104-
Although Apollo Client _can_ use your `WebSocketLink` to execute all operation types, in most cases it should continue using HTTP for queries and mutations. This is because queries and mutations don't require a stateful or long-lasting connection, making HTTP more efficient and scalable if a WebSocket connection isn't already present.
109+
Although Apollo Client _can_ use your `GraphQLWsLink` to execute all operation types, in most cases it should continue using HTTP for queries and mutations. This is because queries and mutations don't require a stateful or long-lasting connection, making HTTP more efficient and scalable if a WebSocket connection isn't already present.
105110

106111
To support this, the `@apollo/client` library provides a `split` function that lets you use one of two different `Link`s, according to the result of a boolean check.
107112

108-
The following example expands on the previous one by initializing both a `WebSocketLink` _and_ an `HttpLink`. It then uses the `split` function to combine those two `Link`s into a _single_ `Link` that uses one or the other according to the type of operation being executed.
113+
The following example expands on the previous one by initializing both a `GraphQLWsLink` _and_ an `HttpLink`. It then uses the `split` function to combine those two `Link`s into a _single_ `Link` that uses one or the other according to the type of operation being executed.
109114

110115
```js:title=index.js
111116
import { split, HttpLink } from '@apollo/client';
112117
import { getMainDefinition } from '@apollo/client/utilities';
113-
import { WebSocketLink } from '@apollo/client/link/ws';
118+
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
114119

115120
const httpLink = new HttpLink({
116121
uri: 'http://localhost:4000/graphql'
117122
});
118123

119-
const wsLink = new WebSocketLink({
120-
uri: 'ws://localhost:4000/subscriptions',
121-
options: {
122-
reconnect: true
123-
}
124+
const wsLink = new GraphQLWsLink({
125+
url: 'ws://localhost:4000/subscriptions',
124126
});
125127

126128
// The split function takes three parameters:
@@ -162,24 +164,20 @@ const client = new ApolloClient({
162164
163165
### 5. Authenticate over WebSocket (optional)
164166

165-
It is often necessary to authenticate a client before allowing it to receive subscription results. To do this, you can provide a `connectionParams` option to the `WebSocketLink` constructor, like so:
167+
It is often necessary to authenticate a client before allowing it to receive subscription results. To do this, you can provide a `connectionParams` option to the `GraphQLWsLink` constructor, like so:
166168

167169
```js{7-9}
168-
import { WebSocketLink } from '@apollo/client/link/ws';
170+
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
169171
170-
const wsLink = new WebSocketLink({
171-
uri: 'ws://localhost:4000/subscriptions',
172-
options: {
173-
reconnect: true,
174-
connectionParams: {
175-
authToken: user.authToken,
176-
},
172+
const wsLink = new GraphQLWsLink({
173+
url: 'ws://localhost:4000/subscriptions',
174+
connectionParams: {
175+
authToken: user.authToken,
177176
},
178177
});
179178
```
180179

181-
Your `WebSocketLink` passes the `connectionParams` object to your server whenever it connects. If your server has a [SubscriptionsServer](https://www.apollographql.com/docs/graphql-subscriptions/authentication) object that's listening for WebSocket connections, it receives the `connectionParams` object and can use it to perform authentication, along with any other connection-related tasks.
182-
180+
Your `GraphQLWsLink` passes the `connectionParams` object to your server whenever it connects. Your server receives the `connectionParams` object and can use it to perform authentication, along with any other connection-related tasks.
183181

184182
## Executing a subscription
185183

@@ -312,3 +310,32 @@ The `useSubscription` Hook accepts the following options:
312310
After being called, the `useSubscription` Hook returns a result object with the following properties:
313311

314312
<SubscriptionResult />
313+
314+
## The older `subscriptions-transport-ws` library
315+
316+
If your server uses `subscriptions-transport-ws` instead of the newer `graphql-ws` library, you need to make a few changes to how you set up your link.
317+
318+
Instead of `npm install graphql-ws`, you `npm install subscriptions-transport-ws`
319+
320+
Instead of `import { GraphQLWsLink } from '@apollo/client/link/subscriptions'`, you `import { WebSocketLink } from '@apollo/client/link/ws`.
321+
322+
The options passed to the link constructor are slightly different. The subscriptions URL is specified in an `uri` option instead of an `url` option. The `connectionParams` option is nested under an options object called `options` instead of being at the top level.
323+
324+
Once you've created your `wsLink`, everything else in this document still applies: `useSubscription`, `subscribeToMore`, and split links work exactly the same way for both implementations.
325+
326+
The following is what typical `WebSocketLink` initialization looks like:
327+
328+
```js
329+
import { WebSocketLink } from "@apollo/client/link/ws";
330+
331+
const wsLink = new GraphQLWsLink({
332+
uri: "ws://localhost:4000/subscriptions",
333+
options: {
334+
connectionParams: {
335+
authToken: user.authToken,
336+
},
337+
},
338+
});
339+
```
340+
341+
More details on `WebSocketLink`'s API can be found in [its API docs](../api/link/apollo-link-ws).

package-lock.json

Lines changed: 24 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,14 @@
6464
},
6565
"peerDependencies": {
6666
"graphql": "^14.0.0 || ^15.0.0 || ^16.0.0",
67+
"graphql-ws": "^5.5.5",
6768
"react": "^16.8.0 || ^17.0.0",
6869
"subscriptions-transport-ws": "^0.9.0 || ^0.11.0"
6970
},
7071
"peerDependenciesMeta": {
72+
"graphql-ws": {
73+
"optional": true
74+
},
7175
"react": {
7276
"optional": true
7377
},
@@ -110,6 +114,7 @@
110114
"fetch-mock": "9.11.0",
111115
"glob": "7.2.0",
112116
"graphql": "16.0.1",
117+
"graphql-ws": "5.5.5",
113118
"jest": "27.4.7",
114119
"jest-fetch-mock": "3.0.3",
115120
"jest-junit": "13.0.0",

src/__tests__/__snapshots__/exports.ts.snap

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,12 @@ Array [
210210
]
211211
`;
212212

213+
exports[`exports of public entry points @apollo/client/link/subscriptions 1`] = `
214+
Array [
215+
"GraphQLWsLink",
216+
]
217+
`;
218+
213219
exports[`exports of public entry points @apollo/client/link/utils 1`] = `
214220
Array [
215221
"createOperation",

src/__tests__/exports.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import * as linkHTTP from "../link/http";
1111
import * as linkPersistedQueries from "../link/persisted-queries";
1212
import * as linkRetry from "../link/retry";
1313
import * as linkSchema from "../link/schema";
14+
import * as linkSubscriptions from "../link/subscriptions";
1415
import * as linkUtils from "../link/utils";
1516
import * as linkWS from "../link/ws";
1617
import * as react from "../react";
@@ -52,6 +53,7 @@ describe('exports of public entry points', () => {
5253
check("@apollo/client/link/persisted-queries", linkPersistedQueries);
5354
check("@apollo/client/link/retry", linkRetry);
5455
check("@apollo/client/link/schema", linkSchema);
56+
check("@apollo/client/link/subscriptions", linkSubscriptions);
5557
check("@apollo/client/link/utils", linkUtils);
5658
check("@apollo/client/link/ws", linkWS);
5759
check("@apollo/client/react", react);

0 commit comments

Comments
 (0)