Skip to main content

Publishing

Publishing to a stream means to write or push data/messages to a stream.

Applications publish and subscribe to streams via Streamr nodes. In other words, nodes are the access points to the Streamr Network. You can either run a light node which is imported as a library and runs locally as part of your application (Streamr SDK) or you can interface your app with a Streamr node. The Streamr node runs separately, and your application connects to it remotely using one of the supported protocols, WebSockets, HTTP or MQTT.

Important:

You must grant PUBLISH permission before the user can publish data to the stream.

Learn more about stream permissions

Publish code snippets

// Run a Streamr node right inside your JS app
const Streamr = require('@streamr/sdk');

// Initialize the SDK with an Ethereum account
// This account will need the publish permission on this stream to publish
const streamr = new Streamr({
auth: {
privateKey: 'ethereum-private-key',
},
});

// Publish messages to this stream
streamr.publish(
streamId,
{
hello: 'world',
}
);

Publishing examples

// Here's our example data point
const msg = {
temperature: 25.4,
humidity: 10,
happy: true,
};

// Publish using the stream id only
await streamr.publish(streamId, msg);

// Publish with a specific timestamp as a Date object (default is now)
await streamr.publish(streamId, msg, { timestamp: new Date(1546300800123) });

// Publish with a specific timestamp in ms
await streamr.publish(streamId, msg, { timestamp: 1546300800123 });

// Publish with a specific timestamp as a ISO8601 string
await streamr.publish(streamId, msg, { timestamp: '2019-01-01T00:00:00.123Z' });

// For convenience, stream.publish(...) equals streamr.publish(stream, ...)
await stream.publish(msg);