Vite (plain JavaScript) quickstart
Build a page that displays a public btcusdt REST price and live WebSocket updates from @siebly/htx-api. No API key is needed. Prices are btcusdt last traded prices.
Use Node.js 24 and npm. You can also view the complete HTX Vite example on GitHub.
See Runtime setup for runtime requirements.
The released SDK provides browser transport mappings. Keep the supplied Vite configuration, omit Node-only agents and keep credentials on your server. REST access depends on HTX CORS policy and regional availability. Public WebSocket messages require DecompressionStream support.
Create the project
mkdir htx-vite-quickstart
cd htx-vite-quickstart1. Create package.json
Declare the SDK dependency and the commands used by this project.
{
"name": "htx-vite-quickstart",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1"
},
"dependencies": {
"@siebly/htx-api": "latest",
"events": "3.3.0"
},
"devDependencies": {
"vite": "5.4.21"
}
}2. Install dependencies
Run this after saving package.json:
npm install3. Create vite.config.js
Configure the development server and production build.
import { fileURLToPath } from 'node:url';
export default {
// htx-api selects its browser transport through its package browser mappings.
optimizeDeps: {
exclude: ['@siebly/htx-api'],
include: ['events', '@siebly/htx-api > isomorphic-ws'],
},
resolve: {
alias: [
{
find: /^events$/,
replacement: fileURLToPath(
new URL('./node_modules/events/events.js', import.meta.url),
),
},
],
},
};4. Create main.js
Read the REST price, show WebSocket updates and close the connection when the user clicks Stop stream.
import { SpotClient, WebsocketClient } from '@siebly/htx-api';
const restOutput = document.querySelector('#rest');
const liveOutput = document.querySelector('#live');
const errorOutput = document.querySelector('#error');
const stopButton = document.querySelector('#stop');
let stopStream;
let userStopped = false;
function startStream() {
const ws = new WebsocketClient();
let stopped = false;
liveOutput.textContent = 'Connecting';
errorOutput.textContent = '';
function showError(error) {
console.error(error);
if (!stopped) {
errorOutput.textContent = error instanceof Error ? error.message : String(error);
}
}
async function loadPrice() {
const client = new SpotClient();
const response = await client.getTicker({ symbol: 'btcusdt' });
const price = response.tick.close;
if (!stopped) {
restOutput.textContent = String(price);
}
}
loadPrice().catch(showError);
const timeout = setTimeout(() => {
showError(new Error('No btcusdt update within 30 seconds.'));
}, 30_000);
ws.on('message', (message) => {
if (Array.isArray(message) || message.ch !== 'market.btcusdt.detail') {
return;
}
const tick = message.tick;
if (!tick || typeof tick !== 'object' || !('close' in tick)) {
return;
}
const price = tick.close;
if (!stopped && price) {
clearTimeout(timeout);
liveOutput.textContent = String(price);
}
});
ws.on('exception', showError);
Promise.resolve().then(async () => {
if (stopped) {
return;
}
try {
await Promise.resolve(ws.subscribe('market.btcusdt.detail', 'spotPublic'));
} finally {
if (stopped) {
ws.closeAll();
}
}
}).catch(showError);
return function stop() {
if (stopped) {
return;
}
stopped = true;
clearTimeout(timeout);
ws.closeAll();
liveOutput.textContent = 'Stopped';
};
}
function start() {
if (!stopStream && !userStopped) {
stopStream = startStream();
}
}
function stop() {
stopStream?.();
stopStream = undefined;
}
function stopByUser() {
userStopped = true;
stop();
}
function restore(event) {
if (event.persisted) {
start();
}
}
stopButton.addEventListener('click', stopByUser);
window.addEventListener('pagehide', stop);
window.addEventListener('pageshow', restore);
start();
if (import.meta.hot) {
import.meta.hot.dispose(() => {
stopButton.removeEventListener('click', stopByUser);
window.removeEventListener('pagehide', stop);
window.removeEventListener('pageshow', restore);
stop();
});
}5. Create index.html
Create the browser page that loads the application entry module.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Live price</title>
</head>
<body>
<h1>Live price</h1>
<p>REST: <output id="rest">Loading</output></p>
<p>WebSocket: <output id="live">Connecting</output></p>
<p id="error" role="alert"></p>
<button id="stop" type="button">Stop stream</button>
<script type="module" src="/main.js"></script>
</body>
</html>Run
npm run devOpen the URL printed by Vite, normally http://localhost:5173/. The page shows a REST price and a changing WebSocket price. Click Stop stream to close the client. Leaving the page or replacing the module during Vite development also closes the connection. If Back or Forward navigation restores a cached page, it starts a new subscription unless you clicked Stop stream.
To check the production bundle:
npm run build
npm run previewOpen the preview URL printed by Vite. Both price fields should contain positive numbers, such as 65000.5. REST and streaming prices may differ.
Troubleshooting
- An
eventsresolution error means the dependency or Vite config is missing. Copy the config exactly and restart Vite. - Run the page through Vite, rather than opening
index.htmldirectly. Check the browser network panel for blocked REST or WSS requests. The exchange must permit your origin and region. - Keep private keys and API credentials in a secure server-side environment, outside source files and browser bundles. This page uses public market data. See WebSocket subscriptions for subscription details.