Skip to content
Latchkey

How to Post the Preview URL as a PR Comment in GitHub Actions

Use actions/github-script to find an existing bot comment and update it, or create one if none exists, so the PR shows a single live preview link.

After a deploy step produces the URL, call the issues API with actions/github-script. List existing comments, match on a marker string, and either updateComment or createComment. Grant pull-requests: write.

Steps

  • Pass the deployed URL into the comment step via a step output.
  • List PR comments and find one containing a hidden marker.
  • Update that comment if found, otherwise create a new one.

Workflow

.github/workflows/preview.yml
permissions:
  pull-requests: write
jobs:
  comment:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v7
        with:
          script: |
            const url = process.env.PREVIEW_URL
            const marker = '<!-- preview-url -->'
            const body = `${marker}\nPreview: ${url}`
            const { data } = await github.rest.issues.listComments({
              owner: context.repo.owner, repo: context.repo.repo,
              issue_number: context.issue.number,
            })
            const existing = data.find(c => c.body.includes(marker))
            if (existing) {
              await github.rest.issues.updateComment({
                owner: context.repo.owner, repo: context.repo.repo,
                comment_id: existing.id, body,
              })
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner, repo: context.repo.repo,
                issue_number: context.issue.number, body,
              })
            }
        env:
          PREVIEW_URL: ${{ needs.preview.outputs.url }}

Gotchas

  • The hidden HTML marker lets the next run find and update the same comment.
  • On forked PRs the default token cannot write comments; run this in a trusted pull_request_target job.

Related guides

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