11

I have two sides.

In one side I have direct usage of WebSocket protocol by using libraries/packages like ws (a Node.js WebSocket library) or Socket.io. Here I can use test tools to subscribe against and address starting with ws or wss like ws://localhost:8080 and receive updates.

In other side, I use GraphQL Subscription by using components like ApolloGraphQL. It seems that this way I should use something embedded in GraphQL. Projects developed with this way can not be accessed via ws:// or wss:// addresses, or at least I am not aware of.

My questions is what are differences between two? Are GraphQL Subscription is built on top of WebSocket? If yes, how? How can I access a GraphQL Subscription via ws:// or wss:// urls?

UPDATE: I have read this and this question before, but they did not helped a lot.

Afshar Mohebi
  • 10,479
  • 17
  • 82
  • 126

1 Answers1

23

GraphQL is a specification and it's common to see GraphQL over HTTP for queries and mutations, however with GraphQL subscriptions we need to receive continuous updates from an API. That's where WebSockets come in.

WebSockets are often used as a transport protocol for GraphQL Subscriptions. So, to answer your question, GraphQL Subscriptions aren't bound to any protocol. In fact, GraphQL queries and mutations aren't limited to HTTP either. Hence, WebSocket-based GraphQL Subscriptions libraries implement a small protocol over which they send GraphQL subscription operations and results.

Two notable implementations are:

  • subscriptions-transport-ws which was made by the Apollo team (and hence does enjoy great support in Apollo Server) but isn't being actively maintained anymore
  • graphql-ws which is a successor project (with slight incompatibilities). Its readme does explain how to add it to an Apollo Server.

These are just protocol libraries with a server-side and a client-side implementation to facilitate GraphQL operations and result being sent over WebSockets. They thus take a lot of the work away from you having to come up with your own protocol or implementing one on something other than WebSockets.

Phil Plückthun
  • 1,381
  • 9
  • 14