### SDK Installation and Quickstart Source: https://context7.com/codesandbox/docs/llms.txt Install the CodeSandbox SDK via npm and initialize it with your API key to get started. This example demonstrates creating a sandbox and running a simple command. ```APIDOC ## SDK Installation and Quickstart The CodeSandbox SDK enables programmatic control of cloud development environments. Install it via npm and initialize with your API key. ```bash npm install @codesandbox/sdk ``` ```javascript import { CodeSandbox } from "@codesandbox/sdk"; // Initialize SDK (uses CSB_API_KEY environment variable) const sdk = new CodeSandbox(); // Create a sandbox and run a command const sandbox = await sdk.sandboxes.create(); const client = await sandbox.connect(); const output = await client.commands.run("echo 'Hello World'"); console.log(output); // Hello World ``` ``` -------------------------------- ### Setup API Source: https://context7.com/codesandbox/docs/llms.txt The Setup API monitors and controls setup tasks that run when a sandbox starts. ```APIDOC ## Setup API The Setup API monitors and controls setup tasks that run when a sandbox starts. ### Methods - `status`: Gets the current setup status. - `waitUntilComplete()`: Waits for all setup tasks to complete. - `getSteps()`: Retrieves all setup steps. ### Example Usage ```typescript const client = await sandbox.connect(); // Check setup status console.log(`Setup status: ${client.setup.status}`); // Wait for all setup tasks to complete await client.setup.waitUntilComplete(); // Or handle each step individually const steps = await client.setup.getSteps(); for (const step of steps) { console.log(`Step: ${step.name}`); console.log(`Command: ${step.command}`); console.log(`Status: ${step.status}`); const output = await step.open(); step.onOutput((data) => { console.log(data); }); await step.waitUntilComplete(); } ``` ``` -------------------------------- ### Setup Tasks Configuration Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/vm-sandboxes/task.mdx Configure sequential setup tasks that run before the workspace is ready. If not provided, dependency installation is the default. ```json { "$schema": "https://codesandbox.io/schemas/tasks.json", "setupTasks": [ { "name": "Installing Dependencies", "command": "yarn install" }, { "name": "Building Workspace", "command": "yarn build" } ] } ``` -------------------------------- ### Install @codesandbox/utils Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/environment/preview-urls.mdx Install the zero-dependency JavaScript library to simplify getting the current hostname for preview URLs. Choose the package manager that suits your project. ```bash npm i @codesandbox/utils ``` ```bash pnpm i @codesandbox/utils ``` ```bash yarn add @codesandbox/utils ``` -------------------------------- ### Example build log output Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/cli.mdx This example shows the real-time progress updates and step-by-step tracking during a container build process. ```text Building and starting container (RUN npm install --production)... Building and starting container (Successfully installed dependencies)... ``` -------------------------------- ### Automate Docker Compose Startup with Setup Tasks Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/templates.mdx Integrate `docker-compose up` into your CodeSandbox template's setup tasks to automatically start services when a Sandbox is created. ```json { // Runs in the workspace directory "setupTasks": ["docker-compose up"] } ``` -------------------------------- ### Monitor and Control Setup Tasks with Setup API Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/setup.mdx Use the CodeSandbox client's Setup API to get the status of setup tasks, wait for their completion, and access their output. This API allows for granular control and monitoring of the initialization process. ```typescript console.log(`Setup status: ${client.setup.status}`); // Wait for the whole thing to complete await client.setup.waitUntilComplete() // Or handle each step const steps = await client.setup.getSteps() for (const step of steps) { console.log(`Step: ${step.name}`); console.log(`Command: ${step.command}`); console.log(`Status: ${step.status}`); const output = await step.open() output.onOutput((output) => { console.log(output) }) await step.waitUntilComplete() } ``` -------------------------------- ### Setup API Usage Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/setup.mdx This snippet demonstrates how to use the CodeSandbox SDK's Setup API to monitor the status of setup tasks, wait for their completion, and access details of individual steps, including their output. ```APIDOC ## Setup API Usage ### Description This section demonstrates how to interact with the CodeSandbox SDK's Setup API to monitor and manage setup tasks. ### Method N/A (Client-side JavaScript API) ### Endpoint N/A (Client-side JavaScript API) ### Parameters N/A ### Request Example ```javascript // Accessing setup status console.log(`Setup status: ${client.setup.status}`); // Waiting for all setup tasks to complete await client.setup.waitUntilComplete(); // Handling individual setup steps const steps = await client.setup.getSteps(); for (const step of steps) { console.log(`Step: ${step.name}`); console.log(`Command: ${step.command}`); console.log(`Status: ${step.status}`); // Opening a stream to the step's output const output = await step.open(); // Listening for output events output.onOutput((output) => { console.log(output); }); // Waiting for a specific step to complete await step.waitUntilComplete(); } ``` ### Response #### Success Response (Various) - `client.setup.status` (string) - The overall status of the setup process (e.g., 'running', 'completed', 'failed'). - `steps` (array) - An array of objects, where each object represents a setup step. - `step.name` (string) - The name of the setup step. - `step.command` (string) - The command executed for the setup step. - `step.status` (string) - The status of the individual setup step. - `output` (object) - An object representing the output stream of a step. - `output.onOutput` (function) - A callback function that receives output logs. #### Response Example ```json { "status": "completed" } ``` ```json [ { "name": "Install Dependencies", "command": "pnpm install", "status": "completed" }, { "name": "Copy Environment File", "command": "cp .env.example .env", "status": "completed" } ] ``` ```json { "output": "... installation logs ..." } ``` ``` -------------------------------- ### Automate Installs with Chokidar Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/templates.mdx Use chokidar to trigger commands, like 'npm install', only when specific files (e.g., package.json) change. This example sets up a dev server and an install task. ```json { "setupTasks": ["npm install -g chokidar", "npm install"], "tasks": { "dev-server": { "name": "Dev Server", "command": "npm run dev", "preview": { "port": 5173 }, "runAtStart": true }, "install": { "name": "Install Deps", "command": "chokidar \"package.json\" -c \"npm install\"" } } } ``` -------------------------------- ### Build Sandbox Snapshot Examples Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/cli.mdx Examples demonstrating various ways to use the 'csb build' command, including specifying directories, custom names, aliases, VM tiers, and ports. ```bash # Build a template from current directory csb build . ``` ```bash # Build with custom name and alias csb build ./my-project --name "My Template" --alias my-template ``` ```bash # Build with specific VM tiers and ports csb build ./web-app --vm-tier small --vm-build-tier medium --ports 3000 8080 ``` ```bash # Build in CI mode csb build ./project --ci ``` -------------------------------- ### Configure Setup Tasks in tasks.json Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/setup.mdx Define setup tasks that run automatically when a sandbox initializes. These are typically used for installing dependencies and performing initial builds. ```json { "setupTasks": [ { "name": "Install Dependencies", "command": "pnpm install" }, { "name": "Copy Environment File", "command": "cp .env.example .env" }, "pnpm run build" // Short form for { "name": "pnpm run build", "command": "pnpm run build" } ] } ``` -------------------------------- ### CLI Installation and Basic Usage Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/cli.mdx Instructions on how to install the CodeSandbox SDK CLI and use its basic commands, including interactive mode. ```APIDOC ## Installation ```bash npm install @codesandbox/sdk ``` ### Direct Usage with npx ```bash npx @codesandbox/sdk [options] ``` ## Usage ### Basic Usage ```bash csb [options] ``` ### Interactive Dashboard Running `csb` without any arguments launches an interactive dashboard: ```bash csb ``` ``` -------------------------------- ### Fork Sandbox Example Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/cli.mdx An example demonstrating how to fork a sandbox by providing its unique identifier. ```bash csb sandboxes fork abc123 ``` -------------------------------- ### Configure Sandbox Tasks (tasks.json) Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/templates.mdx Define setup tasks and controllable tasks for your sandbox. Setup tasks run once after the sandbox starts. Do not run long-running processes in setupTasks. ```json { "setupTasks": [ "npm install" ], "tasks": { "dev-server": { "name": "Dev Server", "command": "npm run dev", "preview": { "port": 5173 }, "runAtStart": true } } } ``` -------------------------------- ### List Sandboxes Examples Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/cli.mdx Examples showcasing different ways to list sandboxes, including filtering by status, specifying output fields, filtering by tags, and sorting by creation date. ```bash # List all sandboxes csb sandboxes list ``` ```bash # List running sandboxes with custom output csb sandboxes list --status running --output id,title,createdAt ``` ```bash # List sandboxes with specific tags csb sandboxes list --tags template,nodejs ``` ```bash # List recent sandboxes csb sandboxes list --since 2024-01-01 --order-by inserted_at --direction desc ``` -------------------------------- ### Initialize Preview Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/browser-previews.mdx Connect to the sandbox and create a preview instance. This example shows how to connect to a sandbox and then create a preview for a development server running on a specific port. ```APIDOC ## Initialize Preview ### Description Connect to the sandbox and create a preview instance. This example shows how to connect to a sandbox and then create a preview for a development server running on a specific port. ### Method Asynchronous function call ### Endpoint N/A (Client-side SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { connectToSandbox, createPreview } from '@codesandbox/sdk/browser' const client = await connectToSandbox({ session: initialSessionFromServer, getSession: (id) => fetchJson(`/api/sandboxes/${id}`) }) // We have a dev server running on port 5173 const preview = createPreview(client.hosts.getUrl(5173)) document.querySelector('#preview-container').appendChild(preview.iframe) ``` ### Response #### Success Response (200) N/A (Client-side SDK) #### Response Example N/A ``` -------------------------------- ### Handle Clean Bootup on Client Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/resume.mdx When a client connects to a sandbox that had a 'CLEAN' bootup, this code retrieves and executes setup steps, logging their progress and output. ```typescript const client = await connectToSandbox({ session, getSession: (id) => fetchJSON(`/api/sandboxes/${id}`) }) if (client.bootupType === 'CLEAN') { const steps = await clients.setup.getSteps() for (const step of setupSteps) { console.log(`Step: ${step.name}`); console.log(`Command: ${step.command}`); console.log(`Status: ${step.status}`); const output = await step.open() output.onOutput((output) => console.log(output)) await step.waitUntilComplete() } } ``` -------------------------------- ### Install and Use CodeSandbox CLI Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/browser-sandboxes/cli-api.mdx Install the CodeSandbox CLI globally using npm and then use it to import a local project by specifying the directory. ```bash $ npm install -g codesandbox $ codesandbox ./ ``` -------------------------------- ### Monitor and Control Sandbox Setup Source: https://context7.com/codesandbox/docs/llms.txt Check the status of sandbox setup tasks, wait for them to complete, or handle individual steps. Provides insights into the sandbox initialization process. ```typescript const client = await sandbox.connect(); // Check setup status console.log(`Setup status: ${client.setup.status}`); // Wait for all setup tasks to complete await client.setup.waitUntilComplete(); // Or handle each step individually const steps = await client.setup.getSteps(); for (const step of steps) { console.log(`Step: ${step.name}`); console.log(`Command: ${step.command}`); console.log(`Status: ${step.status}`); const output = await step.open(); step.onOutput((data) => { console.log(data); }); await step.waitUntilComplete(); } ``` -------------------------------- ### Install CodeSandbox SDK Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/index.mdx Install the CodeSandbox SDK using npm. Ensure you have a CodeSandbox account and an API key with all scopes enabled, exposed as CSB_API_KEY. ```bash npm install @codesandbox/sdk ``` -------------------------------- ### Install Dependencies and Build with Dockerfile Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/templates.mdx Use this Dockerfile snippet to install common tools like zsh, bash, git, and curl, and enable corepack for package managers. Ensure zsh is included as it's the default shell. ```shell # ---- Builder: install deps & build ---- FROM node:22-alpine AS builder # Install zsh and bash (and optionally git, curl, etc.) RUN apk add --no-cache zsh bash git curl # Enable corepack (pnpm/yarn) if you use it; safe to keep on RUN corepack enable WORKDIR /workspace/project ``` -------------------------------- ### Basic OpenTelemetry Setup with CodeSandbox SDK Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/tracing.mdx Initialize OpenTelemetry with Node.js auto-instrumentations and then use the obtained tracer with the CodeSandbox SDK. This setup enables tracing for both your application and SDK operations. ```typescript import { NodeSDK } from '@opentelemetry/sdk-node'; import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; import { CodeSandbox } from '@codesandbox/sdk'; // Initialize OpenTelemetry const sdk = new NodeSDK({ instrumentations: [getNodeAutoInstrumentations()] }); sdk.start(); // Get tracer and use with CodeSandbox SDK const tracer = trace.getTracer('my-app'); const csb = new CodeSandbox({ tracer }); ``` -------------------------------- ### Install codesandboxer-fs CLI Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/browser-sandboxes/cli-api.mdx Install the codesandboxer-fs CLI globally to export projects. This tool helps in creating sandboxes from local files. ```bash $ npm install -g codesandboxer-fs ``` -------------------------------- ### Create Sandbox from Template Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/template-library.mdx Use the `sdk.sandboxes.create` method with a template ID to initialize a new sandbox. This is the primary way to start a project from a predefined template. ```typescript const sandbox = await sdk.sandboxes.create({ id: 'some-template-id' }) ``` -------------------------------- ### Get Specific Task Information Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/tasks.mdx Retrieves detailed information about a specific task using its ID. Logs the task's name, command, status, and whether it runs at start. ```typescript const task = client.tasks.get("build"); if (task) { console.log(`Task: ${task.name}`); console.log(`Command: ${task.command}`); // "RUNNING" | "FINISHED" | "ERROR" | "KILLED" | "RESTARTING" | "IDLE" console.log(`Status: ${task.status}`); console.log(`Runs at start: ${task.runAtStart}`); } ``` -------------------------------- ### Restart Sandbox Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/restart-shutdown.mdx Restarts a sandbox. This action does not use a snapshot and will start the sandbox from scratch, installing dependencies, building resources, and running with the latest agent version. A new reference to the sandbox is returned, requiring a new session. ```APIDOC ## Restart Sandbox ### Description Restarts a sandbox. This action does not use a snapshot and will start the sandbox from scratch, installing dependencies, building resources, and running with the latest agent version. A new reference to the sandbox is returned, requiring a new session. ### Method `POST` ### Endpoint `/sandboxes/{sandboxId}/restart` ### Parameters #### Path Parameters - **sandboxId** (string) - Required - The ID of the sandbox to restart. ### Request Example ```ts let sandbox = await sdk.sandboxes.resume('sandbox-id') sandbox = await sdk.sandboxes.restart(sandbox.id); ``` ### Response #### Success Response (200) - **sandbox** (object) - The updated sandbox object with a new reference. #### Response Example ```json { "id": "sandbox-id", "name": "My Sandbox", "status": "running" } ``` ``` -------------------------------- ### Install VS Code Extension for CodeSandbox Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/faq.mdx This is the command to install the CodeSandbox VS Code extension. Ensure you have VS Code installed. ```bash code --install-extension CodeSandbox-io.codesandbox-projects ``` -------------------------------- ### Build and Deploy Template with CLI Source: https://context7.com/codesandbox/docs/llms.txt Build a local project as a CodeSandbox template and deploy it, specifying the ports to expose. ```bash # Build and deploy the template npx @codesandbox/sdk build ./my-template --ports 5173 ``` -------------------------------- ### Initialize SDK and Run Command Source: https://context7.com/codesandbox/docs/llms.txt Initialize the CodeSandbox SDK and execute a command within a newly created sandbox. Ensure the CSB_API_KEY environment variable is set. ```javascript import { CodeSandbox } from "@codesandbox/sdk"; // Initialize SDK (uses CSB_API_KEY environment variable) const sdk = new CodeSandbox(); // Create a sandbox and run a command const sandbox = await sdk.sandboxes.create(); const client = await sandbox.connect(); const output = await client.commands.run("echo 'Hello World'"); console.log(output); // Hello World ``` -------------------------------- ### Create and Connect to a Sandbox Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/index.mdx Initialize the CodeSandbox SDK, create a new sandbox, connect to it, and run a command. The output of the command will be logged to the console. ```javascript import { CodeSandbox } from "@codesandbox/sdk"; const sdk = new CodeSandbox(); const sandbox = await sdk.sandboxes.create(); const client = await sandbox.connect(); const output = await client.commands.run("echo 'Hello World'"); console.log(output) // Hello World ``` -------------------------------- ### Basic Dockerfile for Ubuntu Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/tutorial/getting-started-with-docker.mdx A simple Dockerfile to set up an Ubuntu-based development environment. It installs the 'htop' package by default. This Dockerfile is intended for development and assumes the project directory is mounted at /workspace. ```docker FROM ubuntu # Install htop by default RUN apt update -y && apt install -y htop ``` -------------------------------- ### Create Project and Sandbox Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/manage-sandboxes.mdx Creates a new project and its associated sandbox. Initializes the sandbox and sets up the project in the database. ```typescript import express from 'express'; const app = express(); app.use(express.json()); // ---- in-memory connection tracking ---- const activeConnCount = new Map(); // sandboxId -> number // POST /api/projects - Create a new project app.post('/api/projects', async (req, res) => { const { userId, projectName, templateId = 'some-template-id' } = req.body; const sandbox = await sdk.sandboxes.create({ id: templateId }); const project = await db.projects.create({ id: generateId(), userId, name: projectName, sandboxId: sandbox.id, templateId, status: 'active', createdAt: new Date(), lastAccessedAt: new Date(), lastActivityAt: new Date(), }); const session = await sandbox.createSession(); await ensureCleanBootSetup(sandbox); res.json({ project, session }); }); ``` -------------------------------- ### Generate GET Request Parameters for Define API Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/browser-sandboxes/cli-api.mdx Use the `getParameters` utility from the `codesandbox` dependency to compress sandbox definition data into a string suitable for URL parameters in a GET request. ```javascript import { getParameters } from 'codesandbox/lib/api/define'; const parameters = getParameters({ files: { 'index.js': { content: "console.log('hello')", }, 'package.json': { content: { dependencies: {} }, }, }, }); const url = `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}`; ``` -------------------------------- ### Create New Vite Project with CLI Source: https://context7.com/codesandbox/docs/llms.txt Initialize a new project using Vite as a template for creating custom CodeSandbox templates. ```bash # Create a new template project npx create-vite@latest my-template ``` -------------------------------- ### Create and Interact with Browser Previews Source: https://context7.com/codesandbox/docs/llms.txt Set up a browser client, wait for a development server port, create a preview iframe, and attach it to the DOM. Listen for messages and control navigation. ```typescript import { connectToSandbox, createPreview } from '@codesandbox/sdk/browser'; const client = await connectToSandbox({ session: initialSessionFromServer, getSession: (id) => fetchJson(`/api/sandboxes/${id}`) }); // Wait for dev server port before creating preview const portInfo = await client.ports.waitForPort(5173); const preview = createPreview(portInfo.host); // Attach preview iframe to DOM document.querySelector('#preview-container').appendChild(preview.iframe); ``` -------------------------------- ### Handle Clean Bootup on Server Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/resume.mdx If a sandbox resumes with a 'CLEAN' bootup type, it means a memory snapshot was unavailable. This code connects to the sandbox and sets up its environment by running setup tasks. ```typescript const sandbox = await sdk.sandboxes.resume('sandbox-id'); if (sandbox.bootupType === 'CLEAN') { const client = await sandbox.connect() const steps = await clients.setup.getSteps() for (const step of setupSteps) { await step.waitUntilComplete() } } ``` -------------------------------- ### Tasks Configuration (tasks.json) Source: https://context7.com/codesandbox/docs/llms.txt Defines setup and runnable tasks for a CodeSandbox environment. ```APIDOC ## Tasks Configuration (`tasks.json`) ### Description Configure setup tasks and runnable tasks in `.codesandbox/tasks.json` to define your development environment. ### Schema ```json { "$schema": "https://codesandbox.io/schemas/tasks.json", "setupTasks": [ // ... setup task objects ], "tasks": { "[taskId]": { // ... task object } } } ``` ### `setupTasks` An array of tasks that run automatically during the sandbox setup process. - **name** (string) - Required - A display name for the setup task. - **command** (string) - Required - The shell command to execute. ### `tasks` An object where keys are task IDs and values are task configurations. - **`[taskId]`** (object) - Configuration for a specific task. - **name** (string) - Required - A display name for the task. - **command** (string) - Required - The shell command to execute. - **runAtStart** (boolean) - Optional - If `true`, the task will run automatically when the sandbox starts. - **preview** (object) - Optional - Configuration for previewing the task's output. - **port** (number) - Required if `preview` is present - The port the application will listen on. - **prLink** (string) - Optional - Specifies how the preview link should be generated (e.g., `direct`). ### Example Configuration ```json { "$schema": "https://codesandbox.io/schemas/tasks.json", "setupTasks": [ { "name": "Install Dependencies", "command": "npm install" }, { "name": "Build Project", "command": "npm run build" } ], "tasks": { "dev-server": { "name": "Development Server", "command": "npm run dev", "runAtStart": true, "preview": { "port": 3000, "prLink": "direct" } }, "test": { "name": "Run Tests", "command": "npm test" }, "lint": { "name": "Lint Code", "command": "npm run lint" } } } ``` ``` -------------------------------- ### Getting Task Information Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/tasks.mdx Retrieves detailed information about a specific task by its ID. ```APIDOC ## GET /tasks/{taskId} ### Description Retrieves detailed information about a specific task using its unique identifier. ### Method GET ### Endpoint /tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The unique identifier of the task. ### Request Example None ### Response #### Success Response (200) - **name** (string) - The name of the task. - **command** (string) - The command executed by the task. - **status** (string) - The current status of the task (e.g., "RUNNING", "FINISHED", "ERROR", "KILLED", "RESTARTING", "IDLE"). - **runAtStart** (boolean) - Indicates if the task is configured to run at sandbox startup. #### Response Example ```json { "name": "build", "command": "react-scripts build", "status": "IDLE", "runAtStart": false } ``` ``` -------------------------------- ### Getting Port Information Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/ports.mdx Retrieve a list of all currently open ports in the sandbox. ```APIDOC ## Getting Port Information ### Description Get information about currently opened ports in the sandbox. ### Method `client.ports.getAll()` ### Endpoint `client.ports` ### Parameters None ### Request Example ```ts // Get all opened ports const openPorts = client.ports.getAll(); for (const port of openPorts) { console.log(`Port ${port.port} is open at ${port.host}`); } ``` ### Response #### Success Response (200) - **openPorts** (array) - An array of objects, where each object contains information about an open port. - **port** (number) - The port number. - **host** (string) - The URL to access the port. #### Response Example ```json [ { "port": 3000, "host": "https://-3000.csb.app" }, { "port": 8080, "host": "https://-8080.csb.app" } ] ``` ``` -------------------------------- ### Create Vite Project for Template Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/templates.mdx Use this command to initialize a new Vite project that will serve as the base for your CodeSandbox template. ```bash npx create-vite@latest my-template ``` -------------------------------- ### Running a Task Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/tasks.mdx Executes a specific task. Can be used to start, restart, or stop a task. ```APIDOC ## POST /tasks/{taskId}/run ### Description Executes a specific task. If the task is already running, this action might restart it depending on the task's configuration. ### Method POST ### Endpoint /tasks/{taskId}/run ### Parameters #### Path Parameters - **taskId** (string) - Required - The unique identifier of the task to run. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message that the task has been initiated. #### Response Example ```json { "message": "Task 'dev' initiated." } ``` ## POST /tasks/{taskId}/restart ### Description Restarts a specific task. This is useful for applying changes or resetting a task's state. ### Method POST ### Endpoint /tasks/{taskId}/restart ### Parameters #### Path Parameters - **taskId** (string) - Required - The unique identifier of the task to restart. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message that the task has been restarted. #### Response Example ```json { "message": "Task 'dev' restarted." } ``` ## POST /tasks/{taskId}/stop ### Description Stops a running task. ### Method POST ### Endpoint /tasks/{taskId}/stop ### Parameters #### Path Parameters - **taskId** (string) - Required - The unique identifier of the task to stop. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message that the task has been stopped. #### Response Example ```json { "message": "Task 'dev' stopped." } ``` ``` -------------------------------- ### Waiting for Ports Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/ports.mdx Asynchronously wait for a specific port to become available, often used after starting a development server. ```APIDOC ## Waiting for Ports ### Description Wait for a specific port to become available in the sandbox. This is useful when starting services that need time to initialize. ### Method `client.ports.waitForPort(port: number)` ### Endpoint `client.ports` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts // Start a development server const command = client.commands.runBackground("npm run dev"); // Wait for the dev server port to open const portInfo = await client.ports.waitForPort(3000); console.log(`Dev server is ready at: ${portInfo.host}`); ``` ### Response #### Success Response (200) - **portInfo** (object) - Information about the opened port. - **port** (number) - The port number that became available. - **host** (string) - The URL to access the port. #### Response Example ```json { "port": 3000, "host": "https://-3000.csb.app" } ``` ``` -------------------------------- ### Default tasks.json Configuration Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/vm-sandboxes/task.mdx This is a default configuration for `.codesandbox/tasks.json`. It includes setup tasks and defines custom tasks with names and commands. ```json { "$schema": "https://codesandbox.io/schemas/tasks.json", "setupTasks": ["yarn install", "yarn build"], "tasks": { "install-dependencies": { "name": "Install Dependencies", "command": "yarn install" }, "start-app": { "name": "Run Dev Server", "command": "yarn start", "runAtStart": true } } } ``` -------------------------------- ### Connect to Sandbox and Create Preview Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/browser-previews.mdx Connect to the sandbox and create a preview iframe. Ensure a dev server is running on the specified port. The iframe is appended to a container element. ```typescript import { connectToSandbox, createPreview } from '@codesandbox/sdk/browser' const client = await connectToSandbox({ session: initialSessionFromServer, getSession: (id) => fetchJson(`/api/sandboxes/${id}`)) }) // We have a dev server running on port 5173 const preview = createPreview(client.hosts.getUrl(5173)) document.querySelector('#preview-container').appendChild(preview.iframe) ``` -------------------------------- ### Monitoring Ports Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/ports.mdx Listen for events when ports are opened or closed within the sandbox. This is useful for reacting to services starting or stopping. ```APIDOC ## Monitoring Ports ### Description Listen for ports being opened and closed in your sandbox. ### Method Event Listeners ### Endpoint `client.ports` ### Parameters None ### Request Example ```ts // Listen for ports being opened const listener1 = client.ports.onDidPortOpen((portInfo) => { console.log(`Port ${portInfo.port} opened`); console.log(`URL: ${client.hosts.getUrl(portInfo.port)}`); }); // Listen for ports being closed const listener2 = client.ports.onDidPortClose((port) => { console.log(`Port ${port} closed`); }); // Remove listeners when done listener1.dispose(); listener2.dispose(); ``` ### Response #### Success Response (Event Data) - **portInfo** (object) - Information about the opened port, including `port` (number) and `host` (string). - **port** (number) - The port number that was closed. #### Response Example ```json // On port open: { "port": 3000, "host": "https://-3000.csb.app" } // On port close: 3000 ``` ``` -------------------------------- ### Create Project with Git Initialization Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/manage-sandboxes.mdx Use this endpoint to create a new project, initialize its Git repository with a remote origin, and push the initial commit. Requires user ID, project name, and repository URL. ```typescript // POST /api/projects - Create project with git initialization app.post('/api/projects', async (req, res) => { const { userId, projectName, repositoryUrl } = req.body; // Create sandbox from template const sandbox = await sdk.sandboxes.create({ id: 'some-template-id' }); const client = await sandbox.connect(); // Initialize Git remote await client.commands.run([ `git remote remove origin` `git remote add origin ${repositoryUrl}` 'git push -u origin main' ]); client.dispose() // Save project to database const project = await db.projects.create({ id: generateId(), userId, name: projectName, sandboxId: sandbox.id, repositoryUrl, status: 'active', lastActivityAt: new Date(), createdAt: new Date() }); const session = await sandbox.createSession(); res.json({ project, session }); }); ``` -------------------------------- ### Long Running Commands Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/commands.mdx This section details how to manage long-running commands, such as starting a server, and how to use `waitForPort` to ensure a service is ready. ```APIDOC ## Long Running Commands ### Description Manage commands that take a significant amount of time to complete, such as starting a development server. This includes methods to wait for a specific port to become available. ### Method `client.ports.waitForPort(port: number, options?: { host?: string }) Waits until the specified port is open and ready to accept connections. ### Parameters - **port** (number) - Required - The port number to wait for. - **options** (object) - Optional - Configuration options for waiting for the port. - **host** (string) - Optional - The host to check for the port. Defaults to localhost. ### Response Example ```json { "port": 3000, "host": "localhost" } ``` ### Example Usage ```typescript // Run a long running command const command = client.commands.runBackground("npx -y serve ."); // Wait for the port to open const portInfo = await client.ports.waitForPort(3000); // You will need to manually kill it command.kill(); // Or you can also restart a command that is already running command.restart(); ``` For long running commands, consider using [tasks](/sdk/tasks.mdx). ``` -------------------------------- ### CodeSandbox Tasks Configuration Source: https://context7.com/codesandbox/docs/llms.txt Defines setup tasks and development server configurations for a CodeSandbox template, including commands and preview port settings. ```json // my-template/.codesandbox/tasks.json { "setupTasks": [ "npm install" ], "tasks": { "dev-server": { "name": "Dev Server", "command": "npm run dev", "preview": { "port": 5173 }, "runAtStart": true } } } ``` -------------------------------- ### Start Sandbox with Specific VM Tier Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/specs.mdx Use the `vmTier` option with `VMTier.Small` to create a sandbox with predefined 'Small' VM specs. Ensure the CodeSandbox SDK is imported. ```typescript import { CodeSandbox, VMTier } from "@codesandbox/sdk"; const sdk = new CodeSandbox(); const sandbox = await sdk.sandboxes.create({ vmTier: VMTier.Small }); ``` -------------------------------- ### Verify PHP Version Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/tutorial/getting-started-with-dev-containers.mdx Command to check the installed PHP version in the Dev Container. This command can be run after adding the PHP feature and rebuilding. ```sh php -v ``` -------------------------------- ### Add a preview host Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/cli.mdx Add a new host to the list of preview hosts. Requires the host name as an argument. ```bash csb preview-hosts add example.com ``` -------------------------------- ### Verify Node Version Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/tutorial/getting-started-with-dev-containers.mdx Command to check the installed Node.js version in the Dev Container. Ensure this command is run in a terminal within the container. ```sh node --version ``` -------------------------------- ### Get Information on Open Ports Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/ports.mdx Retrieve a list of all currently open ports and their associated hosts. Iterate through the list to access details for each port. ```typescript const openPorts = client.ports.getAll(); for (const port of openPorts) { console.log(`Port ${port.port} is open at ${port.host}`); } ``` -------------------------------- ### Basic Dev Container Configuration Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/tutorial/getting-started-with-dev-containers.mdx Sets up a basic Node.js development environment using a pre-built image. This is the initial configuration file for a Dev Container. ```json { "name": "Dev Container tutorial", "image": "mcr.microsoft.com/devcontainers/javascript-node:20" } ``` -------------------------------- ### Get Preview URL with @codesandbox/utils Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/learn/environment/preview-urls.mdx Use the getCodeSandboxHost function from the @codesandbox/utils library to construct the preview URL. This works in both frontend and backend environments. ```javascript import { getCodeSandboxHost } from '@codesandbox/utils'; const port = 3000; const previewUrl = `https://${getCodeSandboxHost(port)}`; ``` -------------------------------- ### Create Sandbox and Connect Source: https://github.com/codesandbox/docs/blob/main/packages/projects-docs/pages/sdk/users.mdx Use this to create a new Sandbox and establish a connection to it using the default global user. ```typescript const sandbox = await sdk.sandboxes.create({ id: 'some-template-id' }) const client = await sandbox.connect() ```