GraphQL Subscription

Subscription is another type of in GraphQL.

This is use real time events using websockets, you can send notification to client for events which happen on the server using web sockets.

It you are not aware what are websockets, you can find plenty of resources online.

Let’s see how to implement subscription in our code base. As an example, let’s add a subscription to notify user when a new todo is added

Let’s first look at our backend


export default `
type Subscription {
    todoAdded: Todo 


export default {
    Subscription: {
        todoAdded: {
            subscribe: () => pubsub.asyncIterator('TODO_ADDED')
    Mutation: {
        addTodo: (_, { input }) => {
            let id = Math.round(Math.random(0, 1000) * 1000)
   = id
            pubsub.publish('TODO_ADDED', { postAdded: input });
            return input

We are using pubsub library to publish events. This is quite simple

  1. define a subscription
  2. setup a resolver for the subscription
  3. publish using pubsub when the event happens

We can test this out in our playground.

When you run a subscription, it shows as Listing.. as you can see in the screenshot

Next add a todo from playground

Add Todo done
New Todo show up on the subscription automatically!

Let’s see how to do in on the frontend

The way to setup subscription is a bit complex but described in detail here