Vite (plain JavaScript) quickstart
Build a page that displays a public BTCUSDT REST price and live WebSocket updates from bitget-api. No API key is needed. Prices are BTCUSDT last traded prices.
Use Node.js 24 and npm. You can also view the complete Bitget Vite example on GitHub.
See Runtime compatibility for runtime requirements.
Keep the supplied Vite configuration: it resolves EventEmitter and rejects Node-only HTTPS agents. Browsers manage connections, so omit keepAlive. REST access depends on Bitget CORS policy; use a server route if blocked. Keep credentials on your server.
Create the project
mkdir bitget-vite-quickstart
cd bitget-vite-quickstart1. Create package.json
Declare the SDK dependency and the commands used by this project.
{
"name": "bitget-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": {
"bitget-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';
const browserAgent = '\0bitget-browser-agent';
const sdkRoot = fileURLToPath(new URL('./node_modules/bitget-api/', import.meta.url));
export default {
// Keep the same SDK transform during development and production builds.
optimizeDeps: {
exclude: ['bitget-api'],
include: ['events', 'bitget-api > isomorphic-ws'],
},
resolve: {
alias: {
events: fileURLToPath(new URL('./node_modules/events/events.js', import.meta.url)),
},
},
plugins: [{
name: 'bitget-browser-transport',
enforce: 'pre',
resolveId(source, importer) {
if (source === 'https' && importer?.startsWith(sdkRoot)) {
return browserAgent;
}
},
load(id) {
if (id === browserAgent) {
// Browsers manage connections themselves. Reject an unsupported option
// rather than presenting a Node Agent as a working browser transport.
return `export class Agent {
constructor() {
throw new Error('keepAlive and HTTPS agents are Node.js-only. Omit keepAlive in a browser.');
}
}
export default { Agent };`;
}
},
}],
};4. Create main.js
Read the REST price, show WebSocket updates and close the connection when the user clicks Stop stream.
import { RestClientV3, WebsocketClientV3 } from 'bitget-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 WebsocketClientV3();
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 RestClientV3();
const response = await client.getTickers({
category: 'SPOT',
symbol: 'BTCUSDT',
});
const price = response.data[0]?.lastPrice;
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('update', (message) => {
if (message.arg?.topic !== 'ticker') {
console.log('WebSocket update:', message);
return;
}
const price = message.data?.[0]?.lastPrice;
if (!stopped && price) {
clearTimeout(timeout);
liveOutput.textContent = String(price);
}
});
ws.on('exception', showError);
Promise.resolve().then(async () => {
if (stopped) {
return;
}
try {
await ws.subscribe({
topic: 'ticker',
payload: {
instType: 'spot',
symbol: 'BTCUSDT',
},
}, 'v3Public');
} 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; a successful bundle alone does not prove network access. - 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.