services
Get a key

library / Integrations / Web frameworks / I0103

Next.js hydration-safe balances

A hydration-safe balance for a Next.js page: one getBalance snapshot read on the server, passed to the client as strings, rendered by one pure format function on both sides, then refreshed after mount from your own route.

By Carbium · Web frameworks · I0103 · updated 2026-11-22

01

What makes the two renders differ

Hydration compares the HTML the server produced with what the client's first render produces. When a text node differs, React logs "Hydration failed because the initial UI does not match what was rendered on the server" and renders that part of the tree again on the client, so the server markup you paid for is thrown away and the page can flash.

A balance is an easy place to trigger it, because the string on screen depends on more than the chain. Four causes cover almost every report:

  • A fetch on each side. The server reads the balance at one slot, the browser reads it a moment later, and a busy address changes in between. A slot is about 200 ms, so the two numbers can differ.
  • Locale formatting. toLocaleString() with no locale argument uses the default of the runtime: the Node process on the server and the visitor's browser setting on the client. 1,234.5 and 1.234,5 are both correct and both different.
  • State that only the browser has. A wallet adapter connection, localStorage and window do not exist during the server render, so text built from them before mount can differ on the first client render.
  • Time and randomness. A relative label such as "3 s ago" is computed twice, at two different moments.

All four share one shape: the two renders received different inputs, or the formatting step read something outside its inputs. The fix is to give both renders the same input and to format it with a function that reads nothing else.

02

The snapshot props

The server component reads the balance once and builds a small props object: the owner address, the lamports as a string and the slot of the read as a string. It passes that object to the client component. The client component renders those props and does not fetch anything during its first render, so its first output is computed from the same three strings the server used.

The getBalance call goes to https://services.carbium.sh with the key in the x-api-key header, from the server only. With commitment left out, @solana/kit 8.6.0 sends confirmed. The answer carries the balance in value and the slot it was read at in context.slot, both as bigint.

The format function takes the lamport string and returns text. It uses BigInt division and remainder, groups the whole part with a regular expression, and cuts the fraction to four digits. It has no Date, no Math.random, no Intl and no access to window, so the same string in gives the same text out in any runtime. The label also carries the slot, which tells a reader how old the number is.

03

The file

Install with npm install @solana/[email protected], set CARBIUM_KEY and run it with a wallet address. It makes the one read, then renders the props twice. The first render stands for the server. The second takes the props through JSON.stringify and JSON.parse, the way they travel to the browser, and stands for the first client render.

main.ts
// I0103 · Next.js hydration-safe balances// https://carbium.sh/library/integrate/next-js-hydration-safe-balances// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  isAddress,} from "@solana/kit";type Props = { owner: string; lamports: string; slot: string };// Pure: the same props give the same text in any runtime. No Date, Math.random, Intl or window.export const formatSol = (lamports: string): string => {  const v = BigInt(lamports);  const whole = (v / 1_000_000_000n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");  const frac = (v % 1_000_000_000n).toString().padStart(9, "0").slice(0, 4);  return `${whole}.${frac} SOL`;};export const render = (p: Props): string => `${formatSol(p.lamports)} at slot ${p.slot}`;const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY.");  process.exit(1);}const owner = process.argv[2];if (!owner || !isAddress(owner)) {  console.error("Usage: node main.ts <wallet address>");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);function show(props: Props) {  const server = render(props);  // The props travel to the browser as JSON, so the client render starts from the parsed copy.  const client = render(JSON.parse(JSON.stringify(props)) as Props);  console.log(`server: ${server}`);  console.log(`client: ${client}`);  console.log(`equal: ${server === client}`);  try {    JSON.stringify({ lamports: BigInt(props.lamports) });  } catch (e) {    console.log(`bigint props: ${(e as Error).message}`);  }  const sol = Number(props.lamports) / 1e9;  const fmt = (loc: string) =>    sol.toLocaleString(loc, { minimumFractionDigits: 4, maximumFractionDigits: 4 });  console.log(`locale en-US: ${fmt("en-US")}`);  console.log(`locale de-DE: ${fmt("de-DE")}`);  console.log(`locale equal: ${fmt("en-US") === fmt("de-DE")}`);}// commitment left out: kit 8.6.0 sends confirmedconst props = await rpc  .getBalance(address(owner))  .send({ abortSignal: AbortSignal.timeout(8_000) })  .then(    (r): Props => ({ owner, lamports: r.value.toString(), slot: r.context.slot.toString() }),    (e: unknown) => {      console.error(`getBalance failed: ${String(e)}`);      return undefined;    },  );if (props) show(props);else process.exitCode = 1;

run: node main.ts 5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9

The two strings come out identical and equal: true prints. A second block then formats the same balance with toLocaleString for en-US and de-DE. Those two differ, which is what a server in one locale and a browser in another produce when the component formats on both sides. In your app, copy formatSol and render into the module the server and client components share.

04

BigInt across the server boundary

@solana/kit returns lamports and slots as bigint. Calling JSON.stringify on an object that holds one throws TypeError: Do not know how to serialize a BigInt, and the file prints that message so you can see it. Pages Router props from getServerSideProps must be JSON serializable, so a bigint there is refused the same way.

Convert at the boundary with toString() and convert back inside the format function with BigInt(text). A string crosses every path the page can take: props, a __NEXT_DATA__ payload, a cache entry, and the JSON body of your own refresh route in the next section.

Converting to Number instead loses digits once a balance passes 9,007,199,254,740,991 lamports, about 9.0 million SOL. Large treasuries and exchange wallets pass that line. Keep integers as strings and BigInt until the last step, then format. BigInt lamport amounts goes deeper on the arithmetic.

05

Refreshing after mount

Once the page has hydrated, the number can move. A useEffect in the client component runs only after hydration, so a state change there is an ordinary update and raises no mismatch. The effect calls a route handler of yours, such as /api/balance?owner=, and that handler makes the Carbium call with the key. The browser never holds the key.

Replace the snapshot only when the route answers with a higher slot. Compare the two slot strings with BigInt. Two refreshes can return out of order, and a late answer from an earlier slot would otherwise put an older balance on screen.

Wallet state belongs here too. The connected wallet is known after mount, so the component holds the page's snapshot first, then sets the connected owner in an effect and fetches for it. The first client render never reads the adapter.

Many visitors multiply the calls. Past its rate a call gets 429 with a retry-after hint, and every key on the account shares one budget. Cache the route handler for a second or two so ten polls from ten visitors become one call, and poll on an interval of seconds. For the refresh that follows a confirmed transaction, see React post-confirm balance refresh.

06

Where it ends

  • The snapshot is as old as the render. A page cached at the edge shows an old balance until the effect replaces it, and the slot in the label shows how old.
  • The first paint shows the snapshot, then the refreshed number replaces it. Expect a visible change on a busy address.
  • suppressHydrationWarning silences the warning for one element and leaves the text different. It does not patch the mismatch.
  • The fixed format is one style for every visitor. For the visitor's own locale, format after mount in an effect and accept a second paint.
  • Only the SOL balance is covered. Token balances are separate calls and need the same string handling for their raw amounts.
  • A plain SOL wallet sends nothing on accountSubscribe. A live view needs a server process that watches logsSubscribe mentions and calls getBalance when one arrives, with the pushes going to the page over your own channel.
  • The file simulates the two renders in Node. Load the page in your app with the browser console open to confirm the mismatch is gone.
07

When it goes wrong

what goes wrongwhat to do
The console shows "Hydration failed because the initial UI does not match what was rendered on the server" after a balance component is added.Compare the page source with the first client render of that node. The usual causes are a locale formatter, a fetch on both sides or a value read from the wallet adapter. Pass the server's snapshot as props and format it with one pure function.
TypeError: Do not know how to serialize a BigInt while building props.Lamports and slots from @solana/kit are bigint. Call toString() on each before they reach props or a JSON response, and use BigInt(text) where you need the number again.
A very large balance ends in wrong last digits.The code converted the lamports to Number, which holds integers exactly only up to 9,007,199,254,740,991. Keep the value as a string or BigInt and divide with BigInt arithmetic.
The warning is gone after suppressHydrationWarning, but the number on screen changes a moment after load.The attribute only hides the message. The client text still differs from the server text. Remove it and render the snapshot props on the first client render.
The refresh route answers 429 once the page has traffic.Every open page polls on its own. Cache the route handler for a second or two, lengthen the interval, and check how many keys on the account share the budget.
The route answers 401.The key is missing where the server runs, or it is cut short. Set it in the host's environment and attach the whole key. An unknown key gets 401.
08

Questions

Does fetching in useEffect avoid the hydration error?

Yes. An effect runs after hydration has finished, so the state change it makes is a normal update. The first render still has to match the server, which is why it uses the snapshot props.

Why not format with Intl on the server and send the string?

That works and the two sides then agree. Every visitor sees the server's locale, though. For the visitor's locale, format in an effect after mount.

Can the client component call Carbium directly for the refresh?

It can, and the key would ship in the bundle to every visitor. Keep the call in a route handler or server component and let the browser call your own route.

Will connecting a wallet adapter cause a mismatch?

Only if the first render reads the connection. Hold the page's snapshot at first, then set the connected address in an effect and fetch the balance for it.