Verify a Bittensor WebSocket RPC Connection with Node.js
Connect to a Bittensor WebSocket RPC endpoint, identify the chain, and request the latest block header without assuming an endpoint or indexing service.
Use this guide to test a live Bittensor WebSocket RPC connection from Node.js 18+. The script calls standard Substrate JSON-RPC methods and prints the chain name plus the latest header. Start with the Bittensor network page to choose an RPC endpoint, then provide that endpoint through an environment variable rather than embedding an unverified URL.
Prepare the RPC URL
A WebSocket RPC endpoint provides request-and-response access to a node. It is not the same as an indexer: this example reads node state directly, while historical, relational, or application-specific queries generally require you to index data or use a query service.
Set BITTENSOR_WS_URL to the WebSocket URL supplied by your node provider or self-hosted node. Do not assume that an HTTP URL can be changed to ws or wss by editing its scheme; use the provider's documented WebSocket address.
- Use a
wss://endpoint when your environment requires an encrypted connection. - Keep credentials out of source control; pass them through environment variables or your runtime's secret manager.
- Install the
wspackage before running the script.
npm init -y
npm install ws
export BITTENSOR_WS_URL='wss://your-bittensor-websocket-endpoint'
node bittensor-rpc-check.jsReplace the placeholder value with a real endpoint before running the command. The example does not claim that placeholder URL is a working service.
Request the chain name and latest header
Save the following as bittensor-rpc-check.js. It sends two standard JSON-RPC requests over one WebSocket connection and fails clearly when the URL is missing, the socket times out, the server closes the connection, or the RPC returns an error.
system_chainidentifies the connected chain as reported by the node.chain_getHeaderrequests the current best header known to that node.- The returned block number is hexadecimal and is converted to decimal only for readability.
const WebSocket = require('ws');
const url = process.env.BITTENSOR_WS_URL;
if (!url) {
console.error('Missing BITTENSOR_WS_URL. Set it to a documented Bittensor WebSocket RPC URL.');
process.exit(1);
}
let parsed;
try {
parsed = new URL(url);
if (!['ws:', 'wss:'].includes(parsed.protocol)) throw new Error('URL must use ws:// or wss://');
} catch (error) {
console.error(`Invalid BITTENSOR_WS_URL: ${error.message}`);
process.exit(1);
}
const socket = new WebSocket(parsed.toString());
const pending = new Map();
let nextId = 1;
let settled = false;
function fail(message) {
if (settled) return;
settled = true;
for (const request of pending.values()) clearTimeout(request.timer);
pending.clear();
console.error(message);
try { socket.terminate(); } catch {}
process.exitCode = 1;
}
function rpc(method, params = []) {
return new Promise((resolve, reject) => {
const id = nextId++;
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`Timed out waiting for ${method}`));
}, 15000);
pending.set(id, { resolve, reject, timer });
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }), (error) => {
if (error) {
clearTimeout(timer);
pending.delete(id);
reject(error);
}
});
});
}
socket.on('open', async () => {
try {
const chain = await rpc('system_chain');
const header = await rpc('chain_getHeader');
const numberHex = header.result?.number;
if (typeof chain.result !== 'string' || typeof numberHex !== 'string') {
throw new Error('The node returned an unexpected JSON-RPC result shape');
}
console.log(JSON.stringify({
chain: chain.result,
latestHeader: header.result,
blockNumberDecimal: Number.parseInt(numberHex, 16)
}, null, 2));
settled = true;
socket.close();
} catch (error) {
fail(`RPC check failed: ${error.message}`);
}
});
socket.on('message', (data) => {
let message;
try {
message = JSON.parse(data.toString());
} catch {
fail('RPC check failed: received invalid JSON');
return;
}
if (message.id == null || !pending.has(message.id)) return;
const request = pending.get(message.id);
pending.delete(message.id);
clearTimeout(request.timer);
if (message.error) {
request.reject(new Error(`${message.error.code}: ${message.error.message}`));
} else {
request.resolve(message);
}
});
socket.on('error', (error) => fail(`WebSocket error: ${error.message}`));
socket.on('close', (code, reason) => {
if (!settled) fail(`WebSocket closed before completion (code ${code}${reason ? `: ${reason}` : ''})`);
});
setTimeout(() => {
if (!settled && socket.readyState !== WebSocket.OPEN) fail('Timed out connecting to the WebSocket RPC endpoint');
}, 15000);A successful response has the following structure, with values supplied by the connected node:
``json
{
"chain": "<chain name returned by the node>",
"latestHeader": {
"parentHash": "0x...",
"number": "0x...",
"stateRoot": "0x...",
"extrinsicsRoot": "0x...",
"digest": { "logs": [] }
},
"blockNumberDecimal": 123
}
``
The hashes, block number, and chain name are live results and will differ between runs; no fixed measurement is implied here.
Interpret the result and choose the next layer
If the script succeeds, you have verified transport, JSON-RPC request handling, and access to the node's current best header. That is sufficient for RPC operations such as reading chain state or submitting supported requests, but it does not create searchable history or decode application-level entities for you.
For indexing and application queries, define the data you need, index the relevant chain events or storage changes, and expose the resulting dataset through a query layer. Measure request latency, error rate, and historical coverage in your own environment rather than relying on assumptions about any provider.
- A timeout can indicate an unreachable endpoint, network policy, TLS issue, overloaded infrastructure, or a provider-side limit; compare with the provider's documentation and test from the same runtime environment.
- A JSON-RPC method error means the node rejected that request. Preserve the error code and message when troubleshooting.
- For endpoint discovery and RPC troubleshooting, use the OnFinality RPC Assistant. For broader implementation material, continue with OnFinality Learn.