Create a GCP Pub/Sub with NodeJS

German Reynaga
2 min readAug 11, 2021

I started writing this looking to contribute to the few articles on the subject and hoping to be of help in someones road.

How it works?

GCP PubSub works as a message broker that consists on a publisher who can send a message containig a set of instructions and/or data to be processed as well as a subscriber which will be listening to those messages and execute the specified instructions, thse are published into a topic which can be seen as a container to store messages of an specific type

How to create the publisher/subscriber functions?

Both of them are nothing more than functions, in this case JavaScript ones that will be in charge of sending and receiving the message respectively.

Luckily in NodeJS we have a package from the google cloud team wich make this task even easier. we just need to:

  • Instantiate de PubSub method
  • Create a buffer containing the data to send
  • Define the name of the topic to use
  • Publish the message passing the data buffer

For his part a subscriber doesn’t need to have the PubSub package installed as it is just a plain function which will receive two parameters, the event wich will contain the data sent through the message and the callback to respond to the message broker.

How to create the topic?

The topic must be created inside GCP or using the `gcloud` cli, in this case we are going to use the web interface.

Inside our project we need to go to the topics page inside pubsub or searching for pubsub in the searcher and moving to the Topics item in the side menu.

Once we are inside we gonna see something like this

Clicking on the “Create Topic” button will open a modal window where we can define the topic configuration. For this example we are just going to add the topic ID. To see more about how to implement schemas you can go this article where Pavan Kumar Kattamuri gives a great explanation about it.

And that’s it with this we are done on the topic creation.

Other considerations

  • To make the subscriber work you gonna need to create the subscription setting the trigger on your google cloud subscriber function. This page can help you if you are using serverless framework (otherwirse I will try to address this in another article)

--

--

German Reynaga

Full Stack web developer, passionate with education and constantly improving my background.