Learn how to use the CodeSandbox SDK to execute code, process data, and more.
The CodeSandbox SDK enables you to programmatically spin up development environments and run untrusted code. It provides a programmatic API to create and run sandboxes quickly and securely.
The CodeSandbox SDK is only available on TypeScript for now, Python support is coming!
To get started, install the SDK:
Copy
Ask AI
npm install @codesandbox/sdk
Then, create an API token by going to https://codesandbox.io/t/api, and clicking on the “Create API Token” button. You can then use this token to authenticate with the SDK:
Copy
Ask AI
import { CodeSandbox } from "@codesandbox/sdk";// Create the client with your tokenconst sdk = new CodeSandbox(token);// This creates a new sandbox by forking our default template sandbox.// You can also pass in other template ids, or create your own template to fork from.const sandbox = await sdk.sandbox.create();// You can run JS code directlyawait sandbox.shells.js.run("console.log(1+1)");// Or Python code (if it's installed in the template)await sandbox.shells.python.run("print(1+1)");// Or anything elseawait sandbox.shells.run("echo 'Hello, world!'");// We have a FS API to interact with the filesystemawait sandbox.fs.writeTextFile("./hello.txt", "world");// And you can clone sandboxes! This does not only clone the filesystem, processes that are running in the original sandbox will also be cloned!const sandbox2 = await sandbox.fork();// Check that the file is still thereawait sandbox2.fs.readTextFile("./hello.txt");// You can also get the opened ports, with the URL to access thoseconsole.log(sandbox2.ports.getOpenedPorts());// Getting metrics...const metrics = await sandbox2.getMetrics();console.log( `Memory: ${metrics.memory.usedKiB} KiB / ${metrics.memory.totalKiB} KiB`);console.log(`CPU: ${(metrics.cpu.used / metrics.cpu.cores) * 100}%`);// Finally, you can hibernate a sandbox. This will snapshot the sandbox and stop it. Next time you start the sandbox, it will continue where it left off, as we created a memory snapshot.await sandbox.hibernate();await sandbox2.hibernate();// Open the sandbox againconst resumedSandbox = await sdk.sandbox.open(sandbox.id);
This SDK uses the API token from your workspace in CodeSandbox to authenticate and create sandboxes. Because of this, the sandboxes will be created inside your workspace, and the resources will be billed to your workspace.You could, for example, create a private template in your workspace that has all the dependencies you need (even running servers), and then use that template to fork sandboxes from. This way, you can control the environment that the sandboxes run in.