services
Get a key

library / Integrations / Game engines / I0108

Unity WebGL RPC CORS fix

A relay function that answers the browser's CORS preflight, forwards a short list of read methods to Carbium with your key added on the server, and refuses the rest. It comes with the UnityWebRequest setup and an in-process check.

By Carbium · Game engines · I0108 · updated 2026-11-22

01

Why the browser blocks the call

A browser build runs under the origin of the page that loaded it: scheme, host and port. When the build asks a different origin for data, the browser sends the request, reads the response headers, and hands the body to your code only if those headers name your origin. UnityWebRequest in a WebGL build goes through the browser's own network stack, so this rule applies to it in full. The console shows the blocked URL and a missing access-control-allow-origin header.

A JSON-RPC call adds a second hurdle. A body sent as application/json and a custom header such as x-api-key each make the request non-simple, so the browser first sends an OPTIONS preflight carrying access-control-request-method and access-control-request-headers. The real POST goes out only when the answer names that method and those headers. A 404, a redirect or a missing header in the preflight answer ends the call inside the browser, and the build sees a network failure with no status.

The key is the other half of the problem. Everything a WebGL build sends shows in the player's network tab, and limits are per account, so a key copied from one tab spends the budget your whole game shares. Carbium reads the key from the x-api-key header or from ?api-key= in the URL, and either one would ship to every player. A relay fixes both problems: the build calls a server you run, and that server adds the key.

$When the relay shares the game page's origin, the browser makes no cross-origin check and sends no preflight. The headers in the handler matter when the build is hosted on a static host and the relay lives on another origin of yours. The handler answers the same way in both layouts.
02

The relay handler

The relay is one function from Request to Response. A framework adapter, or a thin node:http wrapper you write, hands it a Request and sends back the Response. The check below calls the function directly, with no listener and no port.

  1. A request whose Origin is not GAME_ORIGIN gets 403 with no CORS headers.
  2. OPTIONS gets 204 with access-control-allow-origin set to the game's origin, access-control-allow-methods of POST, OPTIONS, access-control-allow-headers of content-type, and access-control-max-age of 600 so the browser caches the answer. vary: origin keeps a shared cache from handing one origin's answer to another.
  3. Any other verb except POST gets 405.
  4. A POST whose JSON method is off the allowlist gets 400, with the CORS headers attached so the game can read the refusal.
  5. An allowed call is rebuilt, sent to CARBIUM_RPC_URL with the key in x-api-key, and answered with Carbium's status and body plus the CORS headers. A retry-after hint is passed on.

The rebuilt body copies id, method and params from what the browser sent and nothing else, so extra fields cannot ride through. A JSON-RPC batch is an array, has no method of its own, and stops at the allowlist check.

CARBIUM_KEY is required and the file exits with a message when it is unset. CARBIUM_RPC_URL defaults to https://services.carbium.sh and GAME_ORIGIN to https://game.example.com; set it to the exact origin the build is served from. An address as the first argument picks the account the balance call reads. Node 24 strips the types on load and the file uses only the global fetch, Request and Response.

main.ts
// I0108 · Unity WebGL RPC CORS fix// https://carbium.sh/library/integrate/unity-webgl-rpc-cors-fix// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITconst key = process.env.CARBIUM_KEY ?? "";if (!key) {  console.error("Set CARBIUM_KEY to your Carbium key.");  process.exit(1);}const upstream = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const gameOrigin = process.env.GAME_ORIGIN ?? "https://game.example.com";const allowed = new Set(["getSlot", "getBalance", "getLatestBlockhash", "getAccountInfo"]);const cors = {  "access-control-allow-origin": gameOrigin,  "access-control-allow-methods": "POST, OPTIONS",  "access-control-allow-headers": "content-type",  "access-control-max-age": "600",  vary: "origin",};const reply = (status: number, body: string, extra: Record<string, string> = {}) =>  new Response(body, { status, headers: { ...cors, "content-type": "application/json", ...extra } });const refuse = (status: number, error: string) => reply(status, JSON.stringify({ error }));export async function relay(req: Request): Promise<Response> {  if (req.headers.get("origin") !== gameOrigin) return new Response('{"error":"origin not allowed"}', { status: 403 });  if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: cors });  if (req.method !== "POST") return refuse(405, "POST only");  const call = await req.json().catch(() => null);  const method = call?.method;  if (typeof method !== "string" || !allowed.has(method)) return refuse(400, "method not allowed");  try {    const up = await fetch(upstream, {      method: "POST",      headers: { "content-type": "application/json", "x-api-key": key },      body: JSON.stringify({ jsonrpc: "2.0", id: call.id ?? 1, method, params: call.params ?? [] }),      signal: AbortSignal.timeout(5_000),    });    const retry = up.headers.get("retry-after");    return reply(up.status, await up.text(), retry ? { "retry-after": retry } : {});  } catch {    return refuse(502, "upstream unreachable");  }}// The check: call the relay in process, as the browser would, with no listener.const url = "http://game.local/rpc";const address = process.argv[2] ?? "So11111111111111111111111111111111111111112";const rpc = (method: string, params: unknown[] = []) =>  new Request(url, {    method: "POST",    headers: { origin: gameOrigin, "content-type": "application/json" },    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),  });const preflight = new Request(url, {  method: "OPTIONS",  headers: {    origin: gameOrigin,    "access-control-request-method": "POST",    "access-control-request-headers": "content-type",  },});const checks: [string, Request][] = [  ["preflight", preflight],  ["getSlot", rpc("getSlot")],  ["getBalance", rpc("getBalance", [address, { commitment: "confirmed" }])],  ["sendTransaction", rpc("sendTransaction", ["AAAA"])],];for (const [label, req] of checks) {  try {    const res = await relay(req);    const text = await res.text();    const h = (name: string) => res.headers.get(name) ?? "none";    console.log(      `${label}: ${res.status} allow-origin=${h("access-control-allow-origin")} allow-methods=${h("access-control-allow-methods")} allow-headers=${h("access-control-allow-headers")}`,    );    console.log(`  ${text.slice(0, 120) || "(empty body)"}`);  } catch (e) {    console.log(`${label}: failed`, e instanceof Error ? e.message : e);  }}

run: node main.ts

node main.ts prints two lines per call: the label, the status and the three CORS headers, then the start of the body. Expect 204 for the preflight with the game's origin in allow-origin, 200 with a result for getSlot and getBalance, and 400 for sendTransaction with the same CORS headers on it. The balance call asks for confirmed commitment.

03

The method allowlist

The list decides what any script on the game's page can do with your key. The relay forwards getSlot, getBalance, getLatestBlockhash and getAccountInfo, which cover the chain reads a game screen usually needs. Every forwarded call spends cells, the admission charge per call, against one account budget.

MethodCells per callRelay
getSlot1forwarded
getAccountInfo10forwarded
getTransaction50refused until you add it
sendTransaction20 without preflight, 70 with itrefused

sendTransaction stays off the list. A send needs a transaction the player's wallet signed, and a relay open to every script on the page would let any of them spend your send budget at 20 or 70 cells a call. If the game sends, give that its own route behind your login.

When Carbium answers 429, the relay returns that status and the retry-after hint with the CORS headers attached. Without those headers the browser hides the status behind a generic network error, and the game cannot back off.

04

UnityWebRequest at the relay

Create the request with new UnityWebRequest(relayUrl, "POST"), set uploadHandler to an UploadHandlerRaw holding the UTF-8 bytes of the JSON, set downloadHandler to a DownloadHandlerBuffer, and call SetRequestHeader("Content-Type", "application/json"). Yield SendWebRequest() in a coroutine and read downloadHandler.text when it finishes. The body is the one the check sends, for example {"jsonrpc":"2.0","id":1,"method":"getSlot","params":[]}.

No x-api-key header goes in the Unity code and no key lives in the project. Content-Type is the only header the build sets, and it is the one the preflight answer lists.

A read answers with result, a failed call with error. A getBalance result holds context and value, where value is lamports. One SOL is 1,000,000,000 lamports, so a 32-bit int overflows at about 2.1 SOL: parse into a long or ulong.

Test from a WebGL build, served from the origin you put in GAME_ORIGIN. Play mode in the Unity editor does not enforce CORS, so a call that works there proves nothing. In the browser's network tab a working call shows an OPTIONS with 204 followed by the POST with 200.

05

Where it ends

  • The origin check keeps other web pages from using the relay through a browser. A script outside a browser can send any Origin header, so the check is no login. Put your own session check in front before real traffic.
  • It forwards single JSON-RPC calls for four methods. WebSocket subscriptions are another path; see Node WebSocket proxy for a server in the middle.
  • The relay forwards params as the game sends them. With no commitment in the params, the node's default of finalized applies.
  • There is no cache and no per-player limit. Every game call becomes one Carbium call, so a polling loop in the build counts against the account budget all keys share.
  • A changed CORS header can take up to 600 seconds to reach a browser that cached the preflight answer.
06

When it goes wrong

what goes wrongwhat to do
The console says No 'Access-Control-Allow-Origin' header is present on the relay's answer.GAME_ORIGIN differs from the page's origin. Match scheme, host and port exactly, with no trailing slash, then reload.
The console says the preflight response failed the access control check, with a 404 or 405 on the OPTIONS request.Your host routes only POST to the relay. Send OPTIONS to the same function.
The relay answers 403 origin not allowed from a local test build.The page runs on a development origin such as http://localhost with a port. Set GAME_ORIGIN to that origin while testing.
A method added in the Unity code answers 400 method not allowed.The method is off the allowlist. Add it to the set only after checking its cell cost and that a player's script should be able to call it.
The relay answers 502 upstream unreachable.The call timed out after 5 seconds or CARBIUM_RPC_URL is wrong. Run node main.ts on the server and read the failure it prints.
The relay passes on 401 with an unknown key message.CARBIUM_KEY is cut short or holds a different value. Set the whole key and restart.
07

Questions

Do I need the CORS headers when the relay sits on the game's own origin?

No. The browser sends no preflight and applies no cross-origin check to same-origin calls. The headers cost nothing there and make the same handler work if you later move the build to a separate static host.

Can I answer with `*` as the allowed origin?

You can, and then a page on any site can call the relay from a visitor's browser and spend your budget. Name the game's origin.

Why not send the key as `?api-key=` and skip the header?

That removes the custom header, and the JSON content type still triggers a preflight. It also puts the key in the build and in every URL the player's browser logs.

Can the relay send transactions for players?

Not as written. A send costs 20 cells without preflight and 70 with it, and it needs a signed transaction. Put it on a separate route behind your login.