library / Integrations / I0034
Node WebSocket proxy
A short Node server accepts browser WebSocket connections, opens one Carbium WebSocket per client with your key attached, relays only subscription methods, and keeps the key out of the page. Run it once with --demo to watch four messages cross.
Why the key stays on the server
A browser WebSocket cannot set request headers, so the only places a Carbium key can travel from a page are the query string and the subprotocol list. Both end up in the page's source or its network tab. Anyone who opens developer tools reads the key and spends your credits with it. A server you run closes that gap: the page talks to your host, and your host talks to Carbium.
Carbium's WebSocket endpoint is wss://services.carbium.sh, and the key goes on the URL as ?api-key=. A subprotocol of api-key.<key> also works. The proxy builds the URL once from CARBIUM_KEY and never writes it to a log or sends it to a page.
The proxy also decides what a page may ask for. Every subscription is priced when it opens, by its filter weight, and a page with a free hand can open the heavy ones on your account. The code relays four subscription kinds and their unsubscribe calls, and the proxy answers anything else itself.
What the proxy does
Node 24 has a WebSocket client in the global scope and no server, so the file speaks the server half of the protocol itself: the HTTP upgrade handshake, then text frames. It adds no dependency.
- Each page that connects gets its own upstream connection to Carbium. Subscription ids belong to one connection, so they pass through unchanged and a page sees the ids Carbium chose.
- Messages a page sends before the upstream socket is open wait in a queue and go out in order once it opens.
- A message whose method is not in the allowlist never leaves the proxy. The page gets a JSON-RPC error with code -32601 and its own request id, written by the proxy.
- Everything Carbium sends comes back to the page as one text frame per message. A ping from the page gets a pong.
- When either side closes, the proxy closes the other, so no upstream socket outlives its page.
The allowlist holds the four subscription methods the browser needs most, each with its unsubscribe. The opening cost depends on the filter.
| Method | What a page receives | Credits to open |
|---|---|---|
| slotSubscribe | A notification for each slot the node sees. | 5 |
| signatureSubscribe | One confirmation for a signature, then the subscription ends. | 5 |
| accountSubscribe | Account state on change, for streamed accounts. | 25 |
| logsSubscribe | Transaction logs, all or filtered by mention. | 25 by mention, 200 for all logs |
A plain SOL wallet sends nothing on accountSubscribe. For wallet activity, the page subscribes with logsSubscribe and a mention of the wallet, then reads the balance with a getBalance call when a notification arrives. That call goes through your own RPC route, since this proxy carries subscriptions only.
The proxy
Save the file as main.ts and run it with Node 24, which strips the types on load. It needs CARBIUM_KEY and exits with a message when it is missing. CARBIUM_WS_URL and PORT are optional, and PORT defaults to 8900. The server binds to 127.0.0.1, so put a reverse proxy in front of it for outside traffic.
// I0034 · Node WebSocket proxy// https://carbium.sh/library/integrate/node-websocket-proxy// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createHash } from "node:crypto";import { createServer } from "node:http";import type { AddressInfo } from "node:net";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1);}const upstream = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}?api-key=${key}`;const demo = process.argv.includes("--demo");const port = demo ? 0 : Number(process.env.PORT ?? 8900); // the demo takes any free portconst allowed = new Set(["slot", "account", "logs", "signature"].flatMap((n) => [`${n}Subscribe`, `${n}Unsubscribe`]));// One unmasked server frame; op 1 is text, 8 close, 10 pong.function frame(op: number, data: Buffer): Buffer { const n = data.length; const head = Buffer.alloc(n < 126 ? 2 : n < 65536 ? 4 : 10); head[0] = 0x80 | op; if (n < 126) head[1] = n; else if (n < 65536) { head[1] = 126; head.writeUInt16BE(n, 2); } else { head[1] = 127; head.writeBigUInt64BE(BigInt(n), 2); } return Buffer.concat([head, data]);}const server = createServer((_req, res) => res.writeHead(426).end("WebSocket only"));server.on("upgrade", (req, sock) => { const wsKey = req.headers["sec-websocket-key"]; if (typeof wsKey !== "string") return void sock.destroy(); // your session check goes here too const accept = createHash("sha1").update(wsKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64"); sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); const up = new WebSocket(upstream); const queue: string[] = []; up.onopen = () => { for (const m of queue.splice(0)) up.send(m); }; up.onmessage = (e) => sock.write(frame(1, Buffer.from(String(e.data)))); up.onerror = () => console.error("upstream error"); // never print the URL: it carries the key up.onclose = () => sock.end(frame(8, Buffer.alloc(0))); const forward = (text: string) => { let msg: { id?: unknown; method?: unknown } = {}; try { msg = JSON.parse(text) ?? {}; } catch { /* answered below */ } if (typeof msg.method === "string" && allowed.has(msg.method)) { if (up.readyState === WebSocket.OPEN) up.send(text); else queue.push(text); } else { const error = { code: -32601, message: "method not allowed" }; sock.write(frame(1, Buffer.from(JSON.stringify({ jsonrpc: "2.0", id: msg.id ?? null, error })))); } }; let buf = Buffer.alloc(0); sock.on("data", (chunk: Buffer) => { buf = Buffer.concat([buf, chunk]); for (;;) { if (buf.length < 2) return; const op = buf[0] & 15; let len = buf[1] & 127; let off = 2; if (len === 126 && buf.length >= 4) { len = buf.readUInt16BE(2); off = 4; } else if (len === 127 && buf.length >= 10) { len = Number(buf.readBigUInt64BE(2)); off = 10; } else if (len >= 126) return; if (len > 65536) return void sock.destroy(); if (buf.length < off + 4 + len) return; const mask = buf.subarray(off, off + 4); const data = Buffer.from(buf.subarray(off + 4, off + 4 + len)); for (let i = 0; i < len; i++) data[i] ^= mask[i & 3]; buf = buf.subarray(off + 4 + len); if (op === 1) forward(data.toString()); else if (op === 9) sock.write(frame(10, data)); else if (op === 8) return void sock.end(frame(8, Buffer.alloc(0))); } }); sock.on("close", () => up.close()); sock.on("error", () => sock.destroy());});server.listen(port, "127.0.0.1", () => { const bound = (server.address() as AddressInfo).port; console.log(`proxy listening on ws://127.0.0.1:${bound}`); if (!demo) return; const page = new WebSocket(`ws://127.0.0.1:${bound}`); let seen = 0; page.onopen = () => { page.send(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "programSubscribe" })); page.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" })); }; page.onmessage = (e) => { const m = JSON.parse(String(e.data)); // the proxy's own refusal is labeled, Carbium's messages are shown as they came console.log(m.error ? `refused by proxy (request ${m.id}): ${m.error.message}` : `page got: ${String(e.data).slice(0, 110)}`); if (++seen === 4) process.exit(0); }; setTimeout(() => { console.error("fewer than 4 messages in 20 s"); process.exit(1); }, 20_000);});
run: node main.ts --demo
Run it and point a page at it
Start it with node main.ts --demo. The flag makes the process listen on a free port of its own, so it never clashes with a proxy already running on 8900. It then connects a test page to itself, sends a programSubscribe and a slotSubscribe, prints the listening address, then four lines, and exits. The first of the four begins refused by proxy and is the proxy's own answer to programSubscribe, which is not in the allowlist. The next line is the subscription result with its id. The last two are slot notifications, cut to their first 110 characters, so each line ends at the notification's slot and the start of parent. Without the flag the server stays up and waits for pages.
A page connects to your host with new WebSocket("wss://your-host/") and sends the usual JSON-RPC subscribe message. The Solana kit browser client can point at the same URL for the four kinds in the allowlist. A page served over HTTPS refuses a plain ws:// address, so terminate TLS in a reverse proxy such as nginx or Caddy and forward the Upgrade and Connection headers to the port. Without those headers the request reaches Node as plain HTTP and gets the file's 426 answer.
Authentication belongs in the upgrade handler, before the 101 line is written. Check your own session cookie there and call sock.destroy() for a visitor you do not know. The key never reaches the page, but the proxy spends your credits for anyone it accepts.
What a relayed subscription costs
Every page holds one Carbium socket and every subscription on it is metered: the opening weight from the table, then 20 credits per MiB sent. A refused subscription costs nothing, and an accountSubscribe that never got a notification is refunded when it closes. The proxy adds no charge of its own.
A slot lasts about 200 ms, so an open slotSubscribe delivers around five notifications a second, and each page that subscribes receives its own copy through its own socket. Run a short session with a few pages open and read the credit meter afterwards before you size a plan.
Your plan caps connections and subscriptions per account, and Free carries 5 sockets. Limits are per account, so all keys on it share one budget. With one upstream socket per page, a Free account serves five pages at once. For a public site, pick a plan whose socket cap matches the pages you expect open together, or see Live mini explorer for a page that keeps a single subscription.
Where it ends
- One upstream socket per page, with no sharing. Sharing sockets would mean rewriting subscription ids on the way in and out, which the file does not do.
- The allowlist checks method names only. A logsSubscribe for all logs still opens at 200 credits. To forbid it, read params in forward and refuse what you do not want.
- No authentication, no TLS and no per-visitor limits. The file checks no Origin, so any site's page can open the proxy and spend your credits. An Origin check belongs in the upgrade handler next to the session check, and a script outside a browser still sets any Origin it likes.
- No reconnect upstream. When Carbium closes a socket the page's socket closes too, and the page reconnects and subscribes again. Notifications sent in between are lost.
- Client frames are read as whole text frames up to 64 KiB. Binary frames, fragmented messages and larger ones are dropped or closed.
- A gap in slot numbers on a slotSubscribe is normal: a slot whose leader produced nothing sends no notification, and a processed slot can later fall away when the cluster abandons its fork.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A page's socket opens and closes at once, and the proxy log shows upstream error. | Carbium refused the upstream connection. An unknown key gets 401 at the door, so check that CARBIUM_KEY holds the whole key and that CARBIUM_WS_URL, if set, is the wss address of the endpoint. |
| A page served over HTTPS throws a security error when it opens ws://your-host. | Browsers block plain WebSocket from a secure page. Put the proxy behind a reverse proxy that holds the certificate and connect to the wss:// address. |
| The browser shows a plain 426 response, or the handshake hangs, when the page connects through nginx. | The reverse proxy dropped the upgrade. Use HTTP 1.1 to the upstream and forward Upgrade and Connection, in nginx with proxy_http_version 1.1 plus proxy_set_header Upgrade $http_upgrade and proxy_set_header Connection upgrade. |
| A page receives {"error":{"code":-32601,"message":"method not allowed"}} for a method it needs. | The method is not in the allowlist. Add it to the list in main.ts once you have checked what it costs to open, and restart the proxy. |
| A subscription on a plain SOL wallet stays silent. | accountSubscribe sends state for streamed accounts only. Subscribe with logsSubscribe and a mention of the wallet, and read the balance with getBalance when a log arrives. |
| A sixth page's socket closes at once on a Free account. | The account is at its socket cap. Close idle pages with a timeout in your page code, or move to a plan with a higher cap. |
Questions
Why does the proxy use the query form of the key and not the subprotocol?
Both work. The query form is one string on the server and needs no subprotocol answer. The subprotocol keeps the key out of URLs that get logged, which matters only if you log upstream URLs, and this file does not.
Can the browser use the Solana kit subscriptions client with it?
Yes for the four subscription kinds in the allowlist: slot, account, logs and signature notifications. Point the client at your proxy's wss address and give it no key.
How many subscriptions can one page open?
The proxy sets no limit of its own. Your plan caps subscriptions per account, so the cap is shared by every page connected through the proxy.
Does the same proxy handle HTTP RPC calls from the page?
No. It carries WebSocket traffic only. A page's getBalance or getTransaction goes to a route on your server that calls Carbium with the x-api-key header.