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_targetjob.
Related guides
How to Deploy a Preview Environment Per Pull Request in GitHub ActionsStand up an ephemeral preview environment for every pull request in GitHub Actions by triggering on pull_requ…
How to Run E2E Tests Against a Preview URL in GitHub ActionsRun Playwright end-to-end and smoke tests against a deployed preview URL in GitHub Actions, waiting for the e…