Beginner Tutorial: How To Build a Simple Instant Messaging dApp With Streamr

Donatus Prince
3 min readJul 26, 2023

--

In this beginner tutorial, we’ll walk you through the process of creating a simple Instant Messaging decentralized application (dApp) using the Streamr network.

Streamr is a fully decentralized and scalable protocol for many-to-many data pipelines, network analytics, and instant messaging.

Prerequisites

Before we get started, make sure you have the following:

  1. NPM v8 or greater
  2. NodeJS 16.13.x or greater
  3. A small amount of MATIC to pay for gas on Polygon mainnet. If you need tokens, you can reach out to the #dev channel on Discord to ask any questions.
  4. Basic knowledge of JavaScript and React (for the frontend)
  5. A Vite app project set up. If you don’t have one yet, you can create it by following these steps:

Setting Up a Vite App

npm create vite@latest
create-vite my-streamr-app
cd my-streamr-app
// install dependencies
npm install

Setting Up the Streamr Client

First, let’s set up the Streamr JavaScript client in a NodeJS script.

Install the Streamr client using NPM:

npm install streamr-client

Open the app.jsx and import the necessary libraries to be used in the dApp as seen below.

import React, { useState, useEffect } from 'react';
import { Stream, StreamrClient } from 'streamr-client';
import './App.css'

Initialize the client with your Ethereum private key:

// Import the Streamr client
const StreamrClient = require("streamr-client");

// Replace 'ethereum-private-key' with your actual private key
const streamr = new StreamrClient({
auth: {
privateKey: "ethereum-private-key",
},
});

Creating a Data Stream

Before we can start messaging, we need to create a data stream. Think of a stream as a sequence of data points in time. It is semantically equivalent to topics in traditional publish/subscribe networks.

const createStreamAndSubscribe = async () => {
try {
// Create or get the stream with the given ID
const stream = await streamr.getOrCreateStream({
id: 'YOUR STREAM ID', // Replace with your desired stream ID
});
setStreamId(stream.id);

// Subscribe to incoming messages on the stream
const subscription = streamr.subscribe(
{
id: 'YOUR STREAM ID', // Replace with your stream ID
},
(message) => {
// 'message' contains the incoming data
const incomingMessage = message;
setMessages((prevMessages) => [...prevMessages, incomingMessage]);
},
(error) => {
console.error('Error subscribing to the data stream:', error);
}
);
} catch (error) {
console.error('Error creating the stream:', error);
}
};

// Call the createStreamAndSubscribe function when the component mounts
useEffect(() => {
createStreamAndSubscribe();
}, []);

Publishing Messages

Now that we have a data stream, let’s enable message publishing:

const handleSubmit = async () => {
if (message.trim() !== '') {
try {
// Publish the message to the data stream
await streamr.publish('YOUR STREAM ID', { message }); // Replace with your stream ID
setMessage('');
} catch (error) {
console.error('Error publishing message:', error);
}
}
};

Rendering Messages on the Frontend

In the frontend, we’ll display the incoming messages and provide an input field to send new messages.

function App() {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [streamId, setStreamId] = useState('');

// ... (insert previously shown code here)

return (
<>
<h1>My Streamr Dapp 💬</h1>
<div>
<p>Stream ID: <strong>{streamId}</strong></p>
<h2>Incoming Messages 📩</h2>
{/* Display incoming messages in this div */}
{messages.map((msgObj, index) => (
<p key={index}>
<strong>You:</strong> {msgObj.message}
</p>
))}
</div>
<h2>Publish To Streamr 📨</h2>
<div className="card">
<input type="text" value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={handleSubmit}>Send</button>
</div>
<p className="read-the-docs">
Made with ❤️ for{' '}
<a href="https://docs.streamr.network/" target="_blank" rel="noopener noreferrer">
Streamr Network
</a>
</p>
</>
);
}

export default App;

Conclusion

Congratulations! You’ve successfully built a simple Instant Messaging dApp using the Streamr network. Now you can expand and customize this application further based on your needs.

Remember that this is just a basic example, and you can enhance it with features like user authentication, message encryption, or adding multiple chat rooms.

Have fun experimenting with Streamr and its capabilities!

--

--

Donatus Prince
Donatus Prince

Written by Donatus Prince

Business Data Analyst @ dataron | Passionate abut building business solutions on the Blockchain's NFTs and Defi network | I love sharing my journey in tech!

No responses yet