iTranslated by AI
Building a Browser-Based Development Environment with WebContainers
What are WebContainers?
Have you ever heard of WebContainers?
WebContainers is a tool developed by StackBlitz for building development environments directly in the browser.
Incredibly, it allows you to run applications like Node.js and Next.js using only a browser.
This tool is already being used for things like the Svelte Playground.
What I'm currently building with WebContainers
I'm currently working on a tool that allows for development using Next.js and React entirely within the browser, as shown in the video below.
Here is the link to the editor currently under development.
The following features are already available in this editor:
- File creation, deletion, and renaming
- Terminal operations (jsh)
- File editing (VS Code-like editor)
- Browser preview of execution results
Once I finish building this tool, I plan to introduce a new plan to my web learning service, mosya, that uses it for learning React.
How to build a development environment using WebContainers
In this article, I would like to briefly explain how to build a development environment using WebContainers.
Booting WebContainers
First, let's look at how to boot WebContainers.
WebContainers can be booted as follows:
import { WebContainer } from "@webcontainer/api";
const container = await WebContainer.boot();
Linking with the file tree
You can mount files into WebContainers by creating an object like the one below.
const files = {
// This is a directory - provide its name as a key
src: {
// Because it's a directory, add the "directory" key
directory: {
// This is a file - provide its path as a key:
'main.js': {
// Because it's a file, add the "file" key
file: {
contents: `
console.log('Hello from WebContainers!')
`,
},
},
// This is another file inside the same folder
'main.css': {
// Because it's a file, add the "file" key
file: {
contents: `
body {
margin: 0;
}
`,
},
},
},
},
// This is a file outside the folder
'package.json': {
/* Omitted for brevity */
},
// This is another file outside the folder
'index.html': {
/* Omitted for brevity */
},
};
container.mount(files);
In the case of directories, you need to add a directory key further down for each directory key name, which is quite tedious.
Therefore, I have created a function like the one below. It is a function that creates a file tree from the paths provided as keys in an object.
filesToSystemTree function
export type Files = {
[key: string]: {
value: string;
language: string;
active?: boolean;
hidden?: boolean;
tabbed?: boolean;
};
};
export function filesToSystemTree(input: Files): FileSystemTree {
const output: FileSystemTree = {};
for (const key in input) {
// Remove any './' from the beginning of the key
const adjustedKey = key.startsWith("./") ? key.slice(2) : key;
const splitKeys = adjustedKey.split("/").filter(Boolean);
let currentOutput = output;
for (let i = 0; i < splitKeys.length; i++) {
const subKey = splitKeys[i];
// If we're at a file, assign it as file with contents
if (i === splitKeys.length - 1) {
currentOutput[subKey] = { file: { contents: input[key].value } };
} else {
// Otherwise, create a new directory if it doesn't exist
if (!currentOutput[subKey]) {
currentOutput[subKey] = { directory: {} };
}
// Move our pointer to this directory
currentOutput = currentOutput[subKey].directory!;
}
}
}
return output;
}
Installing dependencies
WebContainers provides a function to execute commands, which allows you to install dependency libraries using npm or yarn.
// Install dependencies
const installProcess = await container.spawn("npm", ["install"]);
// Wait for install command to exit
await installProcess.exit;
Linking with the terminal
Additionally, I am implementing the terminal using a library called Xterm.js. It works very well with WebContainers.
You can pipe the output of a WebContainers process to the output of Xterm.js as follows.
import { Terminal } from "xterm";
const terminal = new Terminal();
const installProcess = await container.spawn("npm", ["install"]);
installProcess.output.pipeTo(
new WritableStream({
write(data) {
terminal.write(data);
},
})
);
Conversely, when there is input to Xterm, you can pipe it to the WebContainers process as follows.
const shellProcess = await container.spawn("jsh", {
terminal: {
cols: terminal.cols,
rows: terminal.rows,
},
});
shellProcess.output.pipeTo(
new WritableStream({
write(data) {
terminal.write(data);
},
})
);
const input = shellProcess.input.getWriter();
terminal.onData((data) => {
input.write(data);
});
Starting the app
Finally, we will start the application in WebContainers. Starting it is as simple as using the npm command to run the dev command, just as you would when normally using Next.js.
const startProcess = await container.spawn("npm", ["run", "dev"]);
startProcess.output.pipeTo(
new WritableStream({
write(data) {
terminal.write(data);
},
})
);
// Wait for `server-ready` event
return new Promise<string>((resolve) => {
container.on("server-ready", (port, url) => {
resolve(url);
});
});
Additionally, when the container's server starts, the server-ready event is triggered. By waiting for this, you can detect that the server has started and obtain the server's URL at the same time.
By passing this to the src of an iframe, you can display the application within the iframe.
To summarize, the code looks like this:
Summary
import React, { useEffect } from "react";
import { HashLoader } from "react-spinners";
import { Terminal } from "xterm";
import type { Files } from "./types";
import { useBrowserEditor } from "./hooks/use-browser-editor";
import { transform } from "./utils/file-system";
import { getWebContainerInstance } from "./utils/webcontainer";
import { getTerminalInstance } from "./utils/terminal";
async function bootinstance(files: Files) {
const webcontainerInstance = await getWebContainerInstance();
await webcontainerInstance.mount(transform(files));
}
async function installDependencies(terminal: Terminal) {
// Install dependencies
const webcontainerInstance = await getWebContainerInstance();
const installProcess = await webcontainerInstance.spawn("npm", ["install"]);
installProcess.output.pipeTo(
new WritableStream({
write(data) {
terminal.write(data);
},
})
);
// Wait for install command to exit
return installProcess.exit;
}
async function startDevServer(terminal: Terminal) {
const webcontainerInstance = await getWebContainerInstance();
// Run `npm run start` to start the Express app
const startProcess = await webcontainerInstance.spawn("npm", ["run", "dev"]);
startProcess.output.pipeTo(
new WritableStream({
write(data) {
terminal.write(data);
},
})
);
// Wait for `server-ready` event
return new Promise<string>((resolve) => {
webcontainerInstance.on("server-ready", (port, url) => {
resolve(url);
});
});
}
async function startShell(terminal: Terminal) {
const webcontainerInstance = await getWebContainerInstance();
const shellProcess = await webcontainerInstance.spawn("jsh", {
terminal: {
cols: terminal.cols,
rows: terminal.rows,
},
});
shellProcess.output.pipeTo(
new WritableStream({
write(data) {
terminal.write(data);
},
})
);
const input = shellProcess.input.getWriter();
terminal.onData((data) => {
input.write(data);
});
// shellProcess.
return shellProcess;
}
async function run(files: Files) {
const terminal = getTerminalInstance();
await bootinstance(files);
await installDependencies(terminal);
const url = await startDevServer(terminal);
await startShell(terminal);
return url;
}
export const Preview = () => {
const { files } = useBrowserEditor();
const [url, setUrl] = React.useState("");
const [boot, setBoot] = React.useState(false);
useEffect(() => {
if (boot || !files || Object.keys(files).length === 0) {
return;
}
setBoot(true);
run(files).then((url) => {
setUrl(url);
});
}, [files]);
return (
<div className="rounded-md flex-1 h-full overflow-hidden">
<div className="w-full h-11 rounded-t-lg bg-gray-200 flex justify-start items-center space-x-1.5 px-3">
<span className="w-3 h-3 rounded-full bg-red-400"></span>
<span className="w-3 h-3 rounded-full bg-yellow-400"></span>
<span className="w-3 h-3 rounded-full bg-green-400"></span>
</div>
{url && (
<iframe
src={url}
sandbox="allow-scripts allow-same-origin allow-popups-to-escape-sandbox allow-popups"
className="h-full bg-gray-50 p-2 w-full"
></iframe>
)}
{!url && (
<div className="grid place-items-center h-full w-full">
<HashLoader color="#36d7b7" />
</div>
)}
</div>
);
};
Visualizing the file tree
Next is the visualization of the file tree.
For this, I am using a library called @sinm/react-file-tree.
This library is great because it displays icons based on file extensions!

As of August 10, 2023, it only has three stars, but it is very well-made!
Implementing the editor part
For the editor implementation, I am using the familiar Monaco Editor.
One challenging aspect was the type information for libraries and its display, but I solved this by pulling type information from esm.sh and passing it to the Monaco Editor.
For example, if you want to retrieve type information for react, you can access https://esm.sh/react. Since the URL for the type information is in the x-typescript-types response header, you can then access that URL to get the type definitions.
export const resolveModuleType = async (
module: string,
): Promise<void> => {
const res = await fetch(`https://esm.sh/${module}`);
const dtsUrl = res.headers.get("x-typescript-types");
if (!dtsUrl) return;
const dts = await fetch(dtsUrl);
const dtsText = await dts.text();
// Pass the retrieved types to Monaco Editor
monaco.languages.typescript.typescriptDefaults.addExtraLib(
dtsText,
`file:///node_modules/@types/${module}/index.d.ts`
);
};
// Retrieve types for react
resolveModuleType("react");
Highlighting JSX in Monaco Editor
Monaco Editor does not natively support JSX highlighting at the moment, so I use a library called monaco-textmate to achieve JSX highlighting.

The code is as follows. It loads the necessary definition files for highlighting based on each language.
In this case, I'm directly loading VS Code's definition files for convenience.
JSX Highlighting
import { wireTmGrammars } from "monaco-editor-textmate";
import { Registry } from "monaco-textmate"; // peer dependency
import { loadWASM } from "onigasm"; // peer dependency of 'monaco-textmate'
const textmatePath =
"https://esm.sh/githubusercontent/microsoft/vscode/main/extensions";
const registry = new Registry({
getGrammarDefinition: async (scopeName) => {
if (scopeName === "source.tsx") {
const response = await fetch(
`${textmatePath}/typescript-basics/syntaxes/TypeScriptReact.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
if (scopeName === "source.ts") {
const response = await fetch(
`${textmatePath}/typescript-basics/syntaxes/TypeScriptReact.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
if (scopeName === "source.js") {
const response = await fetch(
`${textmatePath}/javascript/syntaxes/JavaScriptReact.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
if (scopeName === "source.jsx") {
const response = await fetch(
`${textmatePath}/javascript/syntaxes/JavaScriptReact.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
if (scopeName === "source.css") {
const response = await fetch(
`${textmatePath}/css/syntaxes/css.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
if (scopeName === "text.html.basic") {
const response = await fetch(
`${textmatePath}/html/syntaxes/html.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
if (scopeName === "source.json") {
const response = await fetch(
`${textmatePath}/json/syntaxes/JSON.tmLanguage.json`
);
return {
format: "json",
content: await response.text(),
};
}
return {
format: "json",
content: "",
};
},
});
export const initEditor = async () => {
await loadWASM("https://esm.sh/onigasm@2.2.5/lib/onigasm.wasm");
monaco.editor.defineTheme("myTheme", theme);
monaco.editor.setTheme("myTheme");
const grammers = new Map();
grammers.set("typescript", "source.tsx");
grammers.set("javascript", "source.jsx");
grammers.set("css", "source.css");
grammers.set("html", "text.html.basic");
grammers.set("json", "source.json");
await wireTmGrammars(monaco, registry, grammers);
};
Summary
By using WebContainers developed by StackBlitz, we were able to easily set up an environment for developing Next.js within a browser.
By combining this with libraries such as Xterm.js and Monaco Editor, the possibilities are endless.
For beginners, setting up an environment can be quite difficult and is often a point where they might give up.
By lowering the barrier to entry with a browser-based environment like this, I hope it will encourage more people to start programming.
Also, since this isn't limited to learning but can also be used for creating playgrounds for libraries you've built, please give it a try.
Future Challenges
I hope to further brush up this editor in the future and am considering the following improvements and feature additions:
- Git integration
- Closing open tabs
- Updating
package.jsonafter runningnpm install, etc. - Support for libraries that use databases, such as Prisma
- Sharing the created code, etc.
It seems that SQLite can be run on WebContainers, so it should probably be possible to run Prisma!
Discussion