React quickstart
Display public BTC REST and WebSocket prices from bitget-api in a React component. No API key is needed. Prices are BTCUSDT last traded prices. This is a React browser app built with Vite; the plain JavaScript Vite guide uses DOM elements directly.
Use Node.js 24 and npm. You can also view the complete Bitget React 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-react-quickstart
cd bitget-react-quickstart1. Create package.json
Declare the SDK dependency and the commands used by this project.
{
"name": "bitget-react-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",
"react": "19.2.0",
"react-dom": "19.2.0",
"events": "3.3.0"
},
"devDependencies": {
"vite": "5.4.21",
"@vitejs/plugin-react": "4.7.0"
}
}2. Install dependencies
Run this after saving package.json:
npm install3. Create sdk.vite.config.js
Resolve the SDK imports that need browser support. Keep this configuration when using the SDK in Vite.
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 vite.config.js
Configure the development server and production build.
import { mergeConfig } from 'vite';
import react from '@vitejs/plugin-react';
import sdkConfig from './sdk.vite.config.js';
export default mergeConfig(sdkConfig, {
plugins: [react()],
});5. Create App.jsx
Build the React screen. The effect makes the REST request, subscribes to prices and closes the WebSocket on unmount.
import { useEffect, useState } from 'react';
import { RestClientV3, WebsocketClientV3 } from 'bitget-api';
function Prices() {
const [restPrice, setRestPrice] = useState('Loading');
const [livePrice, setLivePrice] = useState('Connecting');
const [error, setError] = useState('');
useEffect(() => {
let mounted = true;
const ws = new WebsocketClientV3();
function showError(error) {
console.error(error);
if (mounted) {
setError(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 (!price) {
throw new Error('No price was returned.');
}
if (mounted) {
setRestPrice(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 (mounted && price) {
clearTimeout(timeout);
setLivePrice(String(price));
}
});
ws.on('exception', showError);
// React can clean up an effect before its subscription starts.
Promise.resolve().then(async () => {
if (!mounted) {
return;
}
try {
await ws.subscribe({
topic: 'ticker',
payload: {
instType: 'spot',
symbol: 'BTCUSDT',
},
}, 'v3Public');
} finally {
// Close again if pending setup completed after unmount.
if (!mounted) {
ws.closeAll();
}
}
}).catch(showError);
return () => {
mounted = false;
clearTimeout(timeout);
ws.closeAll();
};
}, []);
return (
<section>
<p>BTCUSDT REST price: <output aria-label="REST price">{restPrice}</output></p>
<p>BTCUSDT WebSocket price: <output aria-label="WebSocket price">{livePrice}</output></p>
<p role="alert">{error}</p>
</section>
);
}
export default function App({ pageActive = true }) {
const [running, setRunning] = useState(true);
return (
<main>
<h1>BTCUSDT price</h1>
{running && pageActive ? <Prices /> : <p>Stream stopped. WebSocket closed.</p>}
<button type="button" onClick={() => setRunning(!running)}>
{running ? 'Stop stream' : 'Start stream'}
</button>
</main>
);
}6. Create main.jsx
Mount the screen with StrictMode. Pause subscriptions while the browser caches the page, resume them on restoration and clean up when the page or entry module is discarded.
import { StrictMode } from 'react';
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const root = createRoot(document.getElementById('root'));
let disposed = false;
function render(pageActive) {
root.render(
<StrictMode>
<App pageActive={pageActive} />
</StrictMode>,
);
}
function dispose() {
if (disposed) {
return;
}
disposed = true;
window.removeEventListener('pagehide', hide);
window.removeEventListener('pageshow', show);
root.unmount();
}
function hide(event) {
if (event.persisted) {
// Finish effect cleanup before the browser freezes this page.
// Keep App mounted so its Stop/Start choice survives restoration.
flushSync(() => render(false));
} else {
dispose();
}
}
function show(event) {
if (event.persisted && !disposed) {
render(true);
}
}
render(true);
window.addEventListener('pagehide', hide);
window.addEventListener('pageshow', show);
if (import.meta.hot) {
import.meta.hot.dispose(dispose);
}7. 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>React price screen</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/main.jsx"></script>
</body>
</html>Run
npm run devOpen Vite's printed URL, normally http://localhost:5173/. Both price fields should display positive numbers such as 65000.5. Tap Stop stream to unmount the price component and close its WebSocket. Start stream mounts a new component and creates a fresh subscription.
The effect ignores REST responses that arrive after unmount. Its cleanup closes the client before the effect runs again and when the component unmounts. This also handles StrictMode’s extra setup and cleanup cycle in development.
The entry module pauses the price component when the browser caches the page for Back or Forward navigation. Restoring the page resumes it without changing your Stop/Start choice. The module unmounts the React root when the page is discarded or Vite replaces the entry module. See React's effect lifecycle.
Build and preview the production app:
npm run build
npm run previewTroubleshooting
- An
eventsresolution error means the dependency or Vite config is missing. Copy the config exactly and restart Vite. - A brief extra connection in development is expected under StrictMode. If updates continue after Stop stream, check that the component cleanup closes the client and ignores late updates.
- This example uses public market data only. Keep private keys and API credentials in a secure server-side environment, outside source files and browser bundles.
- For network failures, inspect the browser's HTTPS and WSS requests to the exchange. Exchange CORS and regional restrictions apply. See Runtime compatibility for browser configuration and WebSocket subscriptions for subscription details.