Subscription

We need one more dependency to setup subscriptions. Let's install it.

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/apollo.js and update the following imports:

githubsrc/apollo.js

Update the createApolloClient function to integrate WebSocketLink.

import { split, HttpLink, InMemoryCache, ApolloClient } from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";
import { WebSocketLink } from "@apollo/client/link/ws";
export function createApolloClient(authToken) {
const headers = {
Authorization: `Bearer ${authToken}`,
};
const httpLink = new HttpLink({
uri: "https://hasura.io/learn/graphql",
headers,
});
+ const wsLink = new WebSocketLink({
+ uri: "wss://hasura.io/learn/graphql",
+ options: {
+ reconnect: true,
+ connectionParams: {
+ headers,
+ },
+ },
+ });
+
+ const link = split(
+ ({ query }) => {
+ const definition = getMainDefinition(query);
+ return (
+ definition.kind === "OperationDefinition" &&
+ definition.operation === "subscription"
+ );
+ },
+ wsLink,
+ httpLink
+ );
const cache = new InMemoryCache();
const client = new ApolloClient({
link,
cache,
});
return client;
}

split is used to choose WebSocketLink for subscription queries and HttpLink for queries and mutations.

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. โœŒ๏ธ