Integration
Blockchain Integration for Web Applications
Practical patterns, pitfalls and a working code sketch for adding blockchain features to an existing product.
Adding blockchain capabilities to an existing product is rarely a matter of "installing Web3". It means introducing a new class of dependency, one that is asynchronous, public, costly to use and partly outside your control. Teams that treat it like an ordinary REST integration tend to discover the differences in production. This guide covers the integration patterns we see most often, the engineering details that decide whether they work reliably, and a testing approach that matches the risks.
Choose the smallest useful integration
Integrations fall along a spectrum of increasing risk and effort. It is worth being deliberate about where on the spectrum a feature really needs to sit.
| Level | What it does | Main new risks |
|---|---|---|
| 1. Read-only | Display balances, ownership, or contract data from the chain | RPC availability and rate limits; stale or inconsistent data |
| 2. Wallet sign-in | Let users authenticate by signing a message | Signature verification, replay, session handling, wrong network |
| 3. User-initiated writes | User signs transactions from their own wallet | Pending and failed transactions, gas, approvals, user error |
| 4. Platform-initiated writes | Your backend signs and sends transactions | Key custody, nonce management, fee spend, abuse and replay |
| 5. Custody or settlement | Your system holds or moves value on behalf of users | Regulatory scope, security of funds, reconciliation, incident response |
Many products create value at levels 1 to 3 and never need level 4 or 5. Moving up the list should be a conscious decision, not a side effect of a library choice.
Connecting to the chain: nodes and RPC providers
Your application talks to a blockchain through a node's JSON-RPC interface. Running your own full node gives maximum control but requires storage, bandwidth and operational skill, so most teams use a managed RPC provider. Whichever you choose, treat it exactly like any other critical third-party API:
- Set explicit timeouts and use retries with exponential backoff for idempotent reads.
- Handle rate-limit responses gracefully and cache results that are safe to cache, such as data from finalised blocks.
- Configure a secondary provider for failover. Libraries such as ethers include a fallback provider that queries several endpoints and compares answers.
- Keep API keys on the server. A key shipped in front-end code will be scraped and its quota used by others.
- Monitor latency, error rate and the lag between your provider's latest block and a reference source.
Wallet connection in the browser
Browser wallets expose a standard interface (EIP-1193) as window.ethereum, and mobile wallets connect through protocols such as WalletConnect. Modern libraries wrap this, but your own code must still handle the full range of states a wallet can be in. The sketch below shows a minimal, defensive write path using ethers v6:
import { BrowserProvider, Contract } from "ethers";
const abi = [
"function sign(string message) external",
"event Signed(address indexed visitor, uint256 indexed entryId, string message)"
];
export async function signGuestBook(contractAddress, text) {
if (!window.ethereum) throw new Error("NO_WALLET");
const provider = new BrowserProvider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const network = await provider.getNetwork();
if (network.chainId !== 11155111n) throw new Error("WRONG_NETWORK");
const signer = await provider.getSigner();
const contract = new Contract(contractAddress, abi, signer);
const tx = await contract.sign(text); // wallet prompt appears here
const receipt = await tx.wait(2); // wait for 2 confirmations
if (receipt.status !== 1) throw new Error("TX_REVERTED");
return receipt.hash;
}
The important details are in what the function does not assume. It checks that a wallet exists; it verifies the network instead of trusting whatever the wallet is set to; it waits for confirmations rather than returning when the transaction is merely broadcast; and it checks the receipt status because a mined transaction can still have reverted. In a real application each of those error codes should map to a clear message and a recovery action, such as a "switch network" button that calls wallet_switchEthereumChain.
User rejection is not an error. When someone declines a signature request, the wallet returns a specific code (4001 under EIP-1193, surfaced as ACTION_REJECTED in ethers). Do not log it as a failure or show a scary red banner. It is a normal user decision.
Listening to events and building your own view of the chain
For anything beyond simple reads, your backend should maintain its own database derived from contract events. The worker below shows the core pattern: process a range of blocks, store events under a unique key, and only advance a cursor once the range is safely processed.
// Backend worker (Node.js): index events safely
const CONFIRMATIONS = 12;
async function processRange(provider, contract, fromBlock, toBlock) {
const logs = await contract.queryFilter("Signed", fromBlock, toBlock);
for (const log of logs) {
await db.upsert("entries", {
txHash: log.transactionHash,
logIndex: log.index, // together these form a unique key
blockNumber: log.blockNumber,
visitor: log.args.visitor,
message: log.args.message,
});
}
}
async function tick() {
const head = await provider.getBlockNumber();
const safeHead = head - CONFIRMATIONS; // avoid unconfirmed blocks
const last = await db.getCursor("signed"); // last processed block
if (safeHead > last) {
await processRange(provider, contract, last + 1, safeHead);
await db.setCursor("signed", safeHead);
}
}
Three details make this robust:
- Confirmation depth. Blocks near the head can be replaced in a reorganisation. Indexing only up to
head - Navoids writing data that later disappears. Choose N based on the network and the value at stake. - Idempotent writes. The combination of transaction hash and log index uniquely identifies an event. Using an upsert means that reprocessing a range after a crash is harmless.
- Cursor persistence. The last processed block lives in your database, so a restart resumes where it left off instead of starting over or skipping blocks.
If you do need low-latency updates, you can add a WebSocket subscription as an optimisation, but keep the polling reconciler as the source of truth. Subscriptions drop silently, and a missed event with no reconciliation is a data-integrity bug.
Sending transactions from your backend
Platform-initiated writes (level 4) are where most serious engineering problems appear. The key points:
- Key management. A private key in an environment variable or repository is a breach waiting to happen. Use a hardware security module or a managed key service, apply least privilege, and separate keys by environment and by function.
- Nonce management. Each account must send transactions with sequential nonces. If two workers fetch the same nonce at once, one transaction will fail or replace the other. Serialise sending per account, or use a single sender service with a queue.
- Idempotency. Store the intended action, and its resulting transaction hash, before and after sending. On retry, check what already happened instead of sending again.
- Fee strategy. Use fee estimation with a safety margin, set sensible maximums so a gas spike cannot drain a hot wallet, and implement replacement ("speed up") with the same nonce for stuck transactions.
- Spending limits and alerts. A hot wallet should hold only what it needs, with automatic alerts on low balance and unusual activity.
Data accuracy: decimals, units and ids
Many production bugs have nothing to do with the chain itself. Token amounts are integers in the smallest unit (for example 18 decimals for many tokens), so the value 1.5 tokens is stored as 1500000000000000000. That exceeds JavaScript's safe integer range, so use BigInt or a decimal library and never floating-point numbers. Format for display only at the very last step. Different tokens use different decimals (stablecoins commonly use 6), so always read decimals() from the token instead of assuming 18. Finally, treat addresses as case-insensitive identifiers and normalise them to one format before storing or comparing.
Testing strategy
Match the test environment to the risk you are trying to reduce:
- Unit tests on contracts with a framework such as Foundry or Hardhat, including failure paths and permission checks.
- Local fork tests that run your integration against a copy of real chain state, so you can test interactions with existing contracts and tokens without spending real funds.
- Public testnet staging to exercise real wallets, real network latency and your deployment process end to end.
- Failure injection. Simulate RPC outages, delayed blocks, dropped transactions and reorgs. These are the scenarios that surface the bugs described above. Our guide to testing Web3 applications provides a checklist.
A go-live checklist
- Contracts tested, reviewed, and (for anything holding value) independently audited.
- Contract addresses and ABIs versioned and configured per environment, never hard-coded in several places.
- RPC failover tested by deliberately disabling the primary provider.
- Indexer lag monitored with an alert, and a documented procedure to re-index from a block height.
- Signing keys in managed custody, with rotation and revocation procedures written down.
- User-facing states for pending, failed, rejected and replaced transactions all designed and tested.
- An incident plan, including who can pause contracts or disable features, and how to communicate with users.
Key takeaways
- Start with the smallest integration that delivers value, usually read-only data, then add wallet connection and writes.
- Treat the RPC provider as a critical dependency: add timeouts, retries with backoff, rate-limit handling and a fallback.
- Never mark an action complete from a transaction hash alone. Wait for the receipt and a sensible number of confirmations.
- Keep private keys out of application code. Use a managed key service or hardware security module for backend signing.
- Test against a local fork and a public testnet, and include wallet-rejection, wrong-network and reorg scenarios.
Related guides
Further reading
- ethers.js v6 documentation
- EIP-1193: Ethereum Provider API
- Foundry Book (testing and forking)
- Hardhat documentation
About this guide. Written by the Kensaltensi engineering and QA team for educational purposes. Examples are illustrative, and standards evolve, so check the primary sources above before relying on a detail in production. If you spot an error or an out-of-date statement, email hello@kensaltensi.org and we will review and correct it.