API with NestJS #29. Real-time updates with GraphQL subscriptions

JavaScript NestJS TypeScript

This entry is part 29 of 148 in the API with NestJS

So far, in this series, we’ve used GraphQL both to fetch and modify data. While this covers many real-life cases, modern applications often include situations in which users need immediate feedback when some event occurs.

One of the solutions suggested by the GraphQL team is polling. In this technique, the client periodically requests the API for changes. It is a straightforward approach and works out of the box without much code. Unfortunately, usually, updates can be unpredictable. Therefore, polling is often wasteful and introduces unnecessary traffic in our API.

To counter the above issue, with GraphQL, we have a concept of subscriptions. They act as a way for the clients to listen for events in real-time. The client informs the server that it cares about a set of events. When they trigger, the server is responsible for notifying the client. To achieve that, the server needs to declare the events that the client can listen to.

Under the hood, an active connection between the client and the server establishes. Thanks to that, we can push messages from the server to our users. Usually, subscriptions in GraphQL are implemented with WebSockets, although the official specification does not enforce that. There were some attempts in implementing subscriptions using Server-sent events, for example.

If you want to know how to use NestJS with WebSockets, check out API with NestJS #26. Real-time chat with WebSockets

Implementing subscriptions with NestJS

The very first step in implementing subscriptions is enabling them. To do so, we need to turn on the property.

app.module.ts

Creating an instance of a PubSub

The first concept that we need to grasp is the PubSub. Its job is to be a middleman between the logic of our application and the GraphQL subscriptions engine. It does that by exposing a simple and API.

Under the hood, NestJS uses Apollo, which is a widespread GraphQL implementation. A part of the Apollo architecture is the graphql-subscriptions library. It does contain a ready-to-use PubSub. Unfortunately, it is not meant to be used in production, though, as mentioned in the docs. It wouldn’t work with multiple instances of our NestJS server. Also, it does not scale beyond a few connections.

Among the suggested PubSub implementations, the most popular seems to be the graphql-redis-subscriptions library.

We’ve already used Redis in this series in API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster. If you want to know how to set up Redis with docker, check it out.

When initializing a PubSub, let’s take the advice from Jay McDoniel, one of the NestJS library maintainers. It includes defining a global module with an instance of the PubSub.

pubSub.module.ts

Global modules should be registered only once, preferably in the , our root module. Doing so makes them available everywhere.

Defining the subscription

In the twenty-seventh part of this series, we’ve defined the model of a post. This article aims to define a subscription that allows our users to listen to newly-created posts.

To define a subscription using the code-first approach, we need to use the decorator.

posts.resolver.ts

Please note that the name of the event matches the method. If that’s not the case, we need to pass additional options to the decorator.

Above, we return the every time a client requests a subscription. Thanks to that, every time we call , the clients who subscribed will receive the event.

posts.resolver.ts

Thanks to doing that, our clients can subscribe to incoming posts. We can try that through the GraphQL playground:

Subscribing to post creation

Above, we can see that the subscription is active, and the client listens to incoming events. When the post gets created, it is visible in the interface right away.

Subscribing to post creation with a result

Filtering events

We can pass additional options to the decorator. One of them is the function. It has the payload and the variables as its arguments. If it returns , the event is filtered out and not returned to the clients.

Modifying the payload before sending

Another optional option of the decorator is the function. It can modify the payload before sending it to the client.

We can also access injected providers both in the and functions. To do that, use the following:

Summary

In this article, we’ve looked into how we can update our users with our application’s newest state. Although one of the solutions might be polling, it has its drawbacks. Therefore, we’ve implemented subscriptions that under the hood use WebSockets. Combined with the Redis-based PubSub, we can send events to our users in a performant way.

Series Navigation<< API with NestJS #28. Dealing in the N + 1 problem in GraphQLAPI with NestJS #30. Scalar types in GraphQL >>
Subscribe
Notify of
guest
9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
koike
koike
2 years ago

Do you publish all the code??

koike
koike
2 years ago
Reply to  Marcin Wanago

thank you!!!!!1

Kurt
Kurt
2 years ago

“GET query missing.” this error presents in playground

Kurt
Kurt
2 years ago
Reply to  Kurt

playground: Boolean(configService.get(‘GRAPHQL_PLAYGROUND’));

this is causing that error.

not really an expert to this and can’t understand why but i just changed it to this:

playground: Boolean(configService.get(‘GRAPHQL_PLAYGROUND’, true));

It seems the value ‘GRAPHQL_PLAYGROUND’ from configService is not available for some reason.

MichaelYao
MichaelYao
2 years ago

Can we do this kind of subscription in restful API?

Juliusz
Juliusz
1 year ago
Reply to  MichaelYao

Yes, with websockets https://docs.nestjs.com/websockets/gateways.
In general, this GraphQL subscriptions are also using websockets under the hood.

Ken
Ken
1 year ago

I got this error.

ERROR [ResolversExplorerService] “PostsResolver” resolver is request or transient-scoped. Resolvers that register subscriptions with the “@Subscription()” decorator must be static (singleton).

How can i fix it?

Adil
Adil
10 months ago

Thanks for writing this. Well written. One question that I posted on Stackoveflow as well is:
How is GraphQL Subscription any different from NestJS Gateway?

Both use ws under the hood.

Your thoughts?

Stack Overflow Question: https://stackoverflow.com/q/76309004/2467760