services
Get a key

library / Integrations / I0037

Next.js server component reads

A server-side module for a Next.js app that reads one wallet's SOL balance and token holdings through Carbium in two parallel calls, sums split token accounts per mint, keeps the key out of the browser bundle and survives one failed call.

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

01

Where the read runs

An App Router page is a server component unless its own file starts with "use client". It is an async function, so it can await a Solana read in its body and return finished HTML. The browser receives markup and never opens a connection to the RPC endpoint.

Running the read on the server also keeps the key there. A key in client code ships to every visitor. A key read inside a server component stays on your server, and the page shows only what you choose to render from the answer.

The file below is one module that a page imports. It exports walletSummary(env, owner), which takes the environment as an argument, so the same function runs inside Next.js, in a route handler, or from the command line as a check. The page itself is a few lines: an async component that reads params, calls walletSummary(process.env, owner) and maps the result to JSX.

02

The Solana side: balance and holdings

The module makes two calls at once. getBalance returns the lamports of the wallet, where 1 SOL is 1,000,000,000 lamports. getTokenAccountsByOwner with the Token program id and jsonParsed encoding returns every classic token account the wallet owns, with the mint, the raw amount and the decimals already decoded by the node.

A wallet can own more than one token account for the same mint, so a list of accounts is not a list of balances. The module groups the accounts by mint and adds the raw amounts as bigint, then renders the sum next to the decimals. Amounts stay integer base units until the last step, so no float ever touches a balance.

The module drops mints whose summed amount is zero, reports how many remain in tokenMints, and returns only the first 10 of them in tokens. Change the slice in the file if your page needs more.

Token-2022 mints live under a second program id, and getTokenAccountsByOwner takes one program per call. This file reads the classic program only. Adding the Token-2022 program id is a second call of the same shape.

The module leaves commitment out of both calls. @solana/kit 8.6.0 then sends confirmed, while the JSON-RPC server alone would answer at finalized. The two calls are separate requests, so each answer carries its own slot and the two can differ by a slot. The module returns both slots instead of one.

03

The Carbium side: key, URL and one client

The endpoint is https://services.carbium.sh and the key travels in the x-api-key header. The module builds its client with createDefaultRpcTransport and createSolanaRpcFromTransport and passes the key as that header. A URL accepts ?api-key= too, but URLs end up in logs, so the header is the better place. When CARBIUM_KEY is missing, the module throws Set CARBIUM_KEY before any call goes out.

In Next.js, keep the key in .env.local as CARBIUM_KEY and leave off the NEXT_PUBLIC_ prefix. Next.js inlines only prefixed variables into the browser bundle, so an unprefixed one exists on the server alone. Put import "server-only" at the top of the copy in your app: the build then fails if a client component ever imports the module.

Connections stay open 600 s and TLS sessions resume, so Carbium asks callers to reuse one client. The module keeps the client in a module variable. A long-lived Node server shares it across requests. On a serverless host each warm instance builds its own once.

04

The file

Install with npm install @solana/[email protected]. In your app, save it as lib/carbium.ts. For the local check, set CARBIUM_KEY and run the file as main.ts with a wallet address: the command-line branch runs only for a file with that name, so node lib/carbium.ts exits silently. Node 24 strips the types on load.

main.ts
// I0037 · Next.js server component reads// https://carbium.sh/library/integrate/next-js-server-component-reads// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  isAddress,} from "@solana/kit";type Env = { CARBIUM_KEY?: string; CARBIUM_RPC_URL?: string };type Parsed = { info: { mint: string; tokenAmount: { amount: string; decimals: number } } };const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const connect = (env: Env) => {  if (!env.CARBIUM_KEY) throw new Error("Set CARBIUM_KEY");  return createSolanaRpcFromTransport(    createDefaultRpcTransport({      url: env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",      headers: { "x-api-key": env.CARBIUM_KEY },    }),  );};let rpc: ReturnType<typeof connect> | undefined; // one client per server process// Call from a server component: await walletSummary(process.env, owner)export async function walletSummary(env: Env, owner: string) {  rpc ??= connect(env);  const who = address(owner);  const opts = { abortSignal: AbortSignal.timeout(8_000) };  // commitment left out: kit 8.6.0 sends confirmed  const [bal, tok] = await Promise.allSettled([    rpc.getBalance(who).send(opts),    rpc.getTokenAccountsByOwner(who, { programId: TOKEN_PROGRAM }, { encoding: "jsonParsed" }).send(opts),  ]);  const errors: string[] = [];  if (bal.status === "rejected") errors.push(`getBalance: ${String(bal.reason)}`);  if (tok.status === "rejected") errors.push(`getTokenAccountsByOwner: ${String(tok.reason)}`);  // One wallet can own several token accounts for one mint: sum the raw amounts per mint.  const byMint = new Map<string, { amount: bigint; decimals: number; accounts: number }>();  if (tok.status === "fulfilled") {    for (const { account } of tok.value.value) {      const { info } = (account.data as unknown as { parsed: Parsed }).parsed;      const cur = byMint.get(info.mint) ?? { amount: 0n, decimals: info.tokenAmount.decimals, accounts: 0 };      cur.amount += BigInt(info.tokenAmount.amount);      cur.accounts += 1;      byMint.set(info.mint, cur);    }  }  const tokens = [...byMint]    .filter(([, t]) => t.amount > 0n)    .map(([mint, t]) => ({ mint, amount: t.amount.toString(), decimals: t.decimals, accounts: t.accounts }));  return {    owner,    lamports: bal.status === "fulfilled" ? bal.value.value.toString() : undefined,    balanceSlot: bal.status === "fulfilled" ? bal.value.context.slot.toString() : undefined,    tokensSlot: tok.status === "fulfilled" ? tok.value.context.slot.toString() : undefined,    tokenMints: tokens.length,    tokens: tokens.slice(0, 10),    errors,  };}// Node check only: node main.ts <wallet address>. Never reached inside Next.js.if (globalThis.process?.argv[1]?.endsWith("main.ts")) {  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 out = await walletSummary({ CARBIUM_KEY: key, CARBIUM_RPC_URL: process.env.CARBIUM_RPC_URL }, owner);  console.log(JSON.stringify(out, null, 1));}

run: node main.ts 5tzFkiKscXHK5ZXCGbXZxdw7gTjjD1mBwuoFbhUvuAi9

05

Using it from a page and caching the answer

A page that calls the module renders on the server for each request unless you opt into caching. For a wallet page that is often the wrong default: ten visitors in a second cost ten sets of Carbium calls for the same answer.

  • React's cache() around the wallet read removes duplicate calls within one render, for example when a header and a body both ask for the same wallet.
  • The use cache directive, or unstable_cache on older Next.js versions, keeps the result for a few seconds across requests. A short lifetime is enough, and balances look live to a visitor at that age.
  • revalidate on the route sets the same lifetime for a whole page.

Under use cache and unstable_cache the arguments of the wrapped function become the cache key. Wrap a function of one argument, such as (owner: string) => walletSummary(process.env, owner), and never walletSummary(env, owner) itself, or the whole environment, key included, lands in stored cache keys. Wrap that function, never the fetch inside the module. The module returns plain strings and arrays, which serialize cleanly into any of these caches. Amounts are already strings, so a bigint never reaches the cache layer.

Give the page a loading state with a loading.tsx file or a Suspense boundary around the wallet block. The shell then streams at once and the balance block fills in when the two calls return.

06

What it costs against your limits

Cells are the admission charge per call. Limits are per account, so every key on the account shares one budget, and a staging site and a production site on one account draw from the same pool.

Over its rate, a call gets a 429 with a `retry-after` hint. A server component has no good way to retry for the visitor, so the module lets the error surface in its errors list and the page renders what it has. Caching the page keeps a traffic spike from turning into two calls per visit. For watching the rate from outside the app, see RPC rate-limit alerts. For a one-token read without the grouping, see SPL token balance.

07

Where it ends

  • Run next build and load the page once to confirm the server-only import and the cache setup in your own app.
  • Only classic token accounts are read. Token-2022 holdings need a second call with that program id.
  • Amounts come back as raw base units and decimals. Names, logos and prices are not in this answer, so a mint label needs its own source.
  • A wallet with thousands of token accounts returns a large answer from the node, and the module hands back only the first 10 mints with a balance. Page on your side if you need the rest.
  • The read is a snapshot taken per request. It holds no WebSocket subscription, so a page that must update by itself needs a client component that polls your own route.
08

When it goes wrong

what goes wrongwhat to do
The build fails with a message that a client component imported a server-only module.A file with "use client" imports the module, directly or through another file. Move the call into a server component and pass the finished data down as props.
The page throws Set CARBIUM_KEY, or the request returns 401.The variable is missing where the server runs, or the key is cut short. Set it in the host's environment and restart, and attach the whole key. An unknown key gets 401.
The page works in next dev but answers 429 under traffic.Each visit makes two calls and nothing is cached. Cache the function for a few seconds, and check how many keys on the account share the budget.
The log shows -32601 for a method.Carbium does not serve that method. getTokenLargestAccounts and getProgramAccountsV2 are two of the methods it leaves out. A -32601 means do not retry. Use a served method, such as getTokenAccountsByOwner for holdings.
A wallet shows one mint twice in your own code, or a balance that looks too small.The wallet owns more than one token account for that mint. Group by mint and add the raw amounts, as the module does.
The page renders the SOL balance but an empty token list, and errors holds one entry.One call failed and the other succeeded. The entry holds the reason. A timeout or a 429 clears on the next cached refresh, and any other message means the request itself needs a change.
09

Questions

Can a client component call Carbium directly?

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

Should I use a route handler or a server component?

Use a server component when the data feeds a page you render. Use a route handler when client code, such as a polling widget, needs JSON from you. Both can import the same module.

Why does the module take `env` as an argument?

The module reads env on the first call and reuses the client it builds after that. The same function then runs in Next.js, in a script and in a test, and the page passes process.env while the command line branch builds its own object.

Does the wallet balance update while the page is open?

No. A server component answers once per render. For a live view, poll a route handler of yours from a client component, or open a WebSocket subscription from a server process of your own.