GraphQL Subscriptions - Graphql

Subscriptions allow clients to listen to real-time messages from the server. The client connects to the server via a bi-directional communication channel using WebSocket and sends a subscription query that specifies which event it is interested in. When an event is triggered, the server executes the stored GraphQL query, and the result is sent through the same communication channel back to the client.

The client can unsubscribe by sending a message to the server. The server can also unsubscribe at any time due to errors or timeout. Another significant difference between queries/mutations and a subscription is that subscriptions are stateful and require maintaining the GraphQL document, variables, and context over the lifetime of the subscription.

Enable Subscriptions

In GraphQL, it’s straightforward to enable subscriptions on any type. We add the directive @withSubscription in the schema along with the type definition.

type Todo @withSubscription {
  id: ID!
  title: String!
  description: String!
  completed: Boolean!
}

Example

Once the schema is added, you can fire a subscription query, and we receive updates when the subscription query result is updated.

Apollo Client Setup

Here is an excellent blog explaining in detail on how to set up GraphQL Subscriptions using Apollo client.


This is a companion discussion topic for the original entry at https://dgraph.io/docs/graphql/subscriptions/

:wave: ,

I am the author of graphql-ws and its, brand new, security first, lean, GraphQL over WebSocket Protocol.

The Protocol is aiming to become a part of the GraphQL standard with the help of the foundation’s brilliant GraphQL over HTTP Work Group (github[dot]com/graphql/graphql-over-http/pull/140).

I’d like to hear your opinion on the Protocol and if you would consider supporting it in your awesome Graph database?

If you are interested on reading a short article about the lib and its inception, you can check it out over at The Guild’s blog (the-guild[dot]dev/blog/graphql-over-websockets).

P.S. subscriptions-transport-ws's readme (github[dot]com/apollographql/subscriptions-transport-ws#graphql-ws) now officially recommends using graphql-ws instead.

Sorry for the flat, unclickable, URLs. New users apparently cant post more than 2 links, bummer…

1 Like

I get this error Error during WebSocket handshake: Unexpected response code: 200 so I assume it does not work outside of the box?

The transport Protocol is completely different, so no - it does not work out of the box.

Dgraph uses Apollo’s subscriptions-transport-ws and their deprecated transport Protocol. The new Protocol is a rewrite and the two are not interchangeable.