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

# Preview environments

> Every pull request gets its own machine, created from a snapshot of your app, live at its own URL.

Every pull request gets its own machine running the branch's exact code, live at a predictable `*.boxd.sh` URL that gets posted on the PR. Reviewers click it and land on a full Linux machine, so two reviewers can poke at two different PRs without stepping on each other's writes. Close the PR and the machine is deleted.

<video autoPlay muted loop playsInline src="/videos/preview-pr.mp4" />

Here GitHub Actions starts the preview. You can also skip GitHub Actions and run it on boxd, which is faster.

The whole thing is two small SDK scripts on top of one primitive: creating a machine from a snapshot.

## How it works

You maintain a [snapshot of your app](/guides/snapshot-your-app.md): a machine with your app installed and running, re-saved on every push to main so it always reflects your latest code. That guide is the prerequisite for this page.

On every PR, a script creates a machine from the latest snapshot, named for the PR:

```bash
boxd machine new myapp-pr-482 --from-snapshot my-workspace
```

<video autoPlay muted loop playsInline src="/videos/from-snapshot.mp4" />

Save a snapshot, then start a machine from it. Booted in 4ms.

The machine starts with the app already serving main's code, since a snapshot captures memory and disk together. The script then checks out the PR branch inside it, rebuilds what the diff needs, and the preview is live at `https://myapp-pr-482.boxd.sh`. On new pushes the machine is recreated from the latest snapshot, and because the name is reused, the URL stays stable across the PR's whole life. On close, one command removes it.

## The scripts

Two small scripts cover the full lifecycle. The recommended way to run them is through the [TypeScript](/reference/typescript-sdk.md) or [Python](/reference/python-sdk.md) SDK, which reads a `BOXD_API_KEY` from the environment and handles authentication for you.

Bring a preview up, or refresh it after a push:

> [tab] TypeScript
>
> ```typescript preview-up.ts
> import { Boxd } from "@boxd-sh/sdk";
>
> const [prNumber, branch] = process.argv.slice(2);
> const name = `myapp-pr-${prNumber}`;
>
> const boxd = new Boxd();                       // reads BOXD_API_KEY
>
> // Recreate from the latest snapshot. The reused name keeps the URL stable.
> await boxd.machines.delete(name).catch(() => {});
> const machine = await boxd.machines.create({
>   name,
>   fromSnapshot: "my-workspace",
>   config: { autoSuspendTimeout: 300 },
> });
> await boxd.machines.waitUntilReady(machine.id);
> await boxd.machines.setAutoHibernateTimeout(machine.id, 1800);   // hibernate after 30 min idle
>
> const r = await boxd.machines.exec(machine.id, {
>   command: `cd ~/myapp && git fetch origin ${branch} \
>     && git checkout -B preview FETCH_HEAD \
>     && npm ci && sudo systemctl restart myapp`,
> });
> if (!r.success) throw new Error(r.stderr);     // fail the job, don't post a stale preview
>
> console.log(`Preview: ${machine.access.url}`);
> await boxd.close();
> ```

> [tab] Python
>
> ```python preview_up.py
> import sys
> from boxd import Boxd, NotFoundError
>
> pr_number, branch = sys.argv[1:3]
> name = f"myapp-pr-{pr_number}"
>
> with Boxd() as boxd:                       # reads BOXD_API_KEY
>     # Recreate from the latest snapshot. The reused name keeps the URL stable.
>     try:
>         boxd.machines.delete(name)
>     except NotFoundError:
>         pass
>     machine = boxd.machines.create(name, from_snapshot="my-workspace", auto_suspend_timeout=300)
>     boxd.machines.wait_until_ready(machine.id)
>     boxd.machines.set_auto_hibernate_timeout(machine.id, 1800)   # hibernate after 30 min idle
>
>     r = boxd.machines.exec(machine.id, (
>         f"cd ~/myapp && git fetch origin {branch} "
>         "&& git checkout -B preview FETCH_HEAD "
>         "&& npm ci && sudo systemctl restart myapp"
>     ))
>     if not r.success:                      # fail the job, don't post a stale preview
>         sys.exit(r.stderr)
>     print(f"Preview: {machine.access.url}")
> ```

Tear it down when the PR closes:

> [tab] TypeScript
>
> ```typescript preview-down.ts
> import { Boxd } from "@boxd-sh/sdk";
>
> const boxd = new Boxd();
> await boxd.machines.delete(`myapp-pr-${process.argv[2]}`).catch(() => {});
> await boxd.close();
> ```

> [tab] Python
>
> ```python preview_down.py
> import sys
> from boxd import Boxd, NotFoundError
>
> with Boxd() as boxd:
>     try:
>         boxd.machines.delete(f"myapp-pr-{sys.argv[1]}")
>     except NotFoundError:
>         pass
> ```

Swap the rebuild command (`npm ci && sudo systemctl restart myapp`) for whatever your stack needs. An API key from `boxd auth keys create` acts as you, so the preview is your private machine: with [Git](/guides/integrations/connections.md#git) connected, the `git fetch` inside it works against private repos with nothing extra to configure. On a shared machine, `git` uses the [GitHub App](/guides/integrations/connections.md#github-app) instead.

## Wire it into CI

Store the key as a repo secret:

```bash
boxd auth keys create "previews" | gh secret set BOXD_API_KEY --repo you/myapp
```

Then add one workflow. It brings the preview up on every push to the PR, comments the URL, and removes the machine when the PR closes:

```yaml .github/workflows/preview.yml
name: preview
on:
  pull_request:
    types: [opened, synchronize, reopened, closed]

# rapid pushes to one PR queue up instead of racing each other
concurrency: preview-${{ github.event.pull_request.number }}

permissions:
  contents: read
  pull-requests: write

defaults:
  run:
    shell: bash

env:
  BOXD_API_KEY: ${{ secrets.BOXD_API_KEY }}
  GH_TOKEN: ${{ github.token }}
  PR: ${{ github.event.pull_request.number }}
  BRANCH: ${{ github.head_ref }}

jobs:
  up:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: oven-sh/setup-bun@v2
      - run: bun install
      - run: bun run preview-up.ts "$PR" "$BRANCH" | tee up.log
      - run: gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "$(grep '^Preview:' up.log)"

  down:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: oven-sh/setup-bun@v2
      - run: bun install
      - run: bun run preview-down.ts "$PR"
```

Any other CI works the same way: run the first script when a PR opens or gets a push, the second when it closes.

### Or skip GitHub Actions

The fastest setup runs on boxd itself. An [automation](/guides/automations/managing-machines.md#fan-work-out-to-fresh-machines) receives the pull request event through the [boxd GitHub App](/guides/integrations/connections.md#github-app) and runs the same steps, so no runner has to start first and there is no API key to store.

## Patterns

### A stable URL per PR

The machine is named for the PR number, so each PR keeps `https://myapp-pr-<n>.boxd.sh` across every push. That makes it a steady target for screenshot diffs and Playwright runs, and reviewers keep refreshing the same link.

> [!NOTE]
>
> A preview asks for a [bot protection](/guides/bot-protection.md) check before it wakes, and with the **On** mode while it runs too. Reviewers pass it in their browser, but headless Playwright runs and other CI jobs may not. Turn it off for previews that automated jobs hit with `boxd machine config set myapp-pr-482 bot-protection off`.

### Preview data without a staging database

Run a local database on the source machine before you snapshot it. Every preview then inherits a copy of that data, and writes stay inside that one preview. Reset comes free with the next recreate.

### More than a URL

Each preview is a full machine you own. `ssh myapp-pr-482.boxd` gets you a shell in the exact environment the reviewer is looking at, and `boxd machine exec` lets other jobs run tests against it.

### Previews sleep when not in use

The script sets a 5-minute auto-suspend and a 30-minute auto-hibernate, so an idle preview goes to standby and then hibernates. The next click on its link wakes it, and only that one.

<video autoPlay muted loop playsInline src="/videos/preview-sleep.mp4" />

Ten previews, all hibernated. Opening one wakes only that one.

## FAQ

> [accordion] What does a preview cost while nobody is clicking it?
>
> Very little, on two levels. The 5-minute auto-suspend puts an idle preview on standby, where it bills for memory and disk but no vCPU, and clicking the link resumes it in sub-millisecond time. The 30-minute auto-hibernate then moves it to disk, where it bills for disk only, and the next click wakes it in about 85ms. A PR sitting open over the weekend costs effectively nothing.

> [accordion] What happens if 5 PRs get previews at once?
>
> You get 5 machines, one per PR. The default cap is 50 machines per organization, extendable on request, and the source machine counts toward it too. Hibernated previews count as well.

> [accordion] How fresh is the code under the branch?
>
> The preview is created from the latest snapshot, which your [refresh workflow](/guides/snapshot-your-app.md#3-refresh-it-on-every-push-to-main) re-saves on every push to main. The PR branch is then checked out on top, so the diff against main is exactly what the rebuild has to cover.

> [accordion] Why recreate instead of reusing the machine on every push?
>
> Recreating from the snapshot gives every push a clean, known starting state for the price of one boot, and the reused name keeps the URL stable. If your rebuild is expensive and pushes are frequent, reuse the machine and run the checkout step alone.
