Node.js - Integrating Google Cluod Functions with Cloud Pub/Sub

Google Cloud Functions can be your choice if you need a serverless solution to run Node.js functions. One of the advantages of using Google Cloud Platform is we can easily integrate a service with another Google service. If you're using Cloud Functions, there are some ways to trigger function execution, one of which is by publishing message on Google Cloud Pub/Sub. Google has made it so easy for us to trigger function execution on Cloud Functions whenever a message is published on a specified Pub/Sub topic. In this tutorial, I'm going to show you how to integrate those two Google services.

I assume you've already known how to setup Google Cloud Functions for running Node.js. If you haven't, read our tutorial about running serverless Node.js on Google Cloud Functions.

The function needs to handle events from Pub/Sub. Whenever an event occurs (a message is published), the function will be triggered with a parameter named event which has the following format.

  {
    '@type': 'type.googleapis.com/google.pubsub.v1.PubsubMessage',
    attributes: null,
    data: 'U2F0IERlYyAyOSAyMDE4IDE3OjExOjUwIEdNVCswNzAwIChXSUIp'
  }

data is the message in Base64 format. Therefore, you need to convert the Base64 value to string.

  exports.helloPubSub = (event) => {
    const pubsubMessage = event.data;
  
    const name = pubsubMessage
      ? Buffer.from(pubsubMessage, 'base64').toString()
      : 'World';

    console.log(`The message is ${name}!`);
  };

Run the following command to deploy the function.

gcloud functions deploy helloPubSub --project PROJECT_NAME --trigger-topic TOPIC_NAME

To trigger the function, what you need to do is publishing a message to the topic. You can do it from Google Cloud Pub/Sub console. Choose the appropriate topic and click on Publish Message. Enter the message and publish it. The function should be triggered if you have set up everything correctly.

Alternatively, you can publish a message to Pub/Sub from your Node.js application.

To view the logs of function executions, you can go to the console of Cloud Functions. Choose the function that handles Pub/Sub event. On the top, click on View Logs and you will be redirected to a page that shows the logs.

Google Cloud Functions - Function Details

If everything goes well, you should see the output of console.log.