Create Sandbox
Sandboxes are the main building blocks of the CodeSandbox SDK. Each one represents a single project that you can run, fork, and modify.
Every Sandbox is backed by a Firecracker VM, and is completely isolated and persisted. Providing you with a secure environment to run untrusted code.
Creating a Sandbox
To create a sandbox, call sandbox.create()
:
import { CodeSandbox } from '@codesandbox/sdk'
const sdk = new CodeSandbox();
const sandbox = await sdk.sandboxes.create();
By default Sandboxes are unlisted
and can be accessed and forked by anyone with a url. If you want to create a private sandbox you can pass privacy: 'private'
, which requires host tokens to access the exposed ports.
If no argument is provided to sandbox.create()
, we'll create a sandbox based on our Universal (opens in a new tab) template on CodeSandbox. You can also pass in a specific template id from our collection of templates or by creating your own snapshot using our Snapshot Builder. Additionally you can choose other sources like Git or Files.
Create from Template
const sandbox = await sdk.sandboxes.create({
source: 'template',
id: 'some-sandbox-id'
})
Create from Git
const sandbox = await sdk.sandboxes.create({
source: 'git',
url: 'https://...',
branch: 'main',
templateId: 'optional-template-id-to-fork-from',
// Optionally pass necessary git config for private repos etc.
config: {
accessToken: 'github-token',
email: '[email protected]',
name: 'Foo Bar'
},
async setup(session) {
await session.commands.run('pnpm install')
await session.commands.run('pnpm run dev')
await session.ports.waitForPort(5173)
}
})
It depends on the repo how you want to setup the sandbox. If it is configured with tasks you can run session.setup.run()
to run the full setup, but if configured with a .devcontainer
you want to restart the sandbox itself. Or you can do like the example just run some commands.
Additional options
For any of the above sources you can also pass the following options:
const sandbox = await sdk.sandboxes.create({
source: 'template',
title: 'my-sandbox',
description: 'My sandbox',
tags: ['my-tag'],
privacy: 'public'
path: '/users/some-user-folder'
})
Sandbox Properties
The sandbox
object represents the instance of a sandbox running in our infrastructure. The methods detailed below require the Sandbox to be running.
Each Sandbox has the following properties, with information about it's own instance:
id
: The unique identifier of the sandbox.isUpToDate
: Whether the sandbox is up to date with the latest agent version.cluster
: The cluster the sandbox is running on.bootupType
: The type of bootup,RUNNING
,CLEAN
,RESUME
orFORK
.
Resume an Existing Sandbox
To resume an existing sandbox from hibernation and connect to it call: sdk.sandboxes.resume(id)
:
const sandbox = await sdk.sandboxes.resume('sandbox-id');
Sandboxes that have been dormant for a week may take longer to start as they will need to run their setup before resuming.