In this tutorial, we'll guide you through building a real-time data dashboard using SuperViz, a powerful SDK for real-time communication and data synchronization. Real-time dashboards are an essential tool for monitoring and analyzing data as it happens, allowing users to make quick, informed decisions based on the latest information.
We'll use stock market data from Yahoo Finance as our example data source. However, the principles and techniques you'll learn can be applied to any data source you have access to on the server. Whether it's financial data, weather updates, or user activity, this tutorial will equip you with the skills to create a dynamic dashboard that updates in real-time.
By the end of this tutorial, you'll have a fully functioning real-time dashboard that can be customized and extended to meet your specific needs. Let's get started!
Prerequisite
To follow this tutorial, you will need a SuperViz account and a developer token. If you already have an account and a developer token, you can move on to the next step.
Create an account
To create an account, go to https://dashboard.superviz.com/register and create an account using either Google or an email/password. It's important to note that when using an email/password, you will receive a confirmation link that you'll need to click to verify your account.
Retrieving a Developer Token
To use the SDK, you’ll need to provide a developer token, as this token is essential for associating SDK requests with your account. You can retrieve both development and production SuperViz tokens from the dashboard..
Copy and save the developer token, as you will need it in the next steps of this tutorial.
Step 1: Setting Up the Server with Express.js
The server is responsible for fetching stock data from Yahoo Finance and broadcasting updates to the frontend using SuperViz.
1. Create a New Project and Install Dependencies
First, set up a new Node.js project and install the necessary packages for the server.
1mkdir realtime-dashboard-server2cd realtime-dashboard-server3npm init -y4npm install express body-parser dotenv cors yahoo-finance2 node-fetch
Explanation:
- express: A web application framework for setting up the server.
- body-parser: Middleware to parse incoming JSON request bodies.
- dotenv: Loads environment variables from a
.env
file. - cors: Middleware to enable Cross-Origin Resource Sharing.
- yahoo-finance2: Library for fetching stock data from Yahoo Finance.
- node-fetch: Fetch API for making HTTP requests.
2. Set Up the Express Server
Create a file named server.js
and configure the server.
1// server.js2import express from "express";3import bodyParser from "body-parser";4import cors from "cors";5import dotenv from "dotenv";6import yahooFinance from "yahoo-finance2";78dotenv.config();910const app = express();11app.use(bodyParser.json());12app.use(cors());1314const subscriptions = [];
Explanation:
- Express App: Create an Express application to handle requests.
- Middlewares: Use
bodyParser
for JSON parsing andcors
for handling cross-origin requests. - Subscriptions: An array to store active stock subscriptions, identified by room IDs.
3. Subscribe to Stock Updates
Define an endpoint to subscribe to stock updates.
1app.get('/subscribe', async (req, res) => {2console.log(req.query)34if(!req.query.symbol) {5return res.status(400).json({ error: 'Missing symbol' })6}78try {9const response = await yahooFinance.quote(req.query.symbol)1011if(!response) {12return res.status(404).json({ error: 'Symbol not found' })13}1415subscriptions.push({16roomId: req.query.roomId,17symbol: req.query.symbol18})1920return res.json({21symbol: response.symbol,22name: response.shortName,23price: response.regularMarketPrice,24change: response.regularMarketChange,25changePercent: response.regularMarketChangePercent,26high: response.regularMarketDayHigh,27low: response.regularMarketDayLow,28updatedAt: new Date().toISOString(),29})30} catch (error) {31return res.status(500).json({ error: error.toString() })32}33})
Explanation:
- Subscribe Endpoint: A
/subscribe
endpoint allows clients to subscribe to stock updates by providing asymbol
androomId
. - Yahoo Finance API: The
yahooFinance.quote
method fetches the stock data using the provided symbol. - Response Data: If the stock is found, it adds a subscription and returns detailed stock data.
4. Unsubscribe from Stock Updates
Provide a way to unsubscribe from stock updates.
1app.get('/unsubscribe', (req, res) => {2if(!req.query.roomId) {3return res.status(400).json({ error: 'Missing roomId' })4}56if(!req.query.symbol) {7return res.status(400).json({ error: 'Missing symbol' })8}910const index = subscriptions.findIndex(subscription => subscription.roomId === req.query.roomId && subscription.symbol === req.query.symbol)11if(index === -1) {12return res.status(404).json({ error: 'Subscription not found' })13}1415subscriptions.splice(index, 1)16return res.json({ message: 'Subscription removed' })17})
Explanation:
- Unsubscribe Endpoint: A
/unsubscribe
endpoint allows clients to remove subscriptions byroomId
. - Find Subscription: It locates the subscription using the
roomId
and removes it if found.
5. Send Stock Updates to SuperViz
Use a timed interval to fetch stock updates and broadcast them using the SuperViz API.
1const interval = setInterval(async () => {2for(const subscription of subscriptions) {3try {4const stock = await yahooFinance.quote(subscription.symbol)56if(!stock) return78const data = {9symbol: stock.symbol,10name: stock.shortName,11price: stock.regularMarketPrice,12change: stock.regularMarketChange,13changePercent: stock.regularMarketChangePercent,14high: stock.regularMarketDayHigh,15low: stock.regularMarketDayLow,16updatedAt: new Date().toISOString(),17}18const channelId = 'stock-price'1920const response = await fetch(`https://api.superviz.com/realtime/${channelId}/publish`, {21method: 'POST',22headers: {23'Content-Type': 'application/json',24secret: process.env.VITE_SUPERVIZ_SECRET_KEY,25client_id: process.env.VITE_SUPERVIZ_CLIENT_ID,26},27body: JSON.stringify({28name: 'stock-update',29data,30})31})3233console.log(`Sending data to ${channelId}, stock: ${stock.symbol}`, response.status)34} catch (error) {35console.error(error)36}37}38}, 2000)
Explanation:
- Interval: Every 2 seconds, fetch stock updates for all subscriptions.
- SuperViz API: Send stock data to SuperViz's real-time API, using the
roomId
andchannelId
to target specific clients.
6. Start the Server
Launch the server to listen for requests.
1app.listen(3000, () => {2console.log("Server is running on <http://localhost:3000>");3});
Explanation:
- Server Listening: The server listens on port 3000 and logs a confirmation message when it's running.
Step 2: Setting Up the Frontend with React
The frontend uses React to display real-time stock updates by connecting to SuperViz Real-time.
1. Create a New React Project
Initialize a new React application using Create React App with TypeScript.
1npm create vite@latest2cd realtime-dashboard-frontend
2. Install SuperViz SDK
Add SuperViz and other necessary packages.
1npm install @superviz/realtime luxon uuid
Explanation:
- @superviz/realtime: SuperViz Real-Time library for integrating real-time synchronization into your application.
- luxon: DateTime library for formatting dates.
- uuid: Library for generating unique identifiers.
3. Configure tailwind
In this tutorial, we'll use the Tailwind css framework. First, install the tailwind package.
1npm install -D tailwindcss postcss autoprefixer2npx tailwindcss init -p
We then need to configure the template path. Open tailwind.config.js
in the root of the project and insert the following code.
1/** @type {import('tailwindcss').Config} */2export default {3content: [4"./index.html",5"./src/**/*.{js,ts,jsx,tsx}",6],7theme: {8extend: {},9},10plugins: [],11}
Then we need to add the tailwind directives to the global CSS file. (src/index.css)
1@tailwind base;2@tailwind components;3@tailwind utilities;
4. Set Up Environment Variables
Create a .env
file in the frontend directory and add the SuperViz API key.
1VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_API_KEY2VITE_SUPERVIZ_CLIENT_ID=YOUR_SUPERVIZ_CLIENT_ID3VITE_SUPERVIZ_SECRET_KEY=YOUR_SUPERVIZ_SECRET_KEY
Explanation:
- Environment Variables: Store the API key securely using
.env
and access it throughimport.meta.env
.
5. Define Common Types
Create a directory src/common
and add a types.ts
file to define types used across the application.
1// src/common/types.ts2export type Stock = {3symbol: string;4name: string;5price: number;6change: number;7changePercent: number;8high: number;9low: number;10updatedAt: string;11};
Explanation:
- Stock Type: Defines the structure for stock data, ensuring consistent use throughout the application.
6. Implement the Main App Component
Open src/App.tsx
and set up the main component to handle user interactions and display stock data.
1import { v4 as generateId } from "uuid";2import { useCallback, useEffect, useState } from "react";3import { Realtime } from "@superviz/realtime/client";4import { Stock } from "./common/types";5import { StockPrice } from "./components/stock-price";67const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;89export default function App() {10const [stock, setStock] = useState('AAPL')11const [stockList, setStockList] = useState<Stock[]>([])1213const subscribeToStock = useCallback(async () => {14const params = {15roomId: ROOM_ID,16symbol: stock,17}1819const url = new URL('http://localhost:3000/subscribe')20url.search = new URLSearchParams(params).toString()2122const response = await fetch(url, {23method: 'GET',24headers: {25'Content-Type': 'application/json',26}27})2829const data = await response.json()3031if(!data || stockList.includes(data.symbol)) return3233setStockList((prev) => [...prev, data])34}, [stock, stockList])35}
Explanation:
- State Management:
stock
holds the input symbol, whilestockList
maintains the list of subscribed stocks. - Subscribe Function: Constructs a URL with query parameters and fetches stock data from the server. Updates the state if the stock isn't already subscribed.
7. Initialize SuperViz for Real-Time data synchronization
Add the initialization logic to connect to SuperViz.
1const initialize = useCallback(async () => {2const realtime = new Realtime(apiKey, {3participant: {4id: generateId(),5name: "participant-name",6},7});89const channel = await realtime.connect("stock-price");10channel.subscribe("stock-update", (data) => {11console.log("New channel event", data);1213if (typeof data === "string") return;1415setStockList((prev) => {16return prev.map((stock) => {17const newStock = data.data as Stock;1819if (stock.symbol === newStock?.symbol) {20return newStock;21}2223return stock;24});25});26});27}, []);
Explanation:
- SuperViz Initialization: Connects to the SuperViz room using an API key and room details. Adds the Realtime component to handle real-time events.
- Realtime Subscription: Subscribes to
stock-update
events, updating the stock list with new data.
8. Render the UI Components
Finish the App
component by rendering the user interface.
1return (2<div className="w-full h-full bg-gray-200 flex items-center justify-center flex-col">3<header className="w-full p-5 bg-purple-400 flex items-center justify-between">4<div>5<h1 className="text-white text-2xl font-bold">6Realtime Data Dashboard7</h1>8</div>9<div>10<input11type="text"12value={stock}13onChange={(e) => setStock(e.target.value)}14className="p-2 border border-gray-400 rounded-md focus:outline-none focus:border-purple-400"15/>16<button17onClick={subscribeToStock}18className="p-2 bg-purple-500 text-white rounded-md ml-2 focus:outline-none"19>20Subscribe21</button>22</div>23</header>24<main className="flex-1 p-20 flex w-full gap-2">25{stockList.map((stock) => (26<StockPrice key={stock.symbol} stock={stock} />27))}28</main>29</div>30);
Explanation:
- UI Structure: The UI contains an input for stock symbols and a subscribe button. The
StockPrice
component is used to display each stock's details. - State Updates: The
onChange
event updates the stock input, while clicking the button triggers the subscription logic.
9. Implement the StockPrice Component
Create a src/components
directory and add a stock-price.tsx
file to define how each stock is displayed.
1// src/components/stock-price.tsx2import { Stock } from "../common/types";3import { DateTime } from "luxon";45type Props = {6stock: Stock;7};89export function StockPrice({ stock }: Props) {10const formatPrice = (price: number) => {11return new Intl.NumberFormat("en-US", {12style: "currency",13currency: "USD",14}).format(price);15};1617const formatDateTime = (date: string) => {18return DateTime.fromISO(date).toFormat("DD HH:mm:ss");19};2021return (22<div className="p-6 border border-solid border-gray-300 bg-white min-w-40 rounded-xl h-fit shadow-md">23<h1>{stock.name}</h1>24<p>{stock.symbol}</p>25<p>Current Price: {formatPrice(stock.price)}</p>26<p>Lower Price: {formatPrice(stock.low)}</p>27<p>Higher Price: {formatPrice(stock.high)}</p>28<p>Updated At: {formatDateTime(stock.updatedAt)}</p>29</div>30);31}
Explanation:
- StockPrice Component: Displays detailed stock information, including the name, symbol, current price, low/high prices, and updated timestamp.
- Formatting Functions:
formatPrice
andformatDateTime
ensure the prices and dates are displayed in a user-friendly format.
Step 3: Running the Application
To start the application, run this command in the terminal:
1npm run dev
This command will start both the server and the frontend application.
You can access the frontend application at http://localhost:5173
and the server at http://localhost:3000
.
Summary
In this tutorial, we've built a real-time stock dashboard using SuperViz, Express.js, and React. The server fetches stock data from Yahoo Finance and sends updates to subscribed clients using SuperViz's real-time API. The frontend subscribes to stock updates, displaying them in a responsive UI. By following these steps, you can customize the dashboard to track different stocks, add more features, and deploy it to a production environment.
Feel free to refer to the full code in the GitHub repository for more details.