# Previews

> Keep a job's machine serving the change at its own private URL until its TTL, the branch's next push or the merge. Access tokens, lifetime and billing.

Source: https://bareci.com/docs/modules/previews

A preview keeps a job's machine after the job ends and serves the app at its own address through a Cloudflare Tunnel. The Gate links it from the pull request, and Flows test against it.

## Starting a preview

In a job, start the app with `bareci preview`:

```yaml
- run: bareci preview --port 3000 --ttl 2h -- bun run start
```

The command runs outside the runner's process tracking, so the runner does not stop it when the job ends; its output goes to `/run/bareci/preview.log`, readable only by the job's user. If the preview cannot be set up, the app and everything it started are stopped. The preview's URL is posted to the job's summary. The machine serves it once the job ends.

| Flag               | What it does                                                                  |
| ------------------ | ----------------------------------------------------------------------------- |
| `--port <n>`       | The app's port on the machine, 1024 to 65535                                  |
| `--ttl <duration>` | How long it lives: `30m`, `2h`, `1d`; 5 minutes to 24 hours (default 4 hours) |
| `--branch <name>`  | The branch (default `$GITHUB_HEAD_REF`, else `$GITHUB_REF_NAME`)              |
| `--pr <number>`    | The pull request (default: from `$GITHUB_REF`)                                |

`bareci preview` works only in a job on a BareCI machine: it asks for the preview as that machine. The access token is not printed in the job's log; `bareci previews get <id>` answers it to callers with `read`.

## Address and access

The hostname is `<repo>-<branch>-<owner>` under BareCI's preview domain, as one DNS label of at most 63 characters (with a hash when shortened).

A preview admits only requests that carry its **access token**: the `x-bareci-preview-token` header, or `?bareci_token=` once in the URL, which then sets a cookie. `previews_list` and `preview_get` answer the token to callers with `read`.

## Lifetime

A preview ends at the first of:

- its time to live (4 hours by default, 24 hours at most);
- `preview_stop` or `bareci previews stop <id>`;
- the branch's next preview replacing it;
- its pull request closing.

Ending releases the machine first, so billing stops, then removes the tunnel and the DNS record.

## Billing

Preview time is billed in whole seconds on top of the machine time. `GET /v1/previews/usage` answers a repository's preview seconds for a period.

## Commands

```sh
bareci previews list
bareci previews stop <id>
bareci previews close --branch my-branch
```

See the [Previews API](https://bareci.com/docs/api/previews).
