## Why Integrate Claude Code into GitHub Actions for Code Reviews?
In modern DevOps workflows, code reviews are a critical gatekeeper for quality. Manual reviews slow down teams, introduce inconsistencies, and scale poorly as repositories grow. Enter Claude Code, Anthropic's CLI tool for AI-assisted development, which brings Claude AI's superior reasoning directly into your CI/CD pipelines.
By embedding Claude Code in GitHub Actions, you can automate comprehensive code reviews on every pull request (PR). It analyzes diffs, suggests improvements, flags security issues, and ensures adherence to best practices—all powered by Claude models like Sonnet 3.5 for balanced performance or Haiku for speed. This setup delivers instant feedback, reduces review bottlenecks, and boosts developer productivity.
This tutorial provides step-by-step instructions, complete YAML workflows, and customizable prompt templates. Whether you're a solo dev or leading an enterprise team, you'll have a production-ready pipeline in minutes.
## Prerequisites
Before diving in, ensure you have:
- A GitHub repository with code to review (public or private).
- An Anthropic API key (sign up at [console.anthropic.com](https://console.anthropic.com) and generate one under API Keys).
- Basic familiarity with GitHub Actions and YAML.
- Node.js 18+ installed locally for testing Claude Code (optional but recommended).
Store your `ANTHROPIC_API_KEY` as a GitHub repository secret:
1. Go to your repo > Settings > Secrets and variables > Actions.
2. Add a new secret named `ANTHROPIC_API_KEY` with your key value.
## Installing Claude Code
Claude Code is a lightweight Node.js CLI. Install it globally for local testing:
```bash
npm install -g @anthropic-ai/claude-code
claude-code --version
```
You'll need to authenticate locally too:
```bash
export ANTHROPIC_API_KEY=your-api-key-here
claude-code auth
```
For GitHub Actions, we'll install it dynamically in the workflow—no pre-installed actions needed.
Test it locally on a file:
```bash
# Create a sample diff
cat > diff.patch << EOF
git diff HEAD~1
--- a/example.js
+++ b/example.js
@@ -1,3 +1,3 @@
console.log('Hello');
-console.log('World');
+console.log('World!');
EOF
claude-code review --input diff.patch --model claude-3-5-sonnet-20240620 --prompt "Review for best practices, security, and performance."
```
This outputs a detailed review Markdown you can iterate on.
## Building the GitHub Actions Workflow
Create a new file at `.github/workflows/code-review.yml` in your repo. This workflow triggers on pull requests, computes the diff, runs Claude Code, and posts the review as a PR comment.
Here's the complete YAML configuration:
```yaml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
review:
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Full history for accurate diffs
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Generate PR diff
id: diff
run: |
git fetch origin ${{ github.event.pull_request.base.ref }}
git diff origin/${{ github.event.pull_request.base.ref }} > pr-diff.patch
echo "diff_path=pr-diff.patch" >> $GITHUB_OUTPUT
- name: Run Claude Code Review
id: review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude-code review \
--input ${{ steps.diff.outputs.diff_path }} \
--model claude-3-5-sonnet-20240620 \
--prompt-file .claude/review-prompt.md \
--output review.md
echo "review_path=review.md" >> $GITHUB_OUTPUT
- name: Post Review Comment
uses: actions/github-script@v7
if: always()
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const reviewPath = '${{ steps.review.outputs.review_path }}';
let reviewContent = fs.readFileSync(reviewPath, 'utf8');
// Truncate if too long for GitHub comment (65536 chars max)
if (reviewContent.length > 60000) {
reviewContent = reviewContent.substring(0, 60000) + '\
\
... (truncated) Full review in artifact.';
}
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## 🤖 Claude Code Review\
\
${reviewContent}`
});
- name: Upload Review Artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: claude-review
path: review.md
```
### Key Breakdown
- **Triggers**: Runs on PR open/sync/reopen for real-time feedback.
- **Permissions**: Grants write access to post comments.
- **Diff Generation**: Fetches base branch and creates `pr-diff.patch` for focused review.
- **Claude Code Step**: Uses your custom prompt (next section) and Sonnet model. Outputs to `review.md`.
- **Comment Posting**: Uses `github-script` to create a formatted PR comment.
- **Artifact Upload**: Full review available for download if truncated or failed.
Commit and push this file. Open a test PR to see it in action!
## Crafting Effective Review Prompts
Prompt engineering is key to high-quality reviews. Create `.claude/review-prompt.md` in your repo root:
```markdown
# Code Review Prompt for Claude
You are an expert code reviewer with 20+ years in software engineering. Review the provided diff thoroughly.
## Focus Areas:
- **Correctness**: Bugs, logic errors, edge cases.
- **Security**: Vulnerabilities (e.g., injection, secrets).
- **Performance**: Inefficiencies, scalability issues.
- **Best Practices**: Readability, naming, DRY principle.
- **Standards**: Adhere to [link to your style guide].
- **Tests**: Suggestions for unit/integration tests.
## Output Format:
Use Markdown with:
- Summary (approve/block with reasons)
- File-by-file breakdowns
- Actionable suggestions (code snippets)
- Severity levels: 🚨 High, ⚠️ Medium, ℹ️ Low
Diff:
{{input}}
```
Claude Code interpolates `{{input}}` with the diff. Customize per project—e.g., add language-specific rules for JS/Python.
**Pro Tip**: Use Haiku (`claude-3-haiku-20240307`) for <10s reviews in CI, Sonnet for depth.
## Example Review Output
On a sample JS PR adding a leaky async function:
```
## 🤖 Claude Code Review
### Summary
**Status: Needs changes (⚠️ Medium issues)**
Two security risks and one performance nit. Fix before merge.
### example.js
**🚨 High: Potential memory leak**
```diff
-async function processData(data) {
+async function processData(data) {
const stream = createStream(data);
stream.on('data', handler);
- // Missing stream.destroy() on error
+}
```
Suggestion:
```js
stream.on('error', () => stream.destroy());
```
**ℹ️ Low: Use const/let appropriately**
... (more)
```
This integrates seamlessly into PR discussions.
## Advanced Configurations
### Multi-File or Selective Reviews
Limit to changed files:
```yaml
- name: Selective Diff
run: git diff --name-only origin/${{ github.event.pull_request.base.ref }} | grep '\.js$' | xargs git diff > js-diff.patch
```
### Parallel Jobs by Language
Split into JS/Python/Go reviewers with different prompts/models.
### Cost Optimization
- Cache Claude Code: Add `cache: 'npm'` already included.
- Rate Limits: Sonnet allows 50k tokens/min; monitor via Anthropic dashboard.
- Conditional Runs: Skip on docs-only PRs:
```yaml
if: !contains(github.event.pull_request.labels.*.name, 'skip-review')
```
### Slack/Teams Notifications
Add a step with `slackapi/slack-github-action` for alerts on blocks.
### Self-Hosted Runners
For private models or speed, deploy on your infra.
## Best Practices and Troubleshooting
- **Security**: Never commit API keys; always use secrets.
- **Token Limits**: Claude handles up to 200k tokens; split large diffs.
- **Errors**: Check logs for `Invalid API key` or `Model not found`. Verify key perms.
- **Iteration**: A/B test prompts; track merge speed pre/post.
- **Metrics**: Use GitHub Insights to measure review-to-merge time.
- **Enterprise**: Combine with MCP servers for custom tools (e.g., lint integration).
Common Issues:
| Issue | Fix |
|-------|-----|
| Diff empty | Ensure `fetch-depth: 0` |
| Comment fails | Check `pull-requests: write` perm |
| High latency | Switch to Haiku |
## Scaling to Teams
Pin this workflow repo-wide. For monorepos, add `paths-ignore` for non-code dirs. Integrate with branch protection rules: Require "Claude approved" label (add via script if summary says OK).
Teams report 30-50% faster PR throughput. Pair with human reviews for high-stakes changes.
## Conclusion
Automating code reviews with Claude Code in GitHub Actions transforms DevOps from bottleneck to accelerator. You've got YAML, prompts, and tips—fork, tweak, deploy.
Stay tuned to Claude Directory for more: MCP extensions, agent workflows, and enterprise playbooks. Questions? Comment below or join our Discord.
*Word count: ~1450*