Templates
CodeSandbox has default templates that you can use to create sandboxes. These templates are available in the Template Library and by default we use the "Universal" template. To create your own template you will need to use our CLI.
Creating the template
Create a new folder in your project and add the files you want to have available inside your Sandbox. For example set up a Vite project:
npx create-vite@latest my-template
Now we need to configure the template with tasks so that it will install dependencies and start the dev server. Create a my-template/.codesandbox/tasks.json
file with the following content:
{
"setupTasks": [
"npm install"
],
"tasks": {
"dev-server": {
"name": "Dev Server",
"command": "npm run dev",
"runAtStart": true
}
}
}
The setupTasks
will run after the Sandbox has started, before any other tasks.
Now we are ready to deploy the template to our clusters, run:
$ CSB_API_KEY=your-api-key npx @codesandbox/sdk build ./my-template --ports 5173
The template will by default be built with Micro
VM Tier unless you pass --vmTier
to the build command.
This will start the process of creating Sandboxes for each of our clusters, write files, restart, wait for port 5173 to be available and then hibernate. This generates the snapshot that allows you to quickly create Sandboxes already running a dev server from the template.
When all clusters are updated successfully you will get a "Template Tag" back which you can use when you create your sandboxes.
const sandbox = await sdk.sandboxes.create({
source: 'template',
id: 'some-template-tag'
})
Custom Docker Image
CodeSandbox uses Dev Containers (opens in a new tab) for configuring Docker or Docker Compose for an environment. You can configure Docker by creating a .devcontainer/devcontainer.json
file inside your template folder with these contents:
{
"image": "ubuntu:22.04"
}
When we boot the sandbox, we’ll make sure that the docker image is pulled (or built) and we’ll make sure that all shells will start within this container. Your /project/sandbox
folder will also be mounted inside the container.
You can decide to build the Docker image as part of the template creation process as well. You can do this by defining this in your .devcontainer/devcontainer.json
:
{
"build": {
"dockerfile": "Dockerfile"
}
}
And creating a .devcontainer/Dockerfile
with the contents of your Dockerfile.
For more options (like running docker compose, or adding additional features), you can look at the Dev Container docs (opens in a new tab).
Setup Tasks vs Dockerfile
When would you configure something in the Dockerfile, and when would you configure something in setup tasks?
As a rule of thumb, if something is configured in relation to the environment (like installing Node, or installing Postgres, or installing Bun), it should go into the Dockerfile. If something is related to the project setup (installing dependencies, building a binary), it should go inside setup tasks.