Tutorials & Guides
How to Build an Automated GitHub PR Code Reviewer with Claude 3.5 Sonnet and Node.js
Tired of lazy LGTM approvals that let critical bugs slip into production? Build your own automated pull request reviewer using Claude 3.5 Sonnet to catch logic flaws, security issues, and style guide violations on every commit.
Updated 10/28/2026
Stop Rubber-Stamping Pull Requests
Let’s be honest: human code review is a fragile art. After staring at a screen for seven hours, your eyes gloss over, and that 400-line diff gets a lazy, rubber-stamped "LGTM" (Looks Good To Me). Two hours later, production is on fire because someone forgot to handle a rejected promise in a critical payment gateway.
While traditional static analysis tools are brilliant at catching missing semicolons, they lack the contextual nuance required to spot logic errors, race conditions, or architectural departures from your team's patterns. That is where LLMs come in, and specifically, why we build with Claude.
By leveraging the advanced reasoning capabilities of /platforms/claude, we can build an automated code reviewer that acts as a tireless, highly opinionated senior developer. In this guide, we will write a clean, lightweight Node.js script that pulls a GitHub Pull Request diff, analyzes it with Claude 3.5 Sonnet, and posts contextual inline feedback directly onto the PR.
Which AI should I use for this?
Tickd is independent and not affiliated with any AI company.
The Architecture: How It Works
We want a setup that is fast, cheap, and seamlessly integrated into your existing development loop. Here is how our automated reviewer operates:
- Trigger: A GitHub Action fires whenever a developer opens a Pull Request or pushes a new commit.
- Fetch: The script retrieves the raw pull request diff using the GitHub REST API.
- Analyze: We parse the diff and feed it to Claude 3.5 Sonnet, accompanied by a strict, structured system prompt.
- Comment: The script parses Claude's JSON response and publishes targeted, line-specific suggestions back to GitHub.
This workflow keeps your loop incredibly tight. It is exactly what makes an elegant engineering pipeline tick.
Step 1: Setting Up Your Workspace
First, let's initialise a lightweight Node.js project. You will need Node 18+ installed on your machine.
`bash
mkdir claude-pr-reviewer
cd claude-pr-reviewer
npm init -y
npm install @anthropic-ai/sdk @octokit/rest dotenv
`
Here is what these packages do: `@anthropic-ai/sdk`*: The official SDK for interacting with Claude. `@octokit/rest`*: GitHub's official client library to fetch diffs and post comments. `dotenv`*: For managing local environment variables during testing.
Create a .env file in your root directory to store your credentials:
`env
ANTHROPIC_API_KEY=your_anthropic_api_key_here
GITHUB_TOKEN=your_github_personal_access_token_here
`
Step 2: Fetching the PR Diff from GitHub
We need to grab the exact changes introduced in the Pull Request. Let's create an index.js file and write our initial fetching logic using Octokit.
`javascript
import { Octokit } from "@octokit/rest";
import Anthropic from "@anthropic-ai/sdk";
import dotenv from "dotenv";
dotenv.config();
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN }); const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
async function getPullRequestDiff(owner, repo, pullNumber) {
try {
const { data } = await octokit.pulls.get({
owner,
repo,
pull_number: pullNumber,
mediaType: {
format: "diff",
},
});
return data;
} catch (error) {
console.error("Failed to retrieve PR diff:", error);
throw error;
}
}
`
Note: Setting the `mediaType.format` to `'diff'` is crucial. It forces GitHub to return a clean unified diff string instead of a heavy JSON object representing the commits.
Step 3: Crafting the Claude Prompt
Now we need to write the engine of our reviewer. The magic lies entirely in the system prompt. If you ask an LLM to "review this code," it will return generic fluff ("Nice clean code! Good job!"). We need to constrain Claude to act like a cynical, highly analytical staff engineer.
We also want Claude to return its findings in a structured JSON array so we can map its comments directly back to the physical line numbers in the GitHub diff. For more general prompting theory on structuring outputs, dive into our comprehensive guide on /prompts.
`javascript
const SYSTEM_PROMPT = `You are an elite Staff Software Engineer. Your job is to review pull request diffs and identify critical bugs, security vulnerabilities, performance bottlenecks, and structural issues.
Rules: 1. Be objective, precise, and constructive. 2. Do NOT comment on trivial style formatting (e.g., spacing, semi-colons) unless it genuinely changes the code's execution logic. 3. Focus heavily on security flaws (SQL injection, XSS, unhandled exceptions) and race conditions. 4. You must output your feedback ONLY as a JSON array of objects. Do not wrap the JSON in markdown blocks. Do not add conversational text before or after the JSON.
Format your output exactly like this:
[
{
"path": "path/to/file.js",
"line": 42,
"message": "Your detailed code review feedback here. Suggest code corrections if appropriate."
}
]`;
`
Step 4: Running the Code Review via Claude
Let’s write the core analyzer function. We pass the raw diff to Claude 3.5 Sonnet. Because we want structured JSON, we will instruct the model explicitly to maintain valid JSON grammar.
`javascript
async function analyzeDiffWithClaude(diffString) {
const response = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 4000,
temperature: 0.1, // Keep it highly analytical and deterministic
system: SYSTEM_PROMPT,
messages: [
{
role: "user",
content: Please review the following git diff and output your structured feedback:\n\n${diffString}
}
]
});
const rawText = response.content[0].text.trim();
try {
return JSON.parse(rawText);
} catch (e) {
console.error("Claude did not return valid JSON. Raw response:", rawText);
return [];
}
}
`
Step 5: Posting Inline Comments Back to GitHub
Now that we have a structured array of suggestions, we iterate over them and use Octokit to place inline comments directly on the PR. To do this, we need to create a review with individual review comments.
`javascript
async function postReviewComments(owner, repo, pullNumber, commitId, comments) {
if (comments.length === 0) {
console.log("No issues detected by Claude. Clear skies!");
return;
}
const formattedComments = comments.map(comment => ({
path: comment.path,
line: comment.line,
body: 🤖 **Claude's Review:** ${comment.message},
}));
try {
await octokit.pulls.createReview({
owner,
repo,
pull_number: pullNumber,
commit_id: commitId,
event: "COMMENT",
comments: formattedComments,
});
console.log(Successfully posted ${comments.length} inline review comments.);
} catch (error) {
console.error("Failed to post PR review comments:", error);
}
}
`
Step 6: Orchestrating the Pipeline
To tie everything together, we need to get the latest commit ID of the pull request, parse our arguments from the environment, and execute the run loop.
`javascript
async function run() {
const owner = process.env.REPO_OWNER;
const repo = process.env.REPO_NAME;
const pullNumber = parseInt(process.env.PR_NUMBER, 10);
if (!owner || !repo || !pullNumber) { console.error("Missing environment variables. Ensure REPO_OWNER, REPO_NAME, and PR_NUMBER are set."); process.exit(1); }
console.log(Fetching diff for ${owner}/${repo} PR #${pullNumber}...);
const diff = await getPullRequestDiff(owner, repo, pullNumber);
// Fetch the latest commit to bind comments to the right state const { data: prDetails } = await octokit.pulls.get({ owner, repo, pull_number: pullNumber }); const commitId = prDetails.head.sha;
console.log("Analyzing diff with Claude 3.5 Sonnet..."); const reviewComments = await analyzeDiffWithClaude(diff);
console.log(Sending comments to GitHub for commit ${commitId}...);
await postReviewComments(owner, repo, pullNumber, commitId, reviewComments);
}
run();
`
Deployment: Wire It Up to GitHub Actions
To automate this on every pull request, save your Node script as .github/scripts/review.js inside your repository and create a workflow file at .github/workflows/claude-review.yml:
`yaml
name: Automated Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs: review: runs-on: ubuntu-latest permissions: pull-requests: write contents: read steps: - name: Checkout code uses: actions/checkout@v3
- name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18'
- name: Install dependencies run: npm install @anthropic-ai/sdk @octokit/rest dotenv
- name: Run Review Script
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO_OWNER: ${{ github.repository_owner }}
REPO_NAME: ${{ github.event.repository.name }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: node .github/scripts/review.js
`
Remember to add your ANTHROPIC_API_KEY to your repository's GitHub Secrets. The standard GITHUB_TOKEN is automatically provided by GitHub Actions with the proper read/write permissions for pull requests.
Next Steps and Customisation
This basic setup gives you an incredibly powerful starting point. To make this tool truly your own, consider extending it in the following ways:
- Introduce Style Guardrails: Pass your team's ESLint config or coding standards markdown file directly into Claude’s system prompt.
- Contextual Awareness: Use GitHub's tree API to let Claude request the contents of imported helper files when analyzing a diff.
- Refusal Handling: Sometimes Claude API returns non-JSON text if a prompt triggers safety blocks. If you experience unexpected API exceptions, head over to /platforms/claude/articles to troubleshoot rate limits and error-handling strategies.
With this pipeline in place, your human reviewers can stop wasting mental energy searching for missing null-checks and spend their time where it matters: thinking about high-level architecture and user experience. Let the machine do the heavy lifting.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.