Skip to content

Engineering

Building a browser IDE: Monaco, local files and remote runs

By Vishnu KumarPublished 7 min read

Putting Monaco on a page takes ten lines. Turning it into an editor people trust with real projects means answering harder questions: where files live, what happens when the tab crashes, how to import a folder without freezing the browser, and how to run code without running it in the user's browser. This is how the Online Code Editor works, with the trade-offs we made.

Monaco, and the workers it needs

Monaco is the editor component VS Code is built on, published separately as monaco-editor. We use it through @monaco-editor/react. It gives syntax highlighting for dozens of languages out of the box, but the features that make it feel like an IDE (completion, validation, formatting for TypeScript, JSON, CSS and HTML) run in web workers, one per language family, so heavy analysis never blocks typing.

Monaco asks the page for those workers through a global hook. With a bundler that understands new URL(…, import.meta.url), each worker becomes its own chunk, loaded only when a file of that language opens:

globalThis.MonacoEnvironment = {
  getWorker(workerId: string, label: string): Worker {
    switch (label) {
      case "json":
        return new Worker(new URL("monaco-editor/esm/vs/language/json/json.worker", import.meta.url),
          { type: "module", name: workerId });
      case "css": case "scss": case "less":
        return new Worker(new URL("monaco-editor/esm/vs/language/css/css.worker", import.meta.url),
          { type: "module", name: workerId });
      // html, typescript / javascript ...
      default:
        return new Worker(new URL("monaco-editor/esm/vs/editor/editor.worker", import.meta.url),
          { type: "module", name: workerId });
    }
  },
};

Languages without a Monaco worker still need formatting. We register formatters lazily, the first time a language is activated: Prettier for Markdown, YAML and GraphQL, and an XML formatter for XML, XSLT and SVG. Nothing is downloaded for a language you never open. A workspace's .editorconfig is parsed too, and its indentation rules are applied per file as model options.

Where files live: a deliberate choice

The obvious design is to store every file in IndexedDB. We decided against it. A copy inside browser storage is a second source of truth that can silently diverge from the user's real project, is lost when site data is cleared, and is invisible to their other tools. Instead:

  • Open files live in memory, as Monaco text models, for as long as the tab is open.
  • A user can connect a real folder on disk. Through the File System Access API (Chrome and Edge), every save is written straight back to that folder, so the disk is the source of truth.
  • IndexedDB stores only the connection: the directory handle, which browsers can structured-clone, so after a reload the editor can offer to reconnect and re-read the files from disk. No file content is persisted.
  • A GitHub import works the same way: the browser remembers only owner, repository and ref, never a token or content, and a restore re-fetches the tree, read-only and lazily.

The cost is honest and stated in the product: a scratch file that is not in a connected folder exists only in the open tab. We think that is better than a hidden copy users did not know about.

Writing back to disk without corrupting it

Connected folders are called mounts. A mount binds one picked directory to one node of the workspace tree, and a file can be covered by several: its own mount and any mount on an ancestor folder. On save, the file is written to every mount that covers it, deduplicated by the resolved on-disk target so the same physical file is never written twice.

Saves are debounced, and two saves of one file can still overlap: createWritable() on a file handle that is already being written produces interleaved or truncated output. The fix is to serialise writes per handle with a promise chain kept in a WeakMap, so a handle that is no longer used is garbage-collected along with its chain:

const writeChains = new WeakMap<FileSystemFileHandle, Promise<unknown>>();

function writeSerialised(handle: FileSystemFileHandle, text: string) {
  const previous = writeChains.get(handle) ?? Promise.resolve();
  const next = previous.catch(() => {}).then(async () => {
    const stream = await handle.createWritable();
    await stream.write(text);
    await stream.close();
  });
  writeChains.set(handle, next);
  return next;
}

File and directory handles cannot live in a serialisable store such as an Immer state tree. The store keeps lightweight mount descriptors (ids and names), and the handles sit in a separate registry keyed by mount id.

Importing a folder without freezing the tab

The first version read an import with Promise.all over every file. Picking a folder that happened to contain node_modules, or a zip with a few videos, loaded everything into memory at once and crashed the tab with no explanation. Imports now run against a budget decided before a single byte is read:

Import limits in the code editor
LimitValueWhy
Largest single file25 MBLarger files are skipped by name
Total per import250 MBBounds memory for the whole selection
Files per import5,000Stops accidental dependency folders
Files read at once8Unbounded parallel reads held every result in memory
Nested zip depth4A zip containing itself would never terminate

Reads go through a small pool that keeps at most eight in flight and returns results in input order, not completion order, so a folder's listing does not depend on which file happened to finish first. Whatever the budget refuses is reported to the user by name and count instead of disappearing silently.

Crash recovery, and its limits

Because content lives in memory, a crash in the React tree is the worst failure the editor can have. An error boundary captures a best-effort snapshot of open files into localStorage (capped at a million characters so one huge buffer cannot exhaust the roughly 5 MB budget) and offers it back after the reload, then clears it so recovered code does not linger on a shared machine.

We document the limit in the code because it is real: React unmounts the failed subtree before the boundary runs, so some Monaco models may already be disposed and unreadable. Each file is attempted independently and whatever survives is kept. It reduces loss; it does not guarantee zero loss. Periodic autosave of open buffers is the robust answer and the next step.

Running code without running it in the browser

Compiling C++ or Rust in a browser tab is possible with WebAssembly toolchains, but only for a few languages, with large downloads and no real isolation from the page. We run code on ls-judge instead, which supports dozens of languages and executes each run in its own Firecracker microVM. The editor's client is small:

  • POST /execute with the language, the code, the standard input as a single test case, a 5-second time limit and 256 MB of memory. The server returns a job id.
  • Poll GET /jobs/{id} starting at 250 ms and backing off by a factor of 1.4 up to 2 seconds, so a quick script answers almost immediately while a slow one does not hammer the judge.
  • Every request has a 15-second network timeout, the whole run a 45-second deadline, and the user can cancel; both feed one AbortSignal.
  • A free-form run has no expected output, so the judge's accepted or wrong-answer verdict is meaningless and ignored. Compile errors, runtime errors and time or memory limits are shown as such.

The judge's address comes from configuration, never a hard-coded fallback. An earlier version defaulted to the production judge, which meant every fork and local build silently sent code there. Now an unconfigured build simply hides the Run button and makes no network requests at all.

Choosing the sandbox was its own project; how to run untrusted code safely explains why we chose microVMs over containers.

An HTTP client that cannot be turned against us

The editor includes an HTTP client for testing APIs. Browser fetch would be blocked by CORS for most APIs, so requests are sent from our server through a Next.js server action. That creates a classic risk, server-side request forgery: a user could ask our server to fetch http://169.254.169.254/ or an internal service. The action resolves the target and blocks private and loopback addresses, including public hostnames that resolve to them, and follows redirects itself so that every hop is checked again rather than only the first URL.

What we would tell someone starting today

  • Decide where files live before writing any UI. It shapes saving, recovery, sync and every promise you make to users.
  • Load language tooling lazily; most sessions touch two or three languages.
  • Put budgets on everything that reads user input: file size, file count, archive depth and concurrency.
  • Write the limits of your recovery mechanism down where the next engineer will see them.
  • Do not run untrusted code in the page; send it to an isolated service with strict timeouts and cancellation.
  • Make external services opt-in by configuration, so a missing setting degrades features instead of silently pointing at production.