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

# Preview environments for pull requests

> Give every pull request its own hosted environment with forge env preview: create it from CI, get its URL, and let it delete itself on expiry. Includes billing.

A preview environment is a copy of one of your environments, made for a single pull request or branch, that deletes itself after a deadline you choose. Reviewers open the change running on its own URL with its own database, instead of checking out the branch, and nothing is left behind when the PR is done.

Forge builds this out of parts it already has. A preview is an ordinary environment from the moment it is created, so `forge env deploy`, `forge env status` and `forge obs check` work on it unchanged. What makes it a preview is a marker that says which environment it copies and when it expires.

> [!NOTE]
>
> This is not the same as [Preview a running app](https://docs.reliantlabs.io/cli/previews.md). That page covers `reliant preview-url`, the browser URL of a dev server listening on a machine, which exists only while the server runs. A preview environment is a deployed copy of your project, with its own hosted workloads and database, that lives until it expires or you delete it.

## How it works

You commit one **template environment**, by default `deploy/kcl/preview/`, that describes what a preview should be. Derive it from an environment you already run, then fill in the placeholders forge leaves for per-environment values:

```bash theme={null}
reliant forge env new preview --from staging
reliant forge env new preview --check      # no REPLACE_ME_* left, and it compiles
```

For each pull request, three commands do the work:

```bash theme={null}
reliant forge env preview create --pr 123 --ttl 72h   # writes deploy/kcl/preview-pr-123/
reliant forge env deploy preview-pr-123 --yes         # build, record and deploy it
reliant forge env preview delete --pr 123 --yes       # when the PR closes
```

`create` copies the template's files verbatim into `deploy/kcl/preview-pr-123/` and marks the copy with its expiry. `deploy` then builds and promotes it like any other environment, with its own release record. When the deploy finishes, its result line prints the environment's URL, and `reliant forge env status preview-pr-123` shows it again later.

The instance directory is a throwaway. Edit the template, never the copy, because the next `create` overwrites it, and do not commit instances: a CI checkout makes them fresh each time.

From forge v1.9.0, `create` also writes a `.gitignore` inside the instance directory that ignores all of it, so creating a preview leaves the checkout clean and its release is not a dirty-tree build. On v1.8.0 and earlier, add `deploy/kcl/preview-*/` to the project's `.gitignore` yourself. Without it, the untracked copy makes forge cut every preview release as `DIRTY TREE`.

### Names

The name depends only on the pull request or branch, so the job that creates a preview when a PR opens and the job that deletes it when the PR closes agree without sharing any state. `--pr 123` gives `preview-pr-123`. `--branch feat/Login_Page` gives `preview-feat-login-page`. `reliant forge env preview name --pr 123` prints the name without creating anything, and `--name-template` changes the shape (`{env}` is the template's name, `{id}` is `pr-<n>` or the branch). A name is at most 40 bytes: a longer one is cut and given a short hash suffix so two long branch names never collide.

### Commands and flags

| Command | What it does |
| - | - |
| `reliant forge env preview create` | Copies the template to `deploy/kcl/<instance>/` and marks it with an expiry. Running it again for the same PR or branch refreshes the copy and the expiry. |
| `reliant forge env preview name` | Prints the instance name for a PR or branch. |
| `reliant forge env preview delete` | Deletes the preview's hosted environment, **data included**, then removes its directory. |
| `reliant forge env gc` | Deletes every preview whose expiry has passed. `--dry-run` lists them without deleting. |

| Flag | Applies to | Meaning |
| - | - | - |
| `--pr <n>` / `--branch <name>` | create, name, delete | What the preview is for. Give one, not both. |
| `--from <env>` | create, name, delete | The committed template to copy. Default `preview`. |
| `--ttl <duration>` | create | Time until expiry: `72h`, `7d`. Default `72h`, at most 30 days. |
| `--name-template <tpl>` | create, name, delete | How the instance is named. Default `{env}-{id}`. |
| `--name <instance>` | delete | Delete by instance name instead of `--pr` or `--branch`. |
| `--yes` | delete, gc | Confirm the deletion. Required when there is no terminal. |
| `--json` | create, gc | Print the result as JSON. `create --json` includes `name` and `expires_at`. |

`create` refuses three things: a template that is itself a preview, an existing directory of that name that is not a preview of the same template, and an instance that would render into a Kubernetes namespace the template environment also renders into.

## Create one per pull request from CI

Save this as `.github/workflows/preview.yml`. It is yours, and forge does not generate it. It needs the same credential as your deploy workflow: an organization automation token stored as the `FORGE_CONTROL_PLANE_TOKEN` secret (see [Deploying from CI](https://docs.reliantlabs.io/forge/deploy/releases-and-promotion.md#deploying-from-ci)).

```yaml theme={null}
name: preview
on:
  pull_request:
    types: [opened, synchronize, reopened]
  # The close runs in the base repository's context, with its secrets, for
  # every PR, a fork's included; the `down` job never checks out PR code.
  pull_request_target:
    types: [closed]
  schedule:
    - cron: "17 * * * *"          # hourly: delete expired previews
concurrency:
  group: preview-${{ github.event.pull_request.number || 'gc' }}
  cancel-in-progress: false
permissions:
  contents: read
  pull-requests: write
jobs:
  up:
    # never run a fork's code with your deploy token (a fork's PR gets no secrets anyway)
    if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-latest
    env:
      FORGE_CONTROL_PLANE_TOKEN: ${{ secrets.FORGE_CONTROL_PLANE_TOKEN }}
    steps:
      - uses: actions/checkout@v4
      - run: npm i -g @reliantlabs/forge
      - id: preview
        run: |
          forge env preview create --pr ${{ github.event.pull_request.number }} --ttl 72h --json > preview.json
          echo "name=$(jq -r .name preview.json)" >> "$GITHUB_OUTPUT"
      - run: forge env deploy ${{ steps.preview.outputs.name }} --yes --json > deploy.json
      - name: Comment the URL
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          urls=$(forge env status ${{ steps.preview.outputs.name }} --json | jq -r '[.. | .url? // empty] | unique | join("\n")')
          gh pr comment ${{ github.event.pull_request.number }} --edit-last --create-if-none \
            --body "Preview \`${{ steps.preview.outputs.name }}\` (expires $(jq -r .expires_at preview.json)):
          ${urls}"
  down:
    # every closed PR, a fork's included: trusted code only, never the PR's
    if: github.event_name == 'pull_request_target'
    runs-on: ubuntu-latest
    env:
      FORGE_CONTROL_PLANE_TOKEN: ${{ secrets.FORGE_CONTROL_PLANE_TOKEN }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.repository.default_branch }}   # your template, not the PR's
      - run: npm i -g @reliantlabs/forge
      - run: forge env preview delete --pr ${{ github.event.pull_request.number }} --yes
  gc:
    if: github.event_name == 'schedule'
    runs-on: ubuntu-latest
    env:
      FORGE_CONTROL_PLANE_TOKEN: ${{ secrets.FORGE_CONTROL_PLANE_TOKEN }}
    steps:
      - uses: actions/checkout@v4
      - run: npm i -g @reliantlabs/forge
      - run: forge env gc --yes
```

Every push to the pull request runs `create` again, which refreshes the copy and moves the expiry to a fresh 72 hours, and `deploy` then ships the new commit to the same environment. The `down` job deletes the preview when the PR closes. The `gc` job is the backstop for a PR whose close event never ran the job.

> [!WARNING]
>
> A pull request from a fork gets no repository secrets, and you should not give it your deploy token. That is why the `up` job runs only when `github.event.pull_request.head.repo.full_name == github.repository`, that is, for branches in your own repository. Keep that condition if you adapt the workflow.
>
> The `down` job is different: deleting a preview runs nothing from the pull request, so it runs on `pull_request_target`, in your repository's own context and with its secrets, for every closed pull request, a fork's included. That deletes a fork's preview created some other way (say, a maintainer ran `create` by hand) when it closes, instead of leaving it to expiry. It checks out your default branch, never the pull request's head, so a fork's code never runs with your token. Keep it that way: never add `ref: ${{ github.event.pull_request.head.sha }}`, or any step that runs the pull request's files, to a `pull_request_target` job.

The runner installs the standalone `forge` CLI from npm, so the workflow calls `forge`, not `reliant forge`.

The same three commands work from anywhere that has a checkout of the project and a credential. A [Reliant workflow](https://docs.reliantlabs.io/workflows/patterns.md) can run them from a `run` node, and on a Reliant machine forge uses your signed-in session instead of a token ([Forge sign-in](https://docs.reliantlabs.io/forge/sign-in.md)).

## What a hosted preview gets

When the template binds its workloads to [Reliant hosting](https://docs.reliantlabs.io/hosting/overview.md) (`forge.OnHosted`), nothing else needs configuring. Each instance becomes its own hosted environment with its own generated URL, its own managed Postgres database and its own secrets.

The database is created for that environment and the deploy runs your migrations against it, so a preview starts with your schema and no data. Forge copies the template's configuration, not anything from a running environment: no rows come over from staging or prod.

Secrets are per environment and are **not** copied from the template. Give each instance the secrets it needs with `reliant forge env secret set --env preview-pr-123 <NAME>` (see [Secrets](https://docs.reliantlabs.io/hosting/secrets.md)), or keep previews on configuration that needs none.

If the template renders onto a Kubernetes cluster you operate instead, give each preview its own namespace by deriving it from the environment name, which forge sets on every render:

```python theme={null}
_cluster = forge.ClusterTarget {
    cluster = "gke_acme_us-central1_previews"
    namespace = "shop-" + option("env")      # shop-preview-pr-123
    platform = "amd64"
}
```

Forge stamps each of those namespaces with the template it came from and its expiry, so `reliant forge env gc` finds expired previews from the cluster alone, even when the CI runner that made them is gone. Pass `--context <kubectl-context>` to `gc` to scan a cluster the template does not render into.

## Expiry and self-deletion

`--ttl` sets how long a preview lives. It is a duration (`72h`) or whole days (`7d`), defaults to 72 hours, and can be at most 30 days. The expiry is recorded in the environment's declared shape on every deploy.

**On Reliant hosting, the platform deletes an expired preview for you.** It checks every five minutes and deletes the hosted environment, its workloads and its database, the same as `forge env delete` would. There is no confirmation and no `--keep-data`: a preview's data is throwaway by declaration. A preview whose expiry cannot be read is never deleted, and one that you refresh with `create` and redeploy before the deadline keeps living.

A hosted preview with a custom domain bound to it is not deleted until you unbind the domain ([Custom domains](https://docs.reliantlabs.io/hosting/custom-domains.md)).

**On a cluster you operate, nothing deletes it for you.** Run `reliant forge env gc --yes` on a schedule, as the `gc` job above does.

## Delete one early

When a PR closes, or you simply want the environment gone:

```bash theme={null}
reliant forge env preview delete --pr 123 --yes
```

This deletes the hosted environment, **its database included, which cannot be undone**, or on a cluster you operate the namespaces it renders into (only while they still carry the preview's label). It then removes `deploy/kcl/preview-pr-123/`. In a fresh CI checkout where that directory is gone, forge re-creates it from the template first to learn what to delete. `reliant forge env gc --dry-run` shows which previews have already expired.

## What it costs

A preview is a real hosted environment, so it is billed like one. Workloads and managed databases need the organization's pay-as-you-go app hosting billing, and CPU, memory and storage are billed from first use for as long as the preview exists. If billing is not active, `forge env deploy` queues the deploy and exits with code 7 rather than failing, and the preview goes live once someone sets billing up ([Queued deploys](https://docs.reliantlabs.io/hosting/overview.md#queued-deploys)).

A frontend-only template falls under the static site free tier, which allows one static site per person, across the organizations they own without a plan, **counted across all environments**. Each preview's site counts, so with your `prod` site already live, the first preview is queued like any other billing hold. Traffic is shared too: the 10 GiB per month is for the whole organization. Details are on [Hosting on Reliant](https://docs.reliantlabs.io/hosting/overview.md#billing).

Cost therefore follows how many previews exist at once and for how long. A short `--ttl`, the delete on PR close, and an hourly `gc` keep it down. `reliant forge env stop <env>` suspends a preview's workloads without deleting it ([Stopping and deleting an environment](https://docs.reliantlabs.io/hosting/overview.md#stopping-and-deleting-an-environment)).

## Related topics

* [Hosting on Reliant](https://docs.reliantlabs.io/hosting/overview.md): what hosting runs, billing, queued deploys
* [Environments](https://docs.reliantlabs.io/forge/deploy/environments.md): template environments, `forge env new` and bindings
* [Releases and promotion](https://docs.reliantlabs.io/forge/deploy/releases-and-promotion.md): `forge env deploy`, exit codes and deploying from CI
* [Secrets](https://docs.reliantlabs.io/hosting/secrets.md): per-environment secrets for a preview
* [Custom domains](https://docs.reliantlabs.io/hosting/custom-domains.md)
* [Preview a running app](https://docs.reliantlabs.io/cli/previews.md): the dev-server URL on a machine, a different feature


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