services
Get a key

library / Integrations / I0061

Angular RPC service

A small fetch-handler proxy that holds the Carbium key and allows only read methods, plus the Angular service that reads Solana through it from a production build, with signals for the results and no key anywhere in the bundle.

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

01

What the build flags do now

The command in the search comes from the webpack era of the Angular CLI. Projects created on recent versions build with the application builder, which runs on esbuild, and on that builder --build-optimizer is refused as an unknown argument before anything compiles. The other flags already hold: production is the default configuration of ng build, ahead-of-time compilation is on, and the production configuration turns optimization on. Plain ng build gives the same optimized output.

Look in angular.json under build for an application builder entry to see which one a project uses. Optimization shrinks and splits the code. It removes no value: every string in environment.ts or in a define entry stays in the output as readable text.

02

Why the key cannot live in environment.ts

environment.ts is compiled into the browser bundle, and so is every other value the build replaces into client code. A key placed there sits in a file each visitor downloads. Moving it into a request header from the browser changes nothing, because that header shows in the network tab of the developer tools.

So the browser sends its calls to a path on your own origin, here /solana, and a small handler on the server adds the key. The key lives in an environment variable on the host that runs the handler.

That handler is a public door to your account. Limits are per account and every key shares one budget, so a stranger who finds /solana spends your calls. The handler therefore answers reads only, chosen by method name, and refuses everything else.

03

The proxy handler

handle(request) takes a standard Request and returns a Response. It mounts in any server that speaks those types: a Node adapter, a worker, a serverless function or the SSR server of the Angular app. Under ng serve, point the dev server's proxyConfig at wherever it runs.

It answers POST only, parses the JSON-RPC body and checks the method of every call against a set. A batch may hold up to 100 calls and each one is checked, so one refused method refuses the whole batch. A refused call gets 403 and a JSON-RPC error body, and nothing goes upstream. An allowed call is forwarded to the RPC endpoint with the key in the `x-api-key` header, and the status and any retry-after header come back unchanged.

The file runs the handler with no listening socket. A small transport turns each kit call into a Request for handle, so main.ts exercises the code a browser request would reach. It prints the current slot, the five newest signatures of a busy program, the SOL balance of the fee payer of one of those transactions, and a closing line that says the allowlist refused a sendTransaction call.

Set CARBIUM_KEY, install @solana/[email protected] and run the file with the address of a busy program. Node 24 strips the types on load.

main.ts
// I0061 · Angular RPC service// https://carbium.sh/library/integrate/angular-rpc-service// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createSolanaRpcFromTransport, isAddress } from "@solana/kit";const key = process.env.CARBIUM_KEY ?? "";if (!key) {  console.error("Set CARBIUM_KEY.");  process.exit(1);}const program = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";if (!isAddress(program)) {  console.error("Usage: node main.ts [program address]");  process.exit(1);}const UPSTREAM = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const ALLOWED = new Set(["getSlot", "getBalance", "getAccountInfo", "getSignaturesForAddress", "getTransaction", "getLatestBlockhash"]);const APP = "http://app.local/solana";const reply = (status: number, message: string) =>  Response.json({ jsonrpc: "2.0", id: null, error: { code: -32601, message } }, { status });// The fetch handler: mount it behind /solana on any host that speaks Request and Response.export async function handle(req: Request): Promise<Response> {  if (req.method !== "POST") return reply(405, "POST only");  const body: unknown = await req.json().catch(() => null);  const calls: { method?: unknown }[] = Array.isArray(body) ? body : [body as { method?: unknown }];  if (!calls.length || calls.length > 100 || !calls.every((c) => typeof c?.method === "string" && ALLOWED.has(c.method))) {    return reply(403, "method not allowed by this proxy");  }  const up = await fetch(UPSTREAM, {    method: "POST",    headers: { "content-type": "application/json", "x-api-key": key },    body: JSON.stringify(body),  }).catch(() => null);  if (!up) return reply(502, "upstream unreachable");  const headers = new Headers({ "content-type": "application/json" });  const wait = up.headers.get("retry-after");  if (wait) headers.set("retry-after", wait);  return new Response(await up.text(), { status: up.status, headers });}// Kit client whose transport calls the handler in process: no socket, same bodies a browser sends.const rpc = createSolanaRpcFromTransport(async <T>({ payload }: { payload: unknown }): Promise<T> => {  const res = await handle(new Request(APP, { method: "POST", body: JSON.stringify(payload) }));  return (await res.json()) as T;});const step = async <T>(name: string, run: () => Promise<T>): Promise<T | undefined> => {  try {    const out = await run();    console.log(name, JSON.stringify(out, (_, v) => (typeof v === "bigint" ? v.toString() : v)));    return out;  } catch (e) {    console.log(name, "failed:", String(e));  }  return undefined;};await step("getSlot", () => rpc.getSlot().send());const sigs = (await step("getSignaturesForAddress", () => rpc.getSignaturesForAddress(program, { limit: 5 }).send())) ?? [];// The newest transaction that comes back names the fee payer (its first account key).type Parsed = { transaction: { message: { accountKeys: { pubkey: string }[] } } } | null;let payer: string | undefined;for (const { signature } of sigs) {  try {    const tx = await rpc.getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();    payer = (tx as unknown as Parsed)?.transaction.message.accountKeys[0]?.pubkey;    if (payer) break;  } catch (e) {    console.log("getTransaction failed:", String(e));  }}if (payer && isAddress(payer)) await step("getBalance", () => rpc.getBalance(address(payer)).send());else console.log("no fee payer found");const send = { jsonrpc: "2.0", id: 1, method: "sendTransaction", params: ["AA=="] };const refused = await handle(new Request(APP, { method: "POST", body: JSON.stringify(send) }));console.log(refused.status === 403 ? "sendTransaction refused: off the allowlist" : "sendTransaction was not refused");

run: node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4

Every call leaves commitment out, so kit sends `confirmed` where the server alone would answer at finalized. Each step runs in its own try, so one failed call prints its reason and the rest still print.

The signature list comes from an address index that keeps up to 30 days. main.ts reads only the five newest, so it stays inside that window. The index lists signatures below the validator's ledger floor, so getTransaction can answer null for an older one. The loop skips nulls and takes the first transaction that comes back, and the fee payer is its first account key. The call carries maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and a missing value answers -32015 for one.

04

The Angular side

In the app, the same kit calls live in one service class. It takes the proxy URL as a plain string constructor argument and builds its client once with createDefaultRpcTransport({ url }) and createSolanaRpcFromTransport. Its methods write into signals: a slot signal starts as null, and a refreshSlot() method awaits rpc.getSlot().send() and sets it.

The class carries no decorator. Provide it in app.config.ts with { provide: SolanaService, useFactory: () => new SolanaService(new URL('/solana', location.origin).href) }. The absolute URL comes from the page's own origin, so the same build runs on any host.

A component reads the service with inject(SolanaService), calls a method from a button or ngOnInit, and the template reads slot(). A signal write schedules the view update, so this path needs no async pipe. A test overrides the provider with a fake and never touches the network.

05

Where it ends

  • The file runs under Node; the Angular app takes the undecorated class with a useFactory provider, your proxy route and the signal or async pipe wiring.
  • The allowlist checks method names and leaves parameters alone. A visitor can ask for any account's data through an allowed read, and those calls draw on your account's budget. Put a session check or a per-visitor limit in front of /solana when the app is public.
  • The set holds reads. A dApp that signs in the browser needs sendTransaction on it, and from then on the handler forwards signed transactions for anyone who can reach it.
  • A signature page that comes back empty past 30 days marks the address index's age limit; the address may have older transactions.
  • The handler covers HTTP calls. A WebSocket takes the key in its URL, so a live subscription from the browser needs its own relay.
  • Run ng build --help on your CLI: a flag it does not list is refused. After a production build, search dist/ for the first characters of the key, and run the same search once on a throwaway build with the key in environment.ts, so you know the search can find one.
06

When it goes wrong

what goes wrongwhat to do
ng build stops with Unknown argument: build-optimizer.Drop the flag. It belongs to the webpack browser builder, and the esbuild application builder has no such option. ng build already compiles ahead of time and optimizes in the production configuration.
The build fails with NG2003 on the service, no suitable injection token for a string parameter.A decorated class with a string constructor parameter has nothing for Angular to inject. Remove @Injectable() and build the instance in a useFactory provider.
The browser gets 403 from /solana with the message that the proxy does not allow the method.The method is outside the set in the handler. Add it if it is a read you want to expose. sendTransaction is left out on purpose.
The proxy answers 401 on every call.The key is wrong or cut short in the environment of the host that runs the handler. Attach the whole key; an unknown key gets 401.
Pages work for one tester and answer 429 under real visitors.Every visitor draws on one account budget through the handler. The retry-after header is passed through, so back off on it, and keep results in signals instead of calling on every render. Check how many keys the account has, since they share the limit.
getTransaction answers null for a signature the list returned.The address index reaches below the validator's ledger floor, so an older signature can be listed without a transaction behind it. Handle null and read newer signatures.
07

Questions

Do I still pass `--configuration production` to `ng build`?

Current projects default to the production configuration, so plain ng build produces the optimized bundle. Pass the flag only when your angular.json sets another default.

Can the handler run inside the Angular SSR server?

Yes. It takes a Request and returns a Response, so you route /solana to it from the server file. The key then stays in that process and the browser still sees only your own path.

Why does `main.ts` use its own transport instead of `createDefaultRpcTransport`?

It calls handle in process, so the check needs no port. The Angular service uses createDefaultRpcTransport with the proxy URL, and both sides send the same JSON-RPC bodies.

Can I restrict the key and keep it in `environment.ts`?

No. Whatever the browser holds, every visitor can read and reuse, and the calls bill to your account. Keep the key on the server and let the allowlist set what the browser may ask for.