Skip to content
Latchkey

How to Create a GitHub Deployment for a Preview in GitHub Actions

Call createDeployment and createDeploymentStatus so the PR displays a first-class environment entry with the preview URL.

The Deployments API turns a preview into a tracked environment on the PR. Create a deployment for the head ref, then post a success status with the environment_url. Grant deployments: write.

Steps

  • Grant deployments: write to the job.
  • Call createDeployment for the PR head ref with an environment name.
  • Post createDeploymentStatus with state success and environment_url.

Workflow

.github/workflows/preview.yml
permissions:
  deployments: write
jobs:
  record:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v7
        with:
          script: |
            const dep = await github.rest.repos.createDeployment({
              owner: context.repo.owner, repo: context.repo.repo,
              ref: context.payload.pull_request.head.sha,
              environment: 'preview',
              auto_merge: false, required_contexts: [],
            })
            await github.rest.repos.createDeploymentStatus({
              owner: context.repo.owner, repo: context.repo.repo,
              deployment_id: dep.data.id,
              state: 'success',
              environment_url: process.env.PREVIEW_URL,
            })
        env:
          PREVIEW_URL: ${{ needs.preview.outputs.url }}

Gotchas

  • Set required_contexts: [] or the deployment stays pending on missing checks.
  • Post an inactive status on teardown so the environment stops showing as live.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →