Google Cloud Pub/Sub Triggers

Cloud Functions can be triggered by messages published to Cloud Pub/Sub topics. Cloud Pub/Sub is a globally distributed message bus that automatically scales as you need it and provides a foundation for building your own robust, global services.

The following gcloud command deploys a function that will be triggered by Cloud Pub/Sub:

gcloud beta functions deploy helloPubSub --trigger-resource hello_world --trigger-event google.pubsub.topic.publish
Argument Description
--trigger-resource <name> The name of the Pub/Sub topic to which the function will be subscribed.
--trigger-event <name> The name of the event type that the function wishes to receive. In this case, it is the Pub/Sub topic.publish event.

Cloud Pub/Sub Events

Cloud Functions triggered from Cloud Pub/Sub topic events will be sent an event containing a PubsubMessage object. The format of the PubsubMessage is as per the published format for PubsubMessage objects.

The payload of the PubsubMessage (the data you published to the topic) is stored as a base64-encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage you need to decode the data attribute.

For example:

Node.js

/**
 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloPubSub = (event, callback) => {
  const pubsubMessage = event.data;
  const name = pubsubMessage.data ? Buffer.from(pubsubMessage.data, 'base64').toString() : 'World';

  console.log(`Hello, ${name}!`);

  callback();
};

Legacy Cloud Pub/Sub triggers

The gcloud command below deploys a function that is triggered by legacy Pub/Sub notifications on a specific bucket. These notifications are supported for legacy functions already consuming these events. However, we recommend moving to the new event type as this one may be removed at a future date.

gcloud beta functions deploy helloPubSub --trigger-resource hello_world --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Next steps

See the Cloud Pub/Sub Tutorial for an example of how to implement a background function that is triggered by Cloud Pub/Sub.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Functions Documentation