Using Google PubSub with Strapi

Saad Mujeeb
2 min readMay 14, 2022

--

Strapi being one of the best open source headless CMS is used in multiple use cases and in different software architectures.
Today we’ll be showing you how you can use Google Cloud Platform’s PubSub with Strapi. Either in a micro-services architecture or in a simple application design, you can publish and subscribe to messages from PubSub in a few easy steps.

To set up PubSub in a Strapi application, we need to first install @google-cloud/pubsub in your strapi application

npm install @google-cloud/pubsub

After installation add a helper file in your Strapi project directory with code below:

This code contains 3 functions for Pubsub init, Publish a message and to subscribe to a topic’s subscription.

Once you have these functions in place, the open index.js file in

root/src/index.js

We will be adding code to the bootstrap function because this function executes before the application gets started and we can use it to initialize PubSub and add it to the Global strapi variable.

Here for the sake of an example we have initialized PubSub with the psInit method from our Helper library.

Then We Published to a topic using the psPublish method, we passed the pubsub object from strapi global object and we also passed the topic name as string and a payload which will be sent as the message body.

We also subscribed to a topic using the psSubscribe helper function and passed a callback function which in our case is a simple console.log function.

and voila, we are done.

We added the pubsub object to the global strapi variable so that we don’t need to re-initialize pubsub every time and strapi.pubsub is available through out the application and you can use it in controller, life cycle hooks etc.
Just to keep the flow clean and avoid any ambiguous errors, keep the subscriptions in the bootstrap function so that they get subscribed only once through out the life cycle of the strapi application.

Conclusion

That’s it, you can now use Google PubSub with Strapi.
Please leave any comments for any queries or suggestions for future topics you’d like me to write on.

--

--

Saad Mujeeb

Google Cloud Solutions Architect, Full Stack JS Dev with Strapi, NodeJS & a Strapi Community Star