How to Enforce PR Review Rules With Danger JS
Danger JS runs a dangerfile.js against the PR and posts warnings or fails the build when your rules are violated.
Write rules in dangerfile.js using the danger API (added/modified files, PR metadata), then run npx danger ci in a workflow with DANGER_GITHUB_API_TOKEN set to the built-in token.
Steps
- Add
dangeras a dev dependency. - Write rules in
dangerfile.jswithwarn()andfail(). - Run
npx danger ciwith the GitHub token in the environment.
dangerfile.js
dangerfile.js
import { danger, warn, fail } from 'danger'
// Fail when a source change ships without a changelog entry
const hasChangelog = danger.git.modified_files.includes('CHANGELOG.md')
const hasSrcChange = danger.git.modified_files.some((f) => f.startsWith('src/'))
if (hasSrcChange && !hasChangelog) {
fail('Please add a CHANGELOG.md entry for this change.')
}
// Warn on large diffs
const bigPR = danger.github.pr.additions + danger.github.pr.deletions > 500
if (bigPR) {
warn('This PR is large; consider splitting it.')
}Workflow
.github/workflows/ci.yml
jobs:
danger:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npx danger ci
env:
DANGER_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}Gotchas
fail()blocks merge only if the Danger check is required in branch protection.- Danger needs the full git history for some helpers; set
fetch-depth: 0on checkout.
Related guides
How to Block PRs Missing Tests or a ChangelogFail a pull request that changes source without touching test files or the changelog using tj-actions/changed…
How to Fail a PR That Exceeds a Diff SizeFail a pull request whose diff exceeds a line threshold by reading additions and deletions from the PR payloa…