Subscription

When we had initially set up Apollo, we used Apollo Boost to install the required dependencies. But subscriptions is an advanced use case which Apollo Boost does not support. So we have to install more dependencies to set up subscriptions.

React Apollo Subscriptions Setup

+ $ npm install subscriptions-transport-ws --save

Now we need to update our ApolloClient instance to point to the subscription server.

Open src/components/App.js and update the following imports:

githubsrc/components/App.js
- import { ApolloClient, ApolloProvider, InMemoryCache, HttpLink } from '@apollo/client';
+ import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
+ import { WebSocketLink } from "@apollo/client/link/ws";

Update the createApolloClient function to integrate WebSocketLink.

const createApolloClient = (authToken) => {
return new ApolloClient({
- link: new HttpLink({
+ link: new WebSocketLink({
- uri: 'https://hasura.io/learn/graphql',
+ uri: 'wss://hasura.io/learn/graphql',
+ options: {
+ reconnect: true,
+ connectionParams: {
headers: {
Authorization: `Bearer ${authToken}`
}
+ }
+ }
}),
cache: new InMemoryCache(),
});
};

Note that we are replacing HttpLink with WebSocketLink and hence all GraphQL queries go through a single websocket connection.

Close

Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.
Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Stay in the know
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. โœŒ๏ธ