services
Get a key

library / AI and blockchain / Solana agent kits / SI0124

Agent kit on serverless routes

A route handler that imports the kit on first use, caches one Carbium client per warm instance, keeps the key in a server-side env var, and reports which reads failed. It replaces a clusterApiUrl call.

By Carbium · Solana agent kits · SI0124 · updated 2026-11-23

01

Replacing clusterApiUrl

Code written for @solana/web3.js often starts with clusterApiUrl("mainnet-beta"), which returns the address of a public cluster. Loading it on demand with const { clusterApiUrl } = await import("@solana/web3.js") inside a function works in a route handler, and the address it hands back is still that public one. An agent kit running inside a Next.js route should read its endpoint from configuration instead. The same code then points at Carbium in production and at a local validator on a laptop, and nothing in the route names a host.

The Carbium RPC endpoint is https://services.carbium.sh. The key travels in the x-api-key header, so the endpoint string carries no secret and can sit in a log line or an error message without harm.

The file below is read only. It builds the client with @solana/kit 8.6.0, answers one request shaped like a route handler, and signs and sends nothing. If your kit ships sending tools, keep them out of the model's tool list; Agent kit RPC setup covers the full setup for a kit.

02

Importing the client lazily

await import("@solana/kit") inside a function loads the package the first time something calls it. A route that never touches Solana, a health check for example, never pays for the load. Node caches the module after the first import, so later calls resolve at once.

Serverless platforms start a new instance when traffic grows and reuse a warm one while it lives. Module scope survives between requests on a warm instance, so the client belongs there. Two details keep it safe.

  • Store the promise of the client. Two requests that arrive together on a cold instance then await the same build, and the package is imported once.
  • Clear the stored promise when the build fails. Without that, one failed import is remembered for the life of the instance and every later request fails with it.
$Mark a route that uses this file with export const runtime = "nodejs" in Next.js. Node.js is already the default runtime for route handlers, and the line keeps the route there if a later edit sets edge.
03

The route file

One file, and @solana/kit 8.6.0 is the only dependency. CARBIUM_KEY must be set, and the file exits with a message when it is not. CARBIUM_RPC_URL overrides the endpoint, which defaults to the address above. In a Next.js project, the GET function moves into app/api/chain/route.ts and reads the address from the request. There the missing-key check returns a 500 response, since process.exit would stop the whole server.

main.ts
// SI0124 · Agent kit on serverless routes// https://carbium.sh/library/si/agent-kit-on-serverless-routes// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Lazy Carbium client for a serverless route. Run: CARBIUM_KEY=... node main.ts [address]const key: string = process.env.CARBIUM_KEY ?? "";if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";let builds = 0;async function build() {  const { createDefaultRpcTransport, createSolanaRpcFromTransport } = await import("@solana/kit");  builds += 1;  return createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));}// Module scope survives on a warm instance. Store the promise so first requests share one build.let client: Promise<Awaited<ReturnType<typeof build>>> | undefined;export function getRpc() {  client ??= build().catch((e: unknown) => {    client = undefined; // a failed import is retried, not remembered    throw e;  });  return client;}// The shape of a Next.js route handler: GET in app/api/chain/route.ts.export async function GET(addr: string): Promise<Response> {  const { address } = await import("@solana/kit");  const rpc = await getRpc();  // No commitment named: kit 8.6.0 sends confirmed.  const [slot, info] = await Promise.allSettled([    rpc.getSlot().send(),    rpc.getAccountInfo(address(addr), { encoding: "base64" }).send(),  ]);  const account = info.status === "fulfilled" ? info.value.value : null;  return Response.json({    slot: slot.status === "fulfilled" ? String(slot.value) : null,    account: account      ? { lamports: String(account.lamports), owner: account.owner, executable: account.executable }      : null,    failed: [slot, info].flatMap((r) => (r.status === "rejected" ? [String((r.reason as Error).message)] : [])),  });}if (import.meta.main) {  const addr = process.argv[2] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";  for (const label of ["first", "second"]) {    const start = performance.now();    const res = await GET(addr);    console.log(`${label} request ${Math.round(performance.now() - start)} ms`, JSON.stringify(await res.json()));  }  console.log(`client builds: ${builds}`);}

run: node main.ts

Pass a public address as the first argument; the default is the USDC mint. The script calls GET twice to stand in for two requests on one warm instance, prints how long each took with its JSON body, then prints how many times the client was built. The build count is 1 after both calls, and the body holds the slot, the account's lamports as a string, its owner, and a failed list.

The slot and the lamports print as strings because kit returns both as bigints, and JSON.stringify throws on a bigint. Promise.allSettled keeps one failed read from taking the other down: the slot can arrive while the account read reports an error.

04

Where the key lives

Next.js ships a variable to the browser only when its name starts with NEXT_PUBLIC_. Call the key CARBIUM_KEY, set it in the host's environment settings for the deployment, and read it only in route handlers and server components. A client component that imports the file would run it in the browser, where CARBIUM_KEY is undefined and every read fails. Put import "server-only" at the top of the file in the Next.js project, and the build stops when a client component imports it.

RPC also accepts the key as ?api-key= in the URL. A kit that takes only an endpoint string needs that form, and the header form is the better choice whenever the kit accepts a client or a transport. A key in a URL appears wherever the URL is logged.

Return only what the route chooses to return. The handler sends the error message of a failed read, never the raw error object, so a failure shown to the model or the browser carries a sentence and nothing else.

05

What a route costs

Carbium charges each call in cells, and each plan has a requests-per-second ceiling per call class. The handler makes two calls: getSlot is a cheap cached read at 1 cell, and getAccountInfo is an account read at 10. One request to the route costs 11 cells.

CallCellsFree (req/s)Dev (req/s)Business (req/s)Pro (req/s)
getSlot1530100500
getAccountInfo100.51550400

The limits apply per account, and an account's keys share one budget. Caching a client inside one instance saves a package load and a transport build on each request, and it saves no cells. Ten instances answering at once draw on the same budget, so the route's own response cache is where the saving comes from.

A route that reads the address from the request runs on every call, so export const revalidate does not cache it. Return a Cache-Control: public, s-maxage=10 header and the CDN in front of the deployment keeps each address's response for ten seconds. A cached response that is ten seconds old is about 50 slots behind, since a slot lasts about 200 ms. Choose the number from how stale the page may be.

A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. Each class keeps its own bucket. Every request draws 10 cells from the account-read class, so about 102 requests that land together empty it on Free, Dev and Business, and 400 do on Pro. Past that the account reads run at the plan's rate while getSlot keeps answering; on Free that is one account read every two seconds.

06

Where it ends

  • The cached client lives in one instance. A cold start builds it again, and two instances share nothing, so the module cache is a speedup and holds no state you can rely on.
  • The route does no queuing. Past the plan's rate a call waits at most once and then fails, and the handler reports that failure in failed. Cap how many reads a tool loop makes per request.
  • A serverless instance is frozen or stopped between requests, so a WebSocket subscription does not belong in a short-lived route. Free carries 5 sockets per account, and one socket per warm instance would exhaust that quickly. Run a long-lived listener in a process that stays up and have the route read its output.
  • The file reads only. sendTransaction is served on the same endpoint, so keeping a model away from it is your code's job.
  • getTokenLargestAccounts and getProgramAccountsV2 are not served and answer -32601. A kit tool built on one fails on every call.
07

When it goes wrong

what goes wrongwhat to do
The route works in next dev and answers Cannot find module '@solana/kit' once deployed.Move the package from devDependencies to dependencies, and import it only in server files so the client bundle never resolves it.
Every call from the deployed route answers 401 UNKNOWN_KEY while the same code works locally.The deployment's CARBIUM_KEY holds a cut-off or wrong value, often from a paste into the host's settings. Set the whole key for that environment and redeploy.
The first request after a quiet period is slower than the rest.The instance imported the package and opened a connection on that request. Later requests on the warm instance skip both. A response served from the CDN cache through s-maxage skips the instance altogether.
Reads start answering 429 when traffic grows, though each instance sends few calls.All instances draw on one account budget. Put a response cache in front of the route and cap the reads one tool loop may make.
The key shows up in the browser's network tab or the page source.The variable name starts with NEXT_PUBLIC_, so Next.js wrote its value into the browser bundle at build time. Rename it to CARBIUM_KEY, put a new key in it, and redeploy; every visitor could read the old one.
A kit tool answers -32601 on every call.The method is not served. Do not retry it, and remove the tool from the model's list.
08

Questions

Does the dynamic import change anything on the Carbium side?

No. It decides only when your instance loads the package. Carbium sees the same calls with the same header either way.

Why not keep calling clusterApiUrl?

It returns the address of a public cluster and knows nothing about a Carbium key. Read the endpoint from CARBIUM_RPC_URL and send the key in x-api-key.

Which commitment does the route read at?

Confirmed. @solana/kit 8.6.0 fills it in when a call leaves commitment out. Pass commitment: "finalized" in a call that needs the other level.

Can I put the key in the URL for a kit that takes only a string?

Yes, as ?api-key= on the endpoint. Keep that URL out of logs and out of anything the model can read.