JavaScript theorytheory 0/50 · 0%
Web3 · medium

37. Fetch and the JSON-RPC protocol

Talking to a node without a library.

Every EVM node speaks JSON-RPC over HTTP: a POST with `jsonrpc`, `method`, `params` and `id`. Results are hex strings you must decode yourself.

const res = await fetch(RPC, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [] }),
});
const { result } = await res.json();
console.log(BigInt(result));

Check both the HTTP status and the `error` field — a 200 response can still carry an RPC error.

Check your understanding

  1. 1. Which HTTP method does JSON-RPC use?

  2. 2. What format are numeric results in?

  3. 3. Can a 200 response contain an error?