Inside the FrontendX In-Browser Compiler
The FrontendX in-browser compiler executes JavaScript, TypeScript, C, C++, Python, and Go locally using WebAssembly runtimes - esbuild and QuickJS for JS/TS, wasm-clang for C and C++, Pyodide for Python, and Yaegi for Go. No code ever leaves the device, but each runtime has hard limits: 10 second execution for JS and TS, 30 seconds for Python and C/C++, no browser or Node.js APIs, no third-party packages, and no interactive stdin for Go. Learn the execution path of each language, how it compares to server-based online judges, what is unsupported and why, and how code splitting, web workers, Cache Storage, and CDN-hosted runtime assets keep six compilers unloaded until you press Run.
The FrontendX in-browser compiler runs six languages - JavaScript, TypeScript, C, C++, Python, and Go - entirely inside your browser tab using WebAssembly runtimes. Your code is compiled and executed locally: it is never uploaded, never queued, and never billed against a shared server CPU. Each language gets a dedicated runtime with explicit limits: 10 seconds of execution for JavaScript and TypeScript, 30 seconds for Python and C/C++, and up to 2 minutes for Go. In exchange for zero server round trips, you give up the full host environment: no browser or Node.js APIs in JS/TS, no third-party Python packages, and no interactive stdin for Go yet.
This article walks the actual execution path of every language, compares the architecture with server-based online judges, documents what is deliberately unsupported, and explains how the platform keeps six compiler systems unloaded until you press Run.
What Is the In-Browser Compiler?
The compiler is a set of browser-side executor modules in apps/web/lib/ that share one entry point: runCompilerSource(language, code, stdin) in apps/web/lib/compiler/compiler-runtime.ts. It dispatches to one of five engines:
runCode()inapps/web/lib/executor.ts- JavaScript and TypeScriptrunCppCustomSource()andrunCppProblem()inapps/web/lib/cpp-executor.ts- C and C++runCProblem()inapps/web/lib/cpp-executor.tsplusbuildCHarness()inapps/web/lib/c-harness.ts- CrunPythonSuite()inapps/web/lib/python-executor.ts- PythonrunGoCustomSource()inapps/web/lib/go-executor.ts- Go
The public surface is the /online-compiler route (apps/web/src/routes/online-compiler.tsx), a Monaco editor with a language rail, a stdin box, an output console, and a per-language runtime limits card. Every executor logs the same claim, visible in the run output: "Execution mode: browser Web Worker singleton (no server API)". That phrase, generated in apps/web/lib/cpp-executor.ts, is the architectural contract: no code path in the compiler reaches a backend.
The full component map is available in the
.
The following interactive trace illustrates the first-run path in the browser. Select Next step to follow the active phase; later runs may reuse already cached assets.
Preparing interactive diagram...
The first run prepares a language runtime, compiles or initializes the source when required, then executes inside a browser worker. This is an illustrative sequence; actual caching and compilation steps depend on the language.
Capabilities. Six languages, each with starter templates, per-language draft persistence in localStorage, formatting via formatCompilerSource() in apps/web/lib/compiler/compiler-format.ts, stdin support for C++ (cin) and Python (input()), and an AI assistant that can read, edit, and run the editor contents through tools like read_code, replace_code, and run_code.
Limits, as shown in the route's LANGUAGE_CONFIG:
| Language | Engine | Time limit | Key restriction |
|---|---|---|---|
| JavaScript | QuickJS | 10 s | No browser or Node.js APIs |
| TypeScript | esbuild + QuickJS | 10 s | Same as JavaScript after transpile |
| C | wasm-clang | 30 s | stdin support "coming next" |
| C++ | wasm-clang | 30 s | First run slower while toolchain loads |
| Python | Pyodide 0.27.0 | 30 s | No third-party packages |
| Go | Yaegi WASM | 120 s | No interactive stdin yet |
The limits are not cosmetic. The language buttons show an "Unavailable" state when a browser lacks the required runtime, and the executors hard-fail with messages such as "WebAssembly is not supported in this browser." (apps/web/lib/executor.ts) and "Web Workers are not available in this browser." (apps/web/lib/python-executor.ts).
Browser Execution vs. Server-Based Judges
Traditional online judges (LeetCode, Codeforces, HackerRank) send your source to a server, compile it in a sandboxed container, run the test suite, and stream results back. The FrontendX compiler inverts that model.
Pros of in-browser execution:
- No queue, no round trip. Compilation starts the moment you press Run. There is no shared server pool, so there is no wait for a free slot and no network latency between each test case.
- Privacy by default. Code never leaves the device. Nothing is uploaded, logged, or stored server-side unless you explicitly save a solution.
- Zero server cost per run. The user's CPU pays for every compile and every test. A burst of 10,000 runs costs the platform nothing.
- Deterministic latency model. Every user gets the same architecture: their own hardware. No noisy-neighbor slowdown from other submissions sharing a container.
- Offline-friendly. The heavy runtime assets are cached in Cache Storage after the first load, so repeat runs work without re-downloading toolchains.
Cons of in-browser execution:
- Hardware variance. A phone with 1 GB of RAM compiles C++ at a fraction of the speed of a desktop with 16 GB. The executor adapts -
_getSafeMaxWorkers()inapps/web/lib/cpp-executor.tsreadsnavigator.hardwareConcurrencyandnavigator.deviceMemoryand caps worker count at 6, dropping to a single worker on low-memory devices - but results are inherently device-dependent. - No true isolation. QuickJS gives you a 64 MiB memory limit and an interrupt handler, but a browser tab cannot provide the container-grade CPU and memory guarantees of a server sandbox.
- Weak resource accounting. Memory deltas come from
performance.memory.usedJSHeapSize, a Chromium-only API. On Firefox and Safari the compiler simply reports no memory metric rather than fake one. - Big first-run downloads. The C/C++ toolchain is roughly 8 MB of wasm assets (clang.wasm, lld.wasm, sysroot.tar), and the Go runtime is a large WASM interpreter. Server judges amortize toolchains across all users; browsers download them per device.
- No rate-limit enforcement beyond the browser. Server judges can hard-cap submission counts; a local compiler cannot stop a user from running code 1,000 times, which is fine for learning but meaningless as a measured submission system.
The honest summary: browser execution trades fairness and precision of measurement for immediacy, privacy, and zero infrastructure cost. It is a learning tool, not a contest judge.
How JavaScript and TypeScript Run: esbuild + QuickJS
The JS/TS path in apps/web/lib/executor.ts is a three-stage pipeline: transpile, sandbox, execute.
Stage 1 - Transpile with esbuild-wasm. The first Run in a tab downloads /esbuild.wasm (initialized with initialize({ wasmURL: "/esbuild.wasm", worker: false })) and transforms the source with transform(source, { loader: "ts" | "js", target: "es2020", format: "esm" }). TypeScript never executes as TypeScript: esbuild strips types, and the online compiler wraps the user body in a function before dispatch. A strict type-check is available in the health-check path, where the full typescript compiler runs with strict: true and noLib: true over an in-memory program (runCodeHealthCheck() in apps/web/lib/executor.ts).
Two source rewrites happen before execution:
import ... from "@frontendxlab/dsa-js"lines are stripped and replaced with a comment - "all symbols are injected as globals into QuickJS". TheDSA_PRELUDE(apps/web/lib/dsa-prelude.ts) is evaluated inside the VM before user code, providingListNode,TreeNode, and the algorithm library without imports.exportstatements are commented out, because esbuild emits ESM exports that are illegal inside the QuickJS IIFE wrapper.
Stage 2 - Sandbox with QuickJS. quickjs-emscripten is imported lazily (ensureQuickJS()) and a fresh context is created per run. The runtime is configured with vm.runtime.setMemoryLimit(64 * 1024 * 1024) - a hard 64 MiB ceiling - and a console object is bound so console.log, console.warn, and console.error are captured per test case instead of hitting the real devtools console.
Stage 3 - Resolve and execute. The transpiled source is wrapped in an IIFE that returns the entry function through a resolution chain:
typeof __run!=='undefined'?__run:(typeof solve!=='undefined'?solve:(...))
The chain tries __run, solve, solution, main, run, fn, handler, then the problem's declared entry point. If none resolves to a function, the compiler scans the transpiled output with extractUserFunctionNames() and returns a helpful hint: "Function X not found or not exported. Available functions: ...". Each test case is executed with an interrupt handler that polls performance.now() against the timeout, so even an infinite loop is cut off at 10 seconds. Inputs are deserialized by type - arrays become linked lists, level-order arrays become binary trees - and outputs are serialized back before a deep equality comparison.
Why QuickJS and not the host JS engine? Running user code on the page's own JS engine would give it full access to document, fetch, and localStorage, and an infinite loop would freeze the tab. QuickJS is a small, embeddable ES2020 engine compiled to WASM. It cannot touch the host, its memory is capped, and its interrupt handler lets the executor kill runaway code deterministically. The trade-off is documented in the UI itself: "Browser and Node.js APIs are not available."
How C and C++ Run: wasm-clang in a Worker
C and C++ are the most impressive path. There is no cloud compiler: a full clang + lld toolchain runs as WebAssembly inside a dedicated worker thread.
Runtime assets. The toolchain lives at https://cdn.frontendx.dev/wasm-clang and consists of five files listed in PREFETCH_FILES in apps/web/lib/cpp-executor.ts: shared.js, clang.wasm, lld.wasm, memfs, and sysroot.tar. On localhost these are proxied same-origin so a stale CDN edge response without CORS headers cannot break development; in production they are fetched cross-origin from the CDN.
Execution path:
- The executor generates a harness - not a runner script, a C++ source file.
buildHarness()inapps/web/lib/cpp-executor.tsembeds every test case as a literal: arguments become__arg0 = {1,2,3}, expected values become typed literals, andListNode/TreeNodehelpers build structures from arrays. Serializers likelistToJsonandtreeToJsonconvert results to JSON for comparison. #include <bits/stdc++.h>is replaced with a portable set of standard includes (that header is GCC-specific and does not exist in wasm-clang).- The harness is compiled once inside
cpp-runner.worker.tswith clang targeting WASM, then all test cases run against the single binary. This is why the log says "Single-compile mode: running N tests in one wasm-clang compile." - Output is parsed with a marker protocol:
__FC_CASE__{...}lines per case plus__FC_SUMMARY__passed/total.
Failure handling is where the reality of a browser compiler shows:
- Missing long-double compare symbols (
__lttf2,__gttf2) trigger a recompile with compiler-rt shims - handwrittenextern "C"functions that emulate the missing libgcc helpers. - Structured bindings inside lambdas are not supported by the current runtime;
normalizeCppUnsupportedFeatureError()detects the clang error, locates the offendingauto [u, color] = ...;line in the user's source, and suggests astd::pairreplacement. - Worker crashes are assumed to be OOM: "C++ compiler crashed (WASM process killed - likely out-of-memory during compilation)".
- Very large suites are chunked (75 cases per chunk, and only beyond 150 total), but the code comments admit this is a last resort: "Each chunk embeds its cases into the harness source and pays a FULL clang compile (~10s in-browser) - so chunking is a last resort for very large suites, not a parallelism win."
- A generated harness over 1,500,000 characters is rejected outright.
Workers and parallelism. getPooledWorker() lazily creates a cpp-runner.worker.ts instance and keeps it warm across runs. Large suites can use up to two workers in parallel (workerCount = chunks.length > 1 && totalCaseCount > 60 ? Math.min(2, chunks.length) : 1), and the pool supports up to 6 workers for concurrent problem sessions. The first compile on a cold worker gets a 90-second grace timeout (Math.max(timeoutMs, 90000)) because it must download and initialize the toolchain.
C is the same pipeline with a different harness. buildCHarness() in apps/web/lib/c-harness.ts generates plain C: since C has no templates, every vector type becomes a concrete struct (FcVec_int, FcVec_string) with its own constructor and JSON serializer, and pairs become FcPair_* structs. The harness includes a C_RUNTIME_HELPERS block with buffer and JSON utilities. Unknown object types throw CUnsupportedTypeError - a compile-time failure, not a runtime guess.
How Python Runs: Pyodide in a Module Worker
Python uses Pyodide 0.27.0, the CPython interpreter compiled to WebAssembly, loaded from https://cdn.jsdelivr.net/pyodide/v0.27.0/full/ by python-runner.worker.ts. The worker is a module worker (type: "module" in apps/web/lib/python-executor.ts), which means importScripts() throws - so the worker dynamically imports the ESM build: import(/* @vite-ignore */ PYODIDE_CDN + "pyodide.mjs").
Execution path:
- The executor posts
{ code, entryPoint, testCases, signatureSchema, adapterId, stdin }to the worker and resolves on a matching response id. - The worker builds a Python harness that indents the user code by four spaces inside a try block, so a syntax error anywhere in the source becomes
compile_error: ...instead of a crash. The harness definesTreeNode,ListNode, andTrieNode, array-to-tree and tree-to-array converters, andsys.stdin = StringIO(...)soinput()reads the stdin box. - Each test case runs with
sys.stdoutandsys.stderrredirected toStringIOcaptures, soprint()output is attributed to the correct case. Per-case timing usestime.perf_counter(). - The worker supports all four problem adapters natively:
plain_function,factory_function,curry_function, andclass_dispatch(the LeetCode "Solution class" pattern).
The singleton worker instance is reused across runs (workerInstance is module-level), and a per-request setTimeout enforces the 30-second budget from the main thread. There is an explicit disposePythonWorker() for cleanup. The documented restriction is blunt: "Third party packages are not installed." Pyodide's package loader is not wired up, so import numpy fails.
How Go Runs: A WASM Interpreter That Cannot Interrupt Itself
Go is the newest and most constrained path. apps/web/lib/go-executor.ts downloads wasm_exec.js and yaegi.wasm from https://cdn.frontendx.dev/wasm-go and runs them in go-runner.worker.ts. Yaegi is an interpreter, not a compiler: your Go source is interpreted against a Go runtime compiled to WASM, which is why the UI warns "the first run downloads a large runtime and can take longer."
Execution path:
- The worker installs a
fsshim onglobalThisbeforewasm_exec.jsloads, because the Go runtime writes stdout through thefsmodule and the marker protocol needs the byte stream intact:writeSyncappends to astdoutBuffer. - The runtime boots once (
bootRuntime()), fetcheswasm_exec.jsandyaegi.wasmthroughcachedFetch(), instantiates the WASM module, and waits up to 120 seconds for a__fcGoReadysignal. The harness parks on a channel so the instance stays callable. - Each run calls
__fcGoRun(source, payload)synchronously inside the WASM instance, then parses the same__FC_CASE__/__FC_SUMMARY__marker protocol as C++.
The defining constraint is in the code comment in apps/web/lib/go-executor.ts: "The Go side runs synchronously inside the WASM instance and cannot self-interrupt, so the only recovery is terminating the worker; the grace window mirrors the C/C++ path." A Go program that spins in an infinite loop cannot be interrupted from inside - the timeout logic (timeoutMs + 2000) must terminate the whole worker and accept the restart cost. That is also why the default timeout is 120 seconds: the runtime needs room to boot, and the interpreter is slower than compiled code.
Stdin is explicitly not implemented: the route renders "The Go browser runtime does not expose interactive standard input yet." Type mapping is handled with renderGoType(): pairs map to [2]T when homogeneous, otherwise to []any - a documented fallback because "Go has no pair type."
Unsupported Features and the Roadmap
There is no standalone roadmap file in the repo; the future plan lives in source comments and UI strings. Assembled, it reads as follows.
Currently unsupported, with the reason:
| Feature | Status | Why |
|---|---|---|
| Browser/Node.js APIs in JS/TS | Unsupported | Code runs in QuickJS, a sandboxed ES2020 VM with no host bindings and a 64 MiB cap |
| Interactive stdin for JS/TS | Unsupported | "This runtime does not expose interactive stdin. Input is ignored for this language." |
C scanf/stdin | Coming next | UI text: "C execution is available. scanf and stdin input support is coming next." |
| Go stdin | Later | "The Go browser runtime does not expose interactive standard input yet." |
| Python third-party packages | Unsupported | Pyodide package loading is not wired up |
#include <bits/stdc++.h> | Rewritten | GCC-only header; replaced with a portable STL include set for wasm-clang |
| Structured bindings in lambdas (C++) | Unsupported | wasm-clang runtime limitation; error message suggests std::pair |
| Long-double comparisons (C++) | Shimmed | Missing libgcc symbols __lttf2/__gttf2 are emulated with compiler-rt shims |
| Go self-interruption | Unsupported | Synchronous WASM execution; worker termination is the only recovery |
| Memory metrics on non-Chromium | Unavailable | performance.memory is Chromium-only |
The roadmap implied by the code:
- C stdin next. The language limit card already says "standard input is not available yet" and the stdin hint says support is "coming next" - the C path in
runCppCustomSourcealready accepts astdinargument (used by C++ via astd::cinredefinition shim), so the C equivalent is the obvious next step. - Per-language runtime availability gating.
isAvailableCompilerLanguage()and the "Unavailable" language-rail state exist now; the UI banner already explains the fallback ("this browser does not have the required runtime. Choose JavaScript, TypeScript, C++, or Python to run code now."). This is the mechanism future runtimes plug into. - Runtime caching as the cold-start fix. Both prefetch functions (
prefetchCppRuntime(),prefetchGoRuntime()) and the worker-sidecachedFetch()write into versioned Cache Storage buckets (cpp-runtime-v1,go-runtime-v1), which is the stated path to making second runs fast: "the first run can take longer while the toolchain loads."
The honest framing: browser compilers will always trail server compilers on environment completeness (no network, no packages, no arbitrary syscalls), and the code says so explicitly in every limit string. The plan is to close the ergonomic gaps - stdin, cold starts, per-device capability detection - not to pretend the sandbox is a container.
How the Compiler Scales: Splitting, Workers, and Caches
Six compilers could easily mean a 10 MB bundle and a frozen main thread. The codebase avoids both with five mechanisms, all visible in the source.
1. Code splitting via dynamic imports. The heavy engines are never statically imported. ensureQuickJS() in apps/web/lib/executor.ts does import("quickjs-emscripten") on first run and caches the promise on globalThis.__frontendxQuickJSReady. esbuild-wasm initializes on demand with initialize({ wasmURL: "/esbuild.wasm", worker: false }). The full typescript compiler is imported only inside the health-check path, and the AI assistant is lazy(() => import("../components/ProblemAssistant")) in OnlineCompilerClient.tsx. The blog preview component for this article's platform follows the same pattern via CodePlaygroundLazy, which wraps CodePlayground in a client-side dynamic import with ssr: false.
2. Web Workers for every compiled language. C++ runs in cpp-runner.worker.ts, Python in python-runner.worker.ts, Go in go-runner.worker.ts. Workers are created lazily on first use (getPooledWorker()), pooled per worker-id, and marked warm after their first successful run so subsequent runs skip the initialization grace period. Compiling clang on the main thread would freeze the UI for 10 seconds; in a worker, the editor stays responsive. performance.now() timing in the executors measures worker wall time, not main-thread time.
3. Cache Storage for runtime assets. Both native-runtime executors use the Cache API: prefetchCppRuntime() fetches and stores shared.js, clang.wasm, lld.wasm, memfs, and sysroot.tar under cpp-runtime-v1; prefetchGoRuntime() stores wasm_exec.js and yaegi.wasm under go-runtime-v1; and go-runner.worker.ts serves its runtime through cachedFetch(), which buffers the response body before cache.put() so a failed cache write can never poison the caller. Pyodide itself relies on the browser's HTTP cache for its 5+ MB interpreter. The result: first run pays the download, every run after reads from cache.
4. CDN-hosted runtime assets. The toolchains are not bundled with the app. They live on cdn.frontendx.dev under /wasm-clang and /wasm-go (and Pyodide on jsdelivr), fetched only when the corresponding language first runs. The app bundle ships zero compiler bytes; the CDN absorbs the bandwidth. The localhost same-origin proxy in both executors exists specifically because "the CDN's edge cache can serve stale responses without CORS headers" on dev ports.
5. Compiler systems stay unloaded until needed. Nothing in the app calls prefetchCppRuntime(), prefetchGoRuntime(), ensureEsbuild(), or ensureQuickJS() at startup. The prefetch functions are exported but invoked only when a user actually opens a runnable surface; the executor singletons are promises cached on globalThis so a second run reuses the initialized esbuild instance and QuickJS module instead of re-downloading. warmupExecutor() exists as an explicit opt-in for surfaces that want to pre-warm JS/TS. The browser tab pays for a compiler only when someone compiles.
The scaling trade-off. Because each user's device is the server, "scaling" means "not making the first run unbearable" rather than "adding nodes." The architecture handles that with a small set of moves: split the engines out of the bundle, run them in workers, cache their assets in Cache Storage, host the assets on a CDN, and initialize everything lazily. When a sixth language arrives, the pattern is already established: a prefetch function, a worker file, a cache bucket, a LANGUAGE_CONFIG entry with an honest limit string, and a lazy import - nothing else changes.
Try It
Open /online-compiler, pick C++, and run the starter. Watch the output log: you will see the toolchain initialize once, the harness get generated, and a single wasm-clang compile produce all your results - all inside the worker, with the console streamed to you through the marker protocol.
<CodePlayground title="A minimal C++ program, exactly as the online compiler runs it" language="cpp" code={`#include <iostream> #include <vector>
int main() { std::vector<int> values{3, 1, 4, 1, 5}; int total = 0; for (int value : values) total += value; std::cout << "Total: " << total << "\n"; return 0; }`} />
If you are on a browser without WebAssembly, the language rail will tell you honestly: the runtime is unavailable, and the compiler will not pretend otherwise.