0
0
GcpHow-ToBeginner · 4 min read

How to Use Pub/Sub with Cloud Functions on GCP

To use Pub/Sub with Cloud Functions, create a Cloud Function triggered by a Pub/Sub topic. When a message is published to the topic, the function automatically runs and processes the message.
📐

Syntax

The basic syntax to create a Cloud Function triggered by Pub/Sub involves specifying the eventTrigger with the Pub/Sub topic name. The function receives an event object containing the message data.

  • event: Contains the Pub/Sub message and metadata.
  • context: Provides event metadata like event ID and timestamp.
javascript
exports.myPubSubFunction = (event, context) => {
  const message = event.data
    ? Buffer.from(event.data, 'base64').toString()
    : 'No message data';
  console.log(`Received message: ${message}`);
};
💻

Example

This example shows a Cloud Function in Node.js triggered by a Pub/Sub topic named my-topic. It logs the message content when a message is published.

javascript
exports.processPubSubMessage = (event, context) => {
  const message = event.data
    ? Buffer.from(event.data, 'base64').toString()
    : 'No message data';
  console.log(`Message received: ${message}`);
};
Output
Message received: Hello, Pub/Sub!
⚠️

Common Pitfalls

Common mistakes include:

  • Not decoding the base64 message data before use.
  • Misconfiguring the Pub/Sub topic name in the function trigger.
  • Ignoring error handling inside the function.

Always decode event.data from base64 to get the original message string.

javascript
/* Wrong: Using event.data directly without decoding */
exports.badFunction = (event) => {
  console.log(event.data); // Prints base64 string, not readable message
};

/* Right: Decode base64 to string */
exports.goodFunction = (event) => {
  const message = Buffer.from(event.data, 'base64').toString();
  console.log(message); // Prints readable message
};
📊

Quick Reference

StepDescription
Create Pub/Sub TopicUse GCP Console or CLI to create a topic.
Write Cloud FunctionCreate a function triggered by the Pub/Sub topic.
Deploy FunctionDeploy with trigger set to the Pub/Sub topic.
Publish MessageSend messages to the topic to trigger the function.
Monitor LogsCheck Cloud Logging for function execution details.

Key Takeaways

Create a Cloud Function with a Pub/Sub trigger to run code on message arrival.
Always decode the Pub/Sub message data from base64 before using it.
Ensure the function trigger matches the exact Pub/Sub topic name.
Test by publishing messages to the topic and checking function logs.
Handle errors inside the function to avoid silent failures.