DEV Community


GraphQL Subscriptions - magic on the frontend

Developer, Tech Enthusiast, Evolving to create awesome UIs, and a Gamer. Trying to document my personal code journey on Instagram!
・2 min read

Hello from the Dev cave! 🍻
Hope you are safe and healthy.

This one is a long due about how I implemented a notification system in one of my react projects using Apollo GraphQL subscriptions.

Install the dependencies


Amending the Apollo Client config

The thing with subscriptions is that it doesn't work on the same http protocol like queries and mutations. Subscriptions work using websockets. So we need to tweak our Apollo Client config to enable and handle this communication.

Import the dependencies -


Just like we create a http link to enable communication for queries and mutations, we will create a an instance of WebSocketLink for our subscriptions.


In the uri property, pass the endpoint for subscriptions which you have defined in your server, something like - ws://server:port/subscriptions. In the options property, we pass various config parameters ( like reconnect i.e. auto reconnect once it disconnects) and connection parameters like your auth and other headers.

Once done, we inform/configure the Apollo Client how it can differentiate when to use which link. For this, we use the "split" functionality and "getMainDefinition" utility. Apollo docs explain this extremely clearly - 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. Split here basically helps in separating the communication channel. We use the getMainDefinition utility to check whether our operation is a query (or a mutation) or a subscription.


Once done, we feed this splitLink to our client.


Consuming subscriptions

Just like queries and mutations, we have a hook for this! The useSubscription hooks, consumes the subscription and return data, loading and error variables. It takes a defined GQL subscription as input along with connection options - like I have use shouldResubscribe here. Doing this, confirms that this is not a one time things and the application should be open to receive updates.


Give this a shot and let me know how it worked out for you.


Discussion (0)