---
title: &title API Reference
description: &description The public WebContainer API allows you to build custom applications on top of an in-browser Node.js runtime.
outline: [2, 3]
head:
- ['meta', { property: 'og:title', content: *title }]
- [
'meta',
{ property: 'og:image', content: 'https://webcontainers.io/img/og/api.png' },
]
- ['meta', { name: 'twitter:title', content: *title }]
- ['meta', { name: 'twitter:description', content: *description }]
---
The public WebContainer API allows you to build custom applications on top of an in-browser Node.js runtime. Its main entry point is the WebContainer
class.
The main export of this library. An instance of WebContainer
represents a runtime ready to be used.
fs: FileSystemAPI
Gives access to the underlying file system.
The default value of the PATH
environment variable for processes started through spawn
.
The full path to the working directory (see FileSystemAPI).
Boots a WebContainer. Only a single instance of WebContainer can be booted concurrently (see teardown
). Booting WebContainer is an expensive operation.
static boot(options: BootOptions = {}): Promise<WebContainer>
Returns a WebContainer
instance.
interface BootOptions {
coep?: 'require-corp' | 'credentialless' | 'none';
workdirName?: string;
forwardPreviewErrors?: boolean | 'exceptions-only';
}
The value of the COEP header used to load your application.
Choosing 'none'
will result in no cross-origin isolation headers being used. This will only work on Chromium-based browsers as long as an Origin Trial is supported.
This value is fixed the first time a WebContainer is booted, and cannot be changed in successive reboots.
Sets the folder name for the working directory of your WebContainer instance. If not provided, it will be auto-generated.
This is mostly a "cosmetic" option.
Configure whether errors occurring in embedded preview iframes should be forwarded to the parent page. Captured errors originate from:
- Calls to
console.error
- Any
unhandledrejection
events onwindow
- Any uncaught
error
events onwindow
If set to exceptions-only
, console.error
s are not forwarded.
Default value is false
, so no errors are emitted.
To receive the events, you register an event handler like this:
webcontainerInstance.on('preview-message', (message) => {
// process the message received from a preview
});
Mounts a tree of files into the filesystem. This can be specified as a FileSystemTree object or as a binary snapshot generated by @webcontainer/snapshot
.
mount(tree: FileSystemTree | Uint8Array | ArrayBuffer, options?: Options): Promise<void>
interface Options {
mountPoint?: string;
}
Listens for an event
. The listener
is called every time the event
gets emitted.
on(event: 'port' | 'error' | 'server-ready' | 'preview-message', listener: PortListener | ErrorListener | ServerReadyListener | PreviewMessageListener): () => void
Returns a function to unsubscribe from the events. Once unsubscribed, the listener
will no longer be called.
▸ on(event: 'port', listener: PortListener): () => void
Listens for port
events, which are emitted when a port is opened or closed by some process.
PortListener
(Function)
(port: number, type: "open" | "close", url: string): void
▸ on(event: 'error', listener: ErrorListener): () => void
Listens for error
events, emitted when an internal error is triggered.
ErrorListener
(Function)
(error: { message: string }): void
▸ on(event: 'preview-message', listener: PreviewMessageListener): () => void
Listens for preview-message
events, emitted when an internal error is triggered.
PreviewMessageListener
(Function)
(message: PreviewMessage): void
type PreviewMessage = (UncaughtExceptionMessage | UnhandledRejectionMessage | ConsoleErrorMessage) & BasePreviewMessage;
interface BasePreviewMessage {
previewId: string;
port: number;
pathname: string;
search: string;
hash: string;
}
interface UncaughtExceptionMessage {
type: PreviewMessageType.UncaughtException;
message: string;
stack: string | undefined;
}
interface UnhandledRejectionMessage {
type: PreviewMessageType.UnhandledRejection;
message: string;
stack: string | undefined;
}
interface ConsoleErrorMessage {
type: PreviewMessageType.ConsoleError;
args: any[];
stack: string;
}
▸ on(event: 'server-ready', listener: ServerReadyListener): () => void
Listens for server-ready
events, emitted when a server was started and ready to receive traffic.
ServerReadyListener
(Function)
(port: number, url: string): void
Spawns a process. When no args
are provided, spawns a process without command-line arguments.
spawn(command: string, args: string[], options?: SpawnOptions): Promise<WebContainerProcess>
With args
:
const install = await webcontainerInstance.spawn('npm', ['i']);
Without args
:
const install = await webcontainerInstance.spawn('yarn');
Returns a WebContainerProcess
.
▸ spawn(command: string, args: string[], options?: SpawnOptions): () => Promise<WebContainerProcess>
Spawns a process with additional arguments.
▸ spawn(command: string, options?: SpawnOptions): () => Promise<WebContainerProcess>
Spawns a process without additional arguments.
Added in version 1.4.0
.
Exports the filesystem.
export(path: string, options?: ExportOptions): Promise<Uint8Array | FileSystemTree>
const data = await webcontainerInstance.export('dist', { format: 'zip' });
const zip = new Blob([data]);
Returns a FileSystemTree
when the format is json
, otherwise a Uint8Array
.
Added in version 1.5.0
.
Configure a script to be injected inside all previews. After this function resolves, every preview iframe that is either added or reloaded will now include this extra script on all HTML responses.
Notably, existing previews won't include the script until they have been reloaded.
To reload a preview you can use reloadPreview
:::warning This API is an advanced feature that should only be used if it is your only option. Since you can control servers running in WebContainer, it's preferable to add this code when serving the content itself.
In particular, this might break existing WebContainer features or ones that will be added later. :::
setPreviewScript(scriptSrc: string, options?: PreviewScriptOptions): Promise<void>
const script = `
console.log('Hello world!');
`;
await webcontainerInstance.setPreviewScript(script);
// now all previews will always print hello world to the console if they serve HTML
Destroys the WebContainer instance, turning it unusable, and releases its resources. After this, a new WebContainer instance can be obtained by calling boot
.
All entities derived from this instance (e.g. processes, the file system, etc.) also become unusable after calling this method.
teardown(): void
Added in version 1.2.2
.
Reload the provided iframe by sending a message to the iframe and falling back to resetting the src
if the iframe didn't respond in time.
Returns a Promise
that resolves when the reload has completed.
Added in version 1.3.0
.
Configure an API key to be used for commercial usage of the WebContainer API. See https://webcontainers.io/enterprise for more information.
This function will throw an exception if WebContainer.boot
was called before configureAPIKey
.
The authentication API is exported under the auth
namespace. It allows you to authenticate users visiting your website via StackBlitz. In order for users to be authenticated via this method, they must:
- Be logged in on StackBlitz.
- Belong to the organisation you used to generate your
clientId
for use with the WebContainer API. - Authorize your website.
Once logged in, you'll be able to install private packages that those users have access to within WebContainer.
Intialize the authentication for use in WebContainer. This method should be called as soon as possible as part of the loading phase of your page. For example at the top of a module that gets loaded as soon as the page loads. This is important for multiple reasons:
-
If you do client side routing, and the OAuth flow is happening, then query parameters might be populated with values related to the OAuth flow. The
init
function removes them after they've been consumed. -
If you do the authentication in popup mode, you likely want the popup to be closed as soon as the authentication completed.
init(options: AuthInitOptions): { status: 'need-auth' | 'authorized' } | AuthFailedError
This function will throw an exception if WebContainer.boot
was called before auth.init
.
interface AuthInitOptions {
/**
* StackBlitz' origin.
*
* @default https://stackblitz.com
*/
editorOrigin?: string;
/**
* The client id for this OAuth application.
*/
clientId: string;
/**
* OAuth scope. The value can be found under your `Teams Settings` > `API`.
*
* @see https://www.rfc-editor.org/rfc/rfc6749#section-3.3
*/
scope: string;
}
interface AuthFailedError {
status: 'auth-failed';
/**
* A short description of the error.
*/
error: string;
/**
* A detailed description of the error.
*/
description: string;
}
This starts the OAuth flow, redirecting the current page to the StackBlitz editor to authenticate the user unless popup
is set to true in which case it's done in a popup.
startAuthFlow(options?: { popup?: boolean }): void
Returns a promise that resolves when the user authorized your application. This promise is guaranteed to never be rejected.
If the user never authorizes or declines your application, this promise never resolves.
loggedIn(): Promise<void>
const instance = await WebContainer.boot();
// wait until the user is logged in
await auth.loggedIn();
// we can now fetch private packages from our organisation
await instance.spawn('npm', ['install']);
Logout the user and clear any credentials that were saved locally.
If ignoreRevokeError
is set and the revocation failed, the locally-saved credentials are discarded nonetheless.
logout(options?: { ignoreRevokeError?: boolean }): Promise<void>
Listens for an event
. The listener
is called every time the event
gets emitted.
on(event: 'logged-out' | 'auth-failed', listener: () => void | (reason: { error: string, description: string }) => void): () => void
Returns a function to unsubscribe from the events. Once unsubscribed, the listener
will no longer be called.
Listens for logged-out
events, which are emitted when the credentials are revoked, meaning the user needs to re-authenticate.
▸ on(event: 'auth-failed', listener: (reason: { error: string, description: string }) => void): () => void
Listens for auth-failed
events, which are emitted when the user declines authorization in another tab / popup.
The property error
corresponds to a constant that your code can match against, while description
is a human readable error that can be useful for development. The possible values of error
are:
access_denied
: The user denied the authorization request.invalid_scope
: The scope is invalid, unknown or malformed.
More might be addded in the future, which is reason behind having error
typed as a string
instead of an union.
A representation of a directory entry, see the Node.js API.
The name of the file or directory.
name
: string | Uint8Array
Whether the entry is a directory.
isDirectory(): boolean
Whether the entry is a file.
isFile(): boolean
Interface to interact directly with the WebContainer file system. Modeled after fs.promises
in Node.
Creates a new directory. If the directory already exists, it will throw an error.
mkdir(path: String, options?: Options): Promise<void>
When recursive
is set to true
, it will create any missing folders in the path.
interface Options {
recursive?: boolean;
}
Reads a given directory and returns an array of its files and directories.
readdir(path: string, options?: Options): Promise<Uint8Array[]> | Promise<string[]> | Promise<DirEnt<Uint8Array>[]> | Promise<DirEnt<string>[]>
interface Options {
encoding?: BufferEncoding;
withFileTypes?: boolean;
}
The encoding (see BufferEncoding
) can be any one of those accepted by Buffer
.
When set to true
, the return value is an array of Dirent
objects.
Reads the file at the given path. If the file does not exist, it will throw an error.
readFile(path: string, encoding?: BufferEncoding | null): Promise<Uint8Array> | Promise<string>
By default, it returns a UInt8Array
. A second argument can be passed as the encoding.
Without encoding
:
const bytes = await webcontainerInstance.fs.readFile('/package.json');
With a specified encoding
:
const content = await webcontainerInstance.fs.readFile('/package.json', 'utf-8');
Promise<Uint8Array>
or Promise<string>
Rename the file from oldPath
to newPath
. The parent folders in newPath
must all exist.
rename(oldPath: string, newPath: string): Promise<void>
Renaming a file:
await webcontainerInstance.fs.rename('/src/index.js', '/src/main.js');
Deletes a file or a directory. If the path is a file, it will delete the file. If the path is a directory, a second argument is needed with option recursive
set to true
to delete the directory and everything inside it, including nested folders.
rm(path: string, options?: Options): Promise<void>
interface Options {
force?: boolean;
recursive?: boolean;
}
When true
, exceptions will be ignored if the path
does not exist.
If true
, it will recursively remove directories, including nested directories.
Deleting a file:
await webcontainerInstance.fs.rm('/src/main.js');
Deleting a directory:
await webcontainerInstance.fs.rm('/src', { recursive: true });
Writes a file to the given path. If the file does not exist, it will create a new one. If the file exists, it will overwrite the file.
writeFile(path: string, data: string | Uint8Array, options?: string { encoding?: null | BufferEncoding } | null): Promise<void>
Default:
await webcontainerInstance.fs.writeFile('/src/main.js', 'console.log("Hello from WebContainers!")');
With encoding
:
await webcontainerInstance.fs.writeFile(
'/src/main.js',
'\xE5\x8D\x83\xE8\x91\x89\xE5\xB8\x82\xE3\x83\x96\xE3\x83\xAB\xE3\x83\xBC\xE3\x82\xB9',
{ encoding: 'latin1' }
);
Watch for changes to a given file or directory.
watch(path: string, options: Options, listener: Listener): Watcher
watch(path: string, listener: Listener): Watcher
interface Options {
encoding?: BufferEncoding | null;
recursive?: boolean;
}
Specifies the character encoding to be used for the filename passed to the listener. Default: 'utf8'
.
Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified. Default: false
.
type Listener = (event: 'rename' | 'change', filename: string | Buffer) => void;
interface Watcher {
close(): void;
}
Stop watching for changes on the given Watcher.
Watching a file:
webcontainerInstance.fs.watch('/src/main.js', (event) => {
console.log(`action: ${event}`);
});
Watching a directory:
webcontainerInstance.fs.watch('/src', { recursive: true }, (event, filename) => {
console.log(`file: ${filename} action: ${event}`);
});
A tree-like structure to describe the contents of a folder to be mounted.
interface FileSystemTree {
[name: string]: FileNode | SymlinkNode | DirectoryNode;
}
Also see FileNode
, SymlinkNode
, and DirectoryNode
.
const tree = {
myproject: {
directory: {
'foo.js': {
file: {
contents: 'const x = 1;',
},
},
'bar.js': {
file: {
symlink: './foo.js',
},
},
'.envrc': {
file: {
contents: 'ENVIRONMENT=staging'
}
},
},
},
emptyFolder: {
directory: {}
},
};
interface FileNode {
file: {
contents: string | Uint8Array;
};
}
Represents a file with contents. Also see FileSystemTree
.
interface SymlinkNode {
file: {
symlink: string;
};
}
Represents a symlink pointing to another location. Also see FileSystemTree
.
interface DirectoryNode {
directory: FileSystemTree;
}
▸ directory: FileSystemTree
Represents a directory node. Also see FileSystemTree
.
Options that control spawning a process.
export interface SpawnOptions {
cwd?: string;
env?: Record<string, string | number | boolean>;
output?: boolean;
terminal?: { cols: number; rows: number };
}
Current working directory for the process, relative to workdir
this instance (which you can change when booting WebContainer
).
By default, the working directory of the spawned process is workdir
.
Environment variables to set for the process.
When set to false
, no terminal output is sent back to the process, and the output
stream will never produce any chunks.
The size of the attached terminal.
Options that control exporting data.
export interface ExportOptions {
format?: 'json' | 'binary' | 'zip',
includes?: string[];
excludes?: string[];
}
The format of the exported data. The json
and binary
format can be used as tree
when calling mount
.
The default value is json
.
Globbing patterns to include files from within excluded folders.
Globbing patterns to exclude files from the export.
Options that control attributes on a script injected into previews.
export interface PreviewScriptOptions {
type?: 'module' | 'importmap';
defer?: boolean;
async?: boolean;
}
The type attribute to use for the script. For more information, check the MDN page on the script: type attribute.
If set to true, then the defer
attribute will be set on the script tag. For more information, check the MDN page on the script: defer attribute.
If set to true, then the async
attribute will be set on the script tag. For more information, check the MDN page on the script: async attribute.
A running process spawned in a WebContainer instance.
A promise for the exit code of the process.
▸ input: WritableStream<string>
An input stream for the attached pseudoterminal device.
▸ output: ReadableStream<string>
A stream that receives all terminal output, including the stdout and stderr emitted by the spawned process and its descendants.
Can be disabled by setting output
to false
via spawn
.
output: ReadableStream<string>
Kills the process.
kill(): void
Resizes the attached terminal.
resize(dimensions: { cols: number, rows: number }): void
type BufferEncoding =
| 'ascii'
| 'utf8'
| 'utf-8'
| 'utf16le'
| 'ucs2'
| 'ucs-2'
| 'base64'
| 'base64url'
| 'latin1'
| 'binary'
| 'hex';