Call a Solana RPC Method from Node.js

Use Node.js to call Solana’s getLatestBlockhash method, validate the JSON-RPC response, and distinguish live RPC access from indexed data queries.

To read Solana’s latest blockhash, send a JSON-RPC 2.0 request for getLatestBlockhash to a Solana RPC endpoint. This Node.js 18+ example reads the endpoint from an environment variable, checks HTTP and JSON-RPC errors, and prints the returned blockhash and last valid block height. Find a Solana network endpoint through OnFinality’s Solana network page, or use an endpoint from your existing provider.

Set your RPC endpoint

Set SOLANA_RPC_URL to the Solana RPC endpoint you are authorized to use. Keep any credentials in the endpoint or a secure configuration; do not commit them to source control.

  • This request reads current RPC data. RPC access does not by itself provide an indexed database or historical query interface. For indexed data, use an indexing service and query the data it has indexed.
bash
export SOLANA_RPC_URL='YOUR_SOLANA_RPC_ENDPOINT'

Replace the placeholder with your actual endpoint before running the script.

Request the latest blockhash

Save this as latest-blockhash.mjs and run it with Node.js 18 or later. The request uses the confirmed commitment and asks for the blockhash and last valid block height.

  • A successful result contains result.value.blockhash and result.value.lastValidBlockHeight. These values change over time, so the example checks their shape instead of assuming fixed values.
JavaScript · Node.js
const endpoint = process.env.SOLANA_RPC_URL;

if (!endpoint) {
  console.error('Set SOLANA_RPC_URL to your Solana RPC endpoint.');
  process.exitCode = 1;
} else {
  try {
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'getLatestBlockhash',
        params: [{ commitment: 'confirmed' }],
      }),
    });

    const text = await response.text();
    let payload;
    try {
      payload = JSON.parse(text);
    } catch {
      throw new Error(`RPC returned non-JSON content (HTTP ${response.status}).`);
    }

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${JSON.stringify(payload)}`);
    }
    if (payload.error) {
      throw new Error(`JSON-RPC error: ${JSON.stringify(payload.error)}`);
    }

    const value = payload.result?.value;
    if (typeof value?.blockhash !== 'string' ||
        typeof value?.lastValidBlockHeight !== 'number') {
      throw new Error('Response did not contain a blockhash and last valid block height.');
    }

    console.log(JSON.stringify({
      blockhash: value.blockhash,
      lastValidBlockHeight: value.lastValidBlockHeight,
    }, null, 2));
  } catch (error) {
    console.error(`Could not fetch the latest blockhash: ${error.message}`);
    process.exitCode = 1;
  }
}

Run node latest-blockhash.mjs. On success, expect a JSON object with a base58 blockhash string and a numeric lastValidBlockHeight; the exact values depend on when you make the request.

If the request fails, check that the endpoint is set correctly and reachable, that its credentials are valid, and that the provider accepts the method. The script reports HTTP errors, JSON-RPC errors, non-JSON responses, and unexpected result shapes.

Choose RPC access or indexed queries

Methods such as getLatestBlockhash are useful when an application needs a current value from a Solana RPC node. Other JSON-RPC methods can fetch account, transaction, or block data, subject to the method’s parameters and the endpoint’s available data.

When an application needs to filter or query a dataset built from blockchain events, RPC calls alone may not supply that indexed query layer. Review SubQuery Learn guides for indexing and query workflows, or use the RPC Assistant to explore RPC methods.