> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Use sandboxes from a web app

> Let the people using your web app run code, preview apps and watch agents in Fibre sandboxes, while your API key stays on your server: the pattern, a small server in TypeScript and Python, previews in a page, live output and CORS.

Many apps built on Fibre have a web page in front: a coding playground, an app builder that shows a live preview, a
data tool that runs Python for its users, or a dashboard that watches agents at work. The people using the page
never talk to Fibre directly. **Your server does**, and the page talks to your server.

> [!WARNING]
>
> **Never put your Fibre API key in code that runs in a browser.** Anyone who opens the page can read it, and with it
> they could create sandboxes on your account. Keep the key on your server, and give the browser only what it needs.

## The pattern

1. **The browser asks your server** to do something for the signed-in user: run this code, start my preview.
2. **Your server finds that user's sandbox**, or creates one, using labels such as `{"user": "42"}`
   (see [a sandbox per user](https://docs.fibre.dev/use-cases/sandbox-per-user.md)), and makes the Fibre calls with your key.
3. **Your server answers the browser** with the result: the command's output, or the address of a preview.

This keeps every decision on your side: who may run what, how much, and for how long.

## A small server

Here is a server with one route, `POST /api/run`, that runs a user's Python in their own sandbox and returns the
output. It finds the sandbox by the user's ID and creates it on first use. Add your own sign-in check where the
comment says so:

```typescript title="TypeScript (Node)" norun reason="runs in your own server" theme={null}
import { createServer } from "node:http";
import { Sandbox } from "@fibre-dev/sdk"; // FIBRE_API_KEY is set on the server, never in the page

async function sandboxFor(userId: string): Promise<Sandbox> {
  for await (const s of Sandbox.list({ labels: { app: "playground", user: userId } })) return s;
  return Sandbox.create({ labels: { app: "playground", user: userId }, idleTimeout: 120, lifetime: 86400 });
}

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/api/run") return void res.writeHead(404).end();
  const userId = "42"; // your sign-in: the user of this request
  let body = "";
  for await (const chunk of req) body += chunk;
  const { code } = JSON.parse(body);

  const sbx = await sandboxFor(userId);
  const r = await sbx.run(["python3", "-c", code], { timeout: 30 });
  res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ stdout: r.stdout, stderr: r.stderr, exitCode: r.exitCode }));
}).listen(8080);
```

```python title="Python (FastAPI)" norun reason="runs in your own server" theme={null}
from fastapi import FastAPI
from pydantic import BaseModel

from fibre import Sandbox  # FIBRE_API_KEY is set on the server, never in the page

app = FastAPI()


def sandbox_for(user_id: str) -> Sandbox:
    for s in Sandbox.list(labels={"app": "playground", "user": user_id}):
        return s
    return Sandbox.create(labels={"app": "playground", "user": user_id}, idle_timeout=120, lifetime=86400)


class Run(BaseModel):
    code: str


@app.post("/api/run")
def run(body: Run):
    user_id = "42"  # your sign-in: the user of this request
    sbx = sandbox_for(user_id)
    r = sbx.run(["python3", "-c", body.code], timeout=30)
    return {"stdout": r.stdout, "stderr": r.stderr, "exit_code": r.exit_code}
```

The page then calls your route like any other:

```javascript title="In the page" norun reason="runs in a browser" theme={null}
const answer = await fetch("/api/run", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ code: "print(6 * 7)" }),
}).then((r) => r.json());
console.log(answer.stdout); // 42
```

Because each user has their own sandbox, which sleeps between requests, a user who runs code again finds the
variables, files and packages of their last run still there.

## Show an app running in a sandbox

When the sandbox serves an app, such as a preview of what the user is building, create it with `exposed_port` and
start the app in the background. Its **public `url`** can go straight into the page, for example in an `iframe`:

```html title="In the page" norun reason="runs in a browser" theme={null}
<iframe src="https://sbx-1a2b3c4d5e.fibre.run" style="width: 100%; height: 600px; border: 0"></iframe>
```

Your server returns the URL to the page. Keep in mind that **anyone who has the URL can open the app**, as with any
public address, and a visit wakes a sleeping sandbox. See [public URLs](https://docs.fibre.dev/connect/public-urls.md).

## Show output as it happens

For long commands, such as an install, a build or an agent at work, the page should show output while it is being
written. Your server starts the command in the background, follows its output, and passes each piece on to the
browser, for example as [server-sent events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) or over
a WebSocket:

```typescript title="TypeScript (Node)" norun reason="runs in your own server" theme={null}
// inside a route handler, after finding the user's sandbox
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
const build = await sbx.spawn("npm run build", { cwd: "/work/app" });
for await (const chunk of build.output()) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
res.end(`data: ${JSON.stringify({ exitCode: (await build.wait()).exitCode })}\n\n`);
```

See [run commands](https://docs.fibre.dev/sandboxes/running-commands.md) for following, reattaching and stopping commands.

## Calls from the page to the sandbox's app (CORS)

If code in your page calls the app inside a sandbox directly, at its `url`, the browser treats that as a request
to another site and asks the app whether it allows it. That is the app's decision: **set CORS headers in the app
that runs in the sandbox**, as you would for any API on another domain. For example, a Node app can answer with
`Access-Control-Allow-Origin: https://your-app.example` and the methods and headers it accepts, and answer
`OPTIONS` requests itself.

## Watching an agent's browser or desktop

If an agent works in a sandbox's [browser](https://docs.fibre.dev/connect/browser.md), its **live view link** shows the browser and passes on
clicks and keys, and nothing else, so it is safe to show to a person in your page. Keep the browser's DevTools
address (`cdp_url`) on your server: it gives full control of the browser. A [desktop](https://docs.fibre.dev/connect/desktop.md) link works
once, for the first person who opens it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.