Create a Topic
Learn how to create a new topic and submit your first message on Hedera testnet using the JavaScript, Java, or Go SDK. A topic on the Hedera Consensus Service (HCS) is like a public channel: anyone who knows the topic ID can publish timestamped messages, and anyone can subscribe to the stream from a mirror node.
Prerequisites
A Hedera testnet operator account ID and DER-encoded private key (from the Quickstart).
A small amount of testnet HBAR (ℏ) to cover the fees
Topic creation: ≈
$0.01
Each message: <
$0.001
NoteYou can always check the "✅ Code Check" section at the bottom of each page to view the entire code if you run into issues. You can also post your issue to the respective SDK channel in our Discord community here.
Install the SDK
Open your terminal and create a directory hedera-examples
directory. Then change into the newly created directory:
mkdir hedera-examples && cd hedera-examples
Initialize a node.js
project in this new directory:
npm init -y
Ensure you have Node.js v18
or later installed on your machine. Then, install the JavaScript SDK.
npm install --save @hashgraph/sdk
Update your package.json
file to enable ES6 modules and configure the project:
{
"name": "hedera-examples",
"version": "1.0.0",
"type": "module",
"main": "createTopicDemo.js",
"scripts": {
"start": "node createTopicDemo.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@hashgraph/sdk": "^2.69.0"
}
}
Create a createTopicDemo.js
file and add the following imports:
import {
Client,
TopicCreateTransaction,
TopicMessageSubmitTransaction
} from "@hashgraph/sdk";
Environment Variables
Set your operator credentials as environment variables. Your OPERATOR_ID
is your testnet account ID. Your OPERATOR_KEY
is your testnet account's corresponding ECDSA private key.
export OPERATOR_ID="0.0.1234"
export OPERATOR_KEY="3030020100300506032b657004220420..."
Step 1: Initialize Hedera Client
Load your operator credentials from environment variables and configure your Hedera testnet client. The client manages your connection to the Hedera test network and uses your operator account to sign transactions and pay transaction fees.
// Load your operator credentials
const operatorId = process.env.OPERATOR_ID;
const operatorKey = process.env.OPERATOR_KEY;
// Initialize your testnet client and set operator
const client = Client.forTestnet()
.setOperator(operatorId, operatorKey);
Step 2: Create a new topic
TopicCreateTransaction
builds and sends the transaction to register a new HCS topic with the provided memo, and once it reaches consensus you retrieve the transaction receipt to extract the new topicId
.
Why messages?
Messages on HCS are consensus-timestamped and immutable. Once published, they become part of the permanent record that anyone can verify and subscribe to in real-time.
// Build and send the transaction
const txResponse = await new TopicCreateTransaction()
.setTopicMemo("My first HCS topic") // optional description
.execute(client);
const receipt = await txResponse.getReceipt(client);
const topicId = receipt.topicId;
console.log(`\nTopic created: ${topicId.toString()}`);
What just happened?
The SDK built a TopicCreateTransaction.
Your operator key signed and paid the fee.
Hedera nodes reached consensus and returned a unique topic ID (
shard.realm.num
).
Step 3: Submit Message to Topic
TopicMessageSubmitTransaction
constructs and sends a transaction that submits your payload (string, bytes, or Uint8Array
) as a message to a specified HCS topic. Once it reaches consensus, the message becomes part of that topic’s immutable record.
// Build & execute the message submission transaction
const message = "Hello, Hedera!";
const messageTransaction = new TopicMessageSubmitTransaction()
.setTopicId(topicId)
.setMessage(message);
await messageTransaction.execute(client);
console.log(`\nMessage submitted: ${message}\n`);
Note
Messages can be up to 1 KiB each. Larger payloads must be chunked automatically by the SDK or split manually
Step 4: Query Messages Using Mirror Node API
Use the Mirror Node REST API to verify your message was published to the topic. Mirror nodes provide free access to network data without transaction fees. Mirror nodes stream every consensus-timestamped message in order, letting your app react in real time.
API endpoint:
/api/v1/topics/{topicId}/messages
Replace the placeholder:
{topicId} - Your topic ID from the creation transaction
Why this endpoint?This endpoint retrieves all messages published to a specific topic, ordered by consensus timestamp. It returns detailed information including message content, timestamp, and sequence number, making it ideal for verifying your message was published successfully.
Example URLs:
const mirrorNodeUrl = `https://testnet.mirrornode.hedera.com/api/v1/topics/${topicId}/messages`;
Complete Implementation:
// wait for Mirror Node to populate data
console.log("\nWaiting for Mirror Node to update...");
await new Promise((resolve) => setTimeout(resolve, 6000));
// query messages using Mirror Node
const mirrorNodeUrl = `https://testnet.mirrornode.hedera.com/api/v1/topics/${topicId}/messages`;
const response = await fetch(mirrorNodeUrl);
const data = await response.json();
if (data.messages && data.messages.length > 0) {
const latestMessage = data.messages[data.messages.length - 1];
const messageContent = Buffer.from(latestMessage.message, "base64")
.toString("utf8")
.trim();
console.log(`\nLatest message: ${messageContent}\n`);
} else {
console.log("No messages found yet in Mirror Node");
}
client.close();
✅ Code check
Before running your project, verify your code matches the complete example:
Run Your Project
Ensure your environment variables are set:
export OPERATOR_ID="0.0.1234"
export OPERATOR_KEY="3030020100300506032b657004220420..."
node createTopicDemo.js
Expected sample output:
Topic created: 0.0.1234567
Message submitted: Hello, Hedera!
Waiting for Mirror Node to update...
Latest message: Hello, Hedera!
‼️ Troubleshooting
What Just Happened?
The SDK built a
TopicCreateTransaction
and signed it with your operator key.A consensus node validated the signature and charged the topic creation fee.
After network consensus, a unique topic ID was assigned and returned in the receipt.
Your message was submitted to the topic and became part of the immutable record.
The Mirror Node API confirmed your message was published with consensus timestamp
Next steps
Subscribe to the topic from your backend or front-end to process messages as they come in
Encrypt messages if you need privacy before publishing
Explore more examples in the SDK repos (JavaScript, Java, Go)
🎉 Great work! You have created a new topic and broadcasted your first message on Hedera testnet. Keep building!
Additional Resources
Last updated
Was this helpful?