> ## 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.

# Preview environments

> A live preview of every branch or pull request: the app's dev server running in a sandbox, at its own HTTPS link, updating as code changes, asleep when nobody looks, and gone when the branch is merged.

A reviewer should not have to download a branch and set it up on their own machine just to see a change. And an
agent that builds a user interface should **show** what it built, not only describe it.

A **preview environment** solves both. You give each branch, pull request or agent session **a sandbox running
the app's development server**. It has its own HTTPS link that you can share, it updates as the code changes, and
it sleeps when nobody is looking at it. Here is how it fits into a pull request's life:

| Event | Your automation |
| - | - |
| A pull request opens | Create a sandbox from the branch, start the dev server, comment the link on the PR |
| New commits | Pull into the same sandbox: the dev server reloads |
| Nobody looks for a while | Nothing: the sandbox sleeps, with no compute cost; the next visit wakes it |
| The PR is merged or closed | Delete the sandbox |

## A live Vite app at a public link

**1. A sandbox that serves port 3000**

```bash title="CLI" run theme={null}
PR=128
SBX=$(fibre create --port 3000 --idle-timeout 10m --lifetime 1d --label preview=true --label pr=$PR --json | jq -r .id)
```

```typescript title="TypeScript" run theme={null}
import { Sandbox } from "@fibre-dev/sdk";

const pr = 128;
const sbx = await Sandbox.create({
  exposedPort: 3000,
  idleTimeout: 600,
  lifetime: 86400,
  labels: { preview: "true", pr: String(pr) },
});
```

```python title="Python" run theme={null}
from fibre import Sandbox

pr = 128
sbx = Sandbox.create(exposed_port=3000, idle_timeout=600, lifetime=86400, labels={"preview": "true", "pr": str(pr)})
```

**2. Get the code**

In your pipeline, this step is a `git clone --branch` of the pull request's branch. To keep the example
self-contained, we write a small Vite app instead. (Vite is a popular development server for web apps.)

```bash title="CLI" run theme={null}
# in your pipeline: fibre exec "$SBX" -- git clone --depth 1 --branch "$BRANCH" "$REPO_URL" /work/app
fibre exec "$SBX" -i -- sh -c 'mkdir -p /work/app && cat > /work/app/package.json' <<'JSON'
{
  "name": "preview-demo",
  "private": true,
  "type": "module",
  "scripts": { "dev": "vite --host 0.0.0.0 --port 3000" },
  "devDependencies": { "vite": "^6.0.0" }
}
JSON
echo "<!doctype html><title>PR #$PR</title><h1 id=\"title\"></h1><script type=\"module\" src=\"/main.js\"></script>" \
  | fibre exec "$SBX" -i -- sh -c 'cat > /work/app/index.html'
echo "document.querySelector(\"#title\").textContent = \"Preview of PR #$PR: version 1\";" \
  | fibre exec "$SBX" -i -- sh -c 'cat > /work/app/main.js'
```

```typescript title="TypeScript" run theme={null}
// in your pipeline: await sbx.run(`git clone --depth 1 --branch ${branch} ${repoUrl} /work/app`)
await sbx.files.write("/work/app/package.json", JSON.stringify({
  name: "preview-demo", private: true, type: "module",
  scripts: { dev: "vite --host 0.0.0.0 --port 3000" },
  devDependencies: { vite: "^6.0.0" },
}, null, 2));
await sbx.files.write("/work/app/index.html",
  `<!doctype html><title>PR #${pr}</title><h1 id="title"></h1><script type="module" src="/main.js"></script>`);
await sbx.files.write("/work/app/main.js",
  `document.querySelector("#title").textContent = "Preview of PR #${pr}: version 1";`);
```

```python title="Python" run theme={null}
import json

# in your pipeline: sbx.run(f"git clone --depth 1 --branch {branch} {repo_url} /work/app")
sbx.files.write("/work/app/package.json", json.dumps({
    "name": "preview-demo", "private": True, "type": "module",
    "scripts": {"dev": "vite --host 0.0.0.0 --port 3000"},
    "devDependencies": {"vite": "^6.0.0"},
}, indent=2))
sbx.files.write("/work/app/index.html",
                f'<!doctype html><title>PR #{pr}</title><h1 id="title"></h1><script type="module" src="/main.js"></script>')
sbx.files.write("/work/app/main.js",
                f'document.querySelector("#title").textContent = "Preview of PR #{pr}: version 1";')
```

**3. Install and start the dev server**

Install the app's dependencies, then start the development server with `keep: true`, so it keeps running across
sleep and wake. Vite only answers requests for hostnames it knows about, so we tell it the sandbox's hostname
through an environment variable:

```bash title="CLI" run theme={null}
fibre exec "$SBX" --cwd /work/app -- npm install --silent

HOST=$(fibre url "$SBX" --json | jq -r .hostname)
fibre exec "$SBX" --cwd /work/app --env __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS=$HOST --detach --keep -- npm run dev
fibre exec "$SBX" --timeout 2m -- 'until curl -sf -o /dev/null localhost:3000; do sleep 1; done'

echo "Preview: $(fibre url "$SBX")"   # comment this on the pull request
```

```typescript title="TypeScript" run theme={null}
await sbx.run("cd /work/app && npm install --silent", { timeout: 300 });

await sbx.spawn(["npm", "run", "dev"], {
  cwd: "/work/app",
  keep: true,
  env: { __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: sbx.hostname },
});
await sbx.run("until curl -sf -o /dev/null localhost:3000; do sleep 1; done", { timeout: 120 });

console.log(`Preview: ${sbx.url}`); // comment this on the pull request
```

```python title="Python" run theme={null}
sbx.run("cd /work/app && npm install --silent", timeout=300)

sbx.spawn(["npm", "run", "dev"], cwd="/work/app", keep=True, env={"__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS": sbx.hostname})
sbx.run("until curl -sf -o /dev/null localhost:3000; do sleep 1; done", timeout=120)

print(f"Preview: {sbx.url}")  # comment this on the pull request
```

**4. Open the link**

```bash title="CLI" run theme={null}
URL=$(fibre url "$SBX")
curl -s "$URL" | grep -q main.js && echo "Vite is serving the app"
curl -s "$URL/main.js" | grep -q "version 1" && echo "version 1"
```

```typescript title="TypeScript" run theme={null}
const page = await fetch(sbx.url).then((r) => r.text());
console.log(page.includes("main.js")); // true: Vite is serving the app

const js = await fetch(`${sbx.url}/main.js`).then((r) => r.text());
console.log(js.includes("version 1")); // true
```

```python title="Python" run theme={null}
from urllib.request import urlopen

page = urlopen(sbx.url).read().decode()
print("main.js" in page)  # True: Vite is serving the app

js = urlopen(f"{sbx.url}/main.js").read().decode()
print("version 1" in js)  # True
```

**Anyone with the link now sees the running branch** in their own browser, with live reloading. They do not need
to download the code or set anything up.

**5. Push a change: the preview updates**

When new commits arrive, run `git pull` in the same sandbox. Vite notices the changed files, and any open page
reloads by itself. Here we change the file directly to show the effect:

```bash title="CLI" run theme={null}
# in your pipeline: fibre exec "$SBX" --cwd /work/app -- git pull
echo "document.querySelector(\"#title\").textContent = \"Preview of PR #$PR: version 2\";" \
  | fibre exec "$SBX" -i -- sh -c 'cat > /work/app/main.js'

sleep 1
curl -s "$URL/main.js" | grep -q "version 2" && echo "version 2: same sandbox, same link, new code"
```

```typescript title="TypeScript" run theme={null}
// in your pipeline: await sbx.run("cd /work/app && git pull")
await sbx.files.write("/work/app/main.js",
  `document.querySelector("#title").textContent = "Preview of PR #${pr}: version 2";`);

await new Promise((r) => setTimeout(r, 1000));
const updated = await fetch(`${sbx.url}/main.js`).then((r) => r.text());
console.log(updated.includes("version 2")); // true: same sandbox, same link, new code
```

```python title="Python" run theme={null}
import time

# in your pipeline: sbx.run("cd /work/app && git pull")
sbx.files.write("/work/app/main.js",
                f'document.querySelector("#title").textContent = "Preview of PR #{pr}: version 2";')

time.sleep(1)
updated = urlopen(f"{sbx.url}/main.js").read().decode()
print("version 2" in updated)  # True: same sandbox, same link, new code
```

## When the PR closes

When the pull request is merged or closed, find its sandbox by label and delete it:

```bash title="CLI" run theme={null}
fibre delete $(fibre list --label preview=true --label pr=$PR --json | jq -r '.[].id')
```

```typescript title="TypeScript" run theme={null}
for await (const s of Sandbox.list({ labels: { preview: "true", pr: String(pr) } })) await s.delete();
```

```python title="Python" run theme={null}
for s in Sandbox.list(labels={"preview": "true", "pr": str(pr)}):
    s.delete()
```

## In GitHub Actions

In practice, a CI workflow runs these steps for you. This GitHub Actions workflow runs a small script each time a
pull request is opened, updated or closed, with your Fibre key stored as a secret:

```yaml title=".github/workflows/preview.yml"  theme={null}
name: preview
on:
  pull_request:
    types: [opened, synchronize, closed]

jobs:
  preview:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22 }
      - run: npm install @fibre-dev/sdk
      - run: node scripts/preview.mjs
        env:
          FIBRE_API_KEY: ${{ secrets.FIBRE_API_KEY }}
          PR: ${{ github.event.pull_request.number }}
          BRANCH: ${{ github.head_ref }}
          ACTION: ${{ github.event.action }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
```

`scripts/preview.mjs` finds the pull request's sandbox by its label and uses the calls from this page. When the pull
request is opened, it creates the sandbox and posts the link as a comment. When new commits arrive, it pulls them.
When the pull request is closed, it deletes the sandbox.

## Good to know

A few things to keep in mind with previews:

| | |
| - | - |
| Dev servers | Listen on `0.0.0.0`, and allow the sandbox's hostname if the framework checks the `Host` header |
| Hot reload | Its WebSocket passes through the sandbox's URL |
| Sleep | After `idleTimeout` with nobody looking; **an open preview tab keeps it awake** |
| Who can open it | Anyone with the link. For private apps, put your own sign-in in front |
| Cost | Awake time only: a preview looked at for 15 minutes a day costs 15 minutes a day |

## Related

> [card] [Public URLs](https://docs.fibre.dev/connect/public-urls.md)
>
> How a sandbox's public address works.

> [card] [Snapshots](https://docs.fibre.dev/setup/snapshots.md)
>
> Start previews with dependencies already installed.


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