Check peaq Mainnet RPC Health Before You Ship: A Node.js Preflight
Build a small Node.js 18+ preflight script that verifies a peaq mainnet RPC endpoint is reachable, returns the expected chain ID, and reports the latest block, with explicit failure handling for timeouts, HTTP errors, and JSON-RPC errors.
Before you point a production service at a peaq mainnet RPC endpoint, you want a fast, repeatable answer to three questions: does the endpoint respond, is it actually peaq mainnet, and is it still producing blocks? This guide gives you a single Node.js script that answers all three and fails loudly when something is wrong. It is a connectivity and identity check, not a performance benchmark — if you need latency numbers, the guide shows you how to measure them yourself rather than trusting anyone's claims.
First, separate RPC access from indexing
An RPC endpoint lets your code talk to a peaq node directly: you send JSON-RPC methods like eth_chainId, eth_blockNumber, or eth_getBalance and get a response. That is what this guide tests. Indexing is a different layer — a SubQuery-style indexer ingests chain data and exposes a GraphQL API so you can query historical or aggregated state without scanning blocks yourself.
The distinction matters for troubleshooting. If eth_blockNumber returns a healthy, advancing height but your GraphQL query returns stale rows, your RPC is probably fine and the problem is in the indexer's sync. Conversely, if the RPC call itself times out, no amount of indexer debugging will help. Test the RPC layer first, in isolation.
- RPC = live node calls via JSON-RPC (eth_chainId, eth_blockNumber, eth_getBalance).
- Indexing = pre-processed chain data served through a query API, typically GraphQL.
- A healthy RPC does not guarantee a healthy indexer, and vice versa — test them separately.
Get a peaq mainnet endpoint
You need an HTTP(S) JSON-RPC URL for peaq mainnet. Public endpoints exist, and managed providers offer dedicated ones. OnFinality lists peaq among its supported networks on the peaq network page, where you can review the network and find how to obtain an endpoint. Do not hardcode a URL you found in a random gist — treat the endpoint as configuration.
The script below reads the endpoint from an environment variable, so the same code works against a public endpoint, a managed endpoint, or a local node. Never commit the URL if it contains an API key.
- Store the endpoint in an environment variable such as PEAQ_RPC_URL.
- Keep API keys out of source control.
- The same script works for any EVM-compatible peaq mainnet endpoint.
The preflight script
This script uses only Node.js 18+ built-ins (global fetch and AbortController), so there is nothing to install. It performs three checks in order: chain identity, latest block, and a second block read after a short wait to confirm the height is advancing. Each JSON-RPC call has a timeout and distinguishes transport failures from JSON-RPC errors.
// preflight.mjs — Node.js 18+
const RPC_URL = process.env.PEAQ_RPC_URL;
if (!RPC_URL) {
console.error('Missing PEAQ_RPC_URL environment variable.');
process.exit(2);
}
const EXPECTED_CHAIN_ID = '0x' + (3338).toString(16); // peaq mainnet chain ID
async function rpc(method, params = [], timeoutMs = 8000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(RPC_URL, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
signal: controller.signal,
});
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText} from RPC endpoint`);
}
const body = await res.json();
if (body.error) {
throw new Error(`JSON-RPC error ${body.error.code}: ${body.error.message}`);
}
if (body.result === undefined) {
throw new Error(`Malformed JSON-RPC response for ${method}`);
}
return body.result;
} catch (err) {
if (err.name === 'AbortError') {
throw new Error(`Timeout after ${timeoutMs}ms calling ${method}`);
}
throw err;
} finally {
clearTimeout(timer);
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
const chainId = await rpc('eth_chainId');
if (chainId.toLowerCase() !== EXPECTED_CHAIN_ID.toLowerCase()) {
throw new Error(`Wrong network: expected ${EXPECTED_CHAIN_ID}, got ${chainId}`);
}
console.log(`chainId OK: ${chainId}`);
const first = await rpc('eth_blockNumber');
const firstHeight = Number.parseInt(first, 16);
console.log(`latest block: ${firstHeight}`);
await sleep(6000);
const second = await rpc('eth_blockNumber');
const secondHeight = Number.parseInt(second, 16);
console.log(`latest block after wait: ${secondHeight}`);
if (secondHeight <= firstHeight) {
throw new Error('Block height did not advance; endpoint may be stalled or lagging');
}
console.log(`OK: advanced ${secondHeight - firstHeight} block(s)`);
}
main().catch((err) => {
console.error('Preflight failed:', err.message);
process.exit(1);
});Run it with PEAQ_RPC_URL=https://your-endpoint node preflight.mjs. A healthy run prints the chain ID, the latest block, and the number of blocks advanced. Exit code 0 means all checks passed; exit code 1 means a check failed; exit code 2 means configuration is missing.
The chain ID check is the most important guard: it prevents you from accidentally sending transactions or queries to a testnet or a different EVM chain that happens to answer on the same URL.
Reading failures and measuring what matters
The script separates failure classes on purpose. An HTTP 401 or 403 usually means a bad or missing API key. A timeout means the endpoint is unreachable or overloaded from your network. A JSON-RPC error with a code and message means the node understood you but rejected the call — read the message. A block height that does not advance over your wait window suggests the endpoint is lagging or stalled; increase the wait before concluding, since block times vary.
If you want latency or reliability numbers, measure them yourself: wrap the rpc() call in a loop, record Date.now() deltas, and compute percentiles over a few hundred samples from your own deployment region. Do not rely on published benchmarks, including any you might read elsewhere — your network path is what matters.
When you are ready to move beyond raw RPC calls, the OnFinality RPC Assistant helps you work through endpoint setup and method selection, and the OnFinality Learn library covers indexing and querying patterns for when you need historical data rather than live node calls.
- HTTP 401/403 → credential problem.
- Timeout → reachability or load problem from your vantage point.
- JSON-RPC error object → the node rejected the call; read code and message.
- Flat block height → lagging or stalled endpoint; extend the wait window before concluding.
- Measure latency and uptime from your own environment with a sampling loop.
Your next step
Wire this preflight into your deploy pipeline or a cron job so a bad endpoint fails before your users see it. Then, once RPC health is confirmed, decide whether your feature needs live calls or indexed queries — and if it is the latter, start with the OnFinality Learn material on indexing rather than building a block scanner from scratch.
- Run the preflight on every deploy and on a schedule.
- Keep RPC and indexer health checks separate.
- Only add indexing once you know you need historical or aggregated data.