How to Create a Topic in Google Cloud Pub/Sub
To create a topic in Google Cloud Pub/Sub, use the
gcloud pubsub topics create [TOPIC_NAME] command or the Pub/Sub client libraries to programmatically create it. A topic is a named resource to which messages are sent for subscribers to receive.Syntax
The basic command to create a topic is:
gcloud pubsub topics create [TOPIC_NAME]: Creates a new topic with the specified name.
In code, you use the Pub/Sub client library's createTopic method with the topic name as input.
bash
gcloud pubsub topics create my-topic
Output
Created topic [projects/your-project-id/topics/my-topic].
Example
This example shows how to create a topic named my-topic using the Google Cloud SDK and Node.js client library.
javascript
const {PubSub} = require('@google-cloud/pubsub'); async function createTopic() { const pubSubClient = new PubSub(); const topicName = 'my-topic'; await pubSubClient.createTopic(topicName); console.log(`Topic ${topicName} created.`); } createTopic().catch(console.error);
Output
Topic my-topic created.
Common Pitfalls
- Trying to create a topic that already exists will cause an error.
- Not specifying the correct project ID can create the topic in the wrong project or fail.
- Missing permissions (Pub/Sub Admin role) will prevent topic creation.
- Using invalid characters in the topic name will cause failure.
Always check if the topic exists before creating or handle errors gracefully.
bash
gcloud pubsub topics create my-topic
# Error if topic exists
# Correct approach:
gcloud pubsub topics describe my-topic || gcloud pubsub topics create my-topicQuick Reference
| Command / Method | Description |
|---|---|
| gcloud pubsub topics create [TOPIC_NAME] | Create a topic via CLI |
| pubSubClient.createTopic(topicName) | Create a topic via client library |
| gcloud pubsub topics describe [TOPIC_NAME] | Check if topic exists |
| Topic name rules | Lowercase letters, numbers, dashes, underscores; max 255 chars |
Key Takeaways
Use the gcloud CLI or client libraries to create Pub/Sub topics easily.
Ensure the topic name follows naming rules and does not already exist.
Set the correct project and have proper permissions before creating topics.
Handle errors when creating topics to avoid failures in your app.