Node.js / TypeScript quickstart
Compile a typed public-price request and WebSocket subscription with binance, then run it in Node.js. No API key is needed. Prices are BTCUSDT last traded prices.
Create the project
Use Node.js 24 with npm. Download the complete TypeScript starter, or copy the files below.
mkdir binance-typescript-quickstart
cd binance-typescript-quickstartCopy the files below, or extract the downloaded archive into this directory (adjust the download path if needed):
tar -xzf ~/Downloads/typescript.tar.gzInstall the dependencies after saving or extracting the files:
npm installThe SDK installs from latest and includes its type definitions. This starter uses TypeScript 6.0.3. Its market.ts imports the SDK's constructor types so the compiler checks the REST methods and subscription arguments against the installed package.
Project files
package.json
{
"name": "binance-typescript-quickstart",
"private": true,
"type": "module",
"scripts": {
"check": "tsc --noEmit",
"build": "tsc",
"start": "npm run build && node dist/prices.js"
},
"dependencies": {
"binance": "latest"
},
"devDependencies": {
"typescript": "6.0.3",
"@types/node": "24.13.2"
}
}market.ts
import type * as SDK from 'binance';
type Sdk = typeof SDK;
export const endpoints = {"rest": "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT", "websocket": "wss://stream.binance.com:9443"};
export function client(sdk: Sdk) { return new sdk.MainClient({}, {timeout:15000}); }
export async function read(client: InstanceType<Sdk['MainClient']>) {
const response = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' });
if (Array.isArray(response)) throw new Error('Expected one ticker');
return response.price;
}
export function stream(sdk: Sdk, logger?: ConstructorParameters<Sdk['WebsocketClient']>[1]) { return new sdk.WebsocketClient({}, logger); }
export const event = 'message';
export function value(message: any) { return message.e === '24hrTicker' ? message.c : undefined; }
export async function subscribe(ws: InstanceType<Sdk['WebsocketClient']>) { await ws.subscribeSpotSymbol24hrTicker('btcusdt'); }price.ts
import * as sdk from 'binance';
import * as market from './market.js';
function positivePrice(value: unknown): string {
if (!Number.isFinite(Number(value)) || Number(value) <= 0) {
throw new Error('The exchange did not return a positive BTC price.');
}
return String(value);
}
export async function readPrice(): Promise<string> {
return positivePrice(await market.read(market.client(sdk)));
}
// Returns cleanup without waiting for subscription acknowledgement.
export function watchPrice(onPrice: (price: string) => void, onError: (error: unknown) => void): () => void {
const ws = market.stream(sdk);
let stopped = false;
const receive = (message: Parameters<typeof market.value>[0]) => {
const value = market.value(message);
if (!stopped && value !== undefined) {
clearTimeout(deadline);
try { onPrice(positivePrice(value)); } catch (error) { fail(error); }
}
};
const fail = (error: unknown) => { if (!stopped) onError(error); };
const deadline = setTimeout(() => fail(new Error('No BTC update within 30 seconds. Check network access.')), 30000);
ws.on(market.event, receive);
ws.on('exception', fail);
// React may clean up an effect before its queued subscription starts.
Promise.resolve().then(async () => {
if (stopped) return;
try {
await market.subscribe(ws);
} finally {
// A connection may finish opening after cleanup was requested.
if (stopped) ws.closeAll();
}
}).catch(fail);
return () => {
if (stopped) return;
stopped = true;
clearTimeout(deadline);
ws.closeAll();
ws.removeListener(market.event, receive);
ws.removeListener('exception', fail);
};
}prices.ts
import process from 'node:process';
import { readPrice, watchPrice } from './price.js';
async function main() {
console.log('BTC REST price:', await readPrice());
let stop: (() => void) | undefined;
try {
const price = await new Promise<string>((resolve, reject) => {
stop = watchPrice(resolve, reject);
});
console.log('BTC WebSocket price:', price);
} finally {
stop?.();
console.log('WebSocket closed.');
}
}
main().catch(error => {
console.error(error.message || String(error));
process.exitCode = 1;
});tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": true,
"outDir": "dist",
"types": [
"node"
]
},
"include": [
"*.ts"
]
}Run
Check types without making any exchange requests:
npm run checkCompile and run:
npm startnpm start runs tsc and then node dist/prices.js. It stops on a compiler error. The script prints a REST price and one WebSocket price, closes the client in finally, and exits:
BTC REST price: 65000.5
BTC WebSocket price: 65001.2
WebSocket closed.The NodeNext compiler settings follow Node.js module resolution. Relative imports name the emitted .js files even though the source files end in .ts. The selected WebSocket event payload is an untyped boundary; the shared price helper validates the numeric value before presenting it.
Troubleshooting
- Run
npm run checkto see SDK method or argument errors before execution. Keep the includedtsconfig.jsonwhen copying this starter. - If Node cannot find
dist/prices.js, runnpm run buildfirst or usenpm start, which builds automatically. This recipe usestscfor type checking and compilation rather than relying on Node's type stripping. - If types cannot be resolved, run
npm installand keep both development dependencies inpackage.json. - For HTTP failures or no update within 30 seconds, allow the exchange endpoints in
market.tsfrom your network and region. See Runtime compatibility and Troubleshooting.