Code Review and Documentation
Code Review and Documentation
So far in this module, you have used Claude Code to build and modify code. But Claude Code is equally powerful when it comes to reviewing code and generating documentation. These are tasks that developers often skip because they are tedious, but they are critical for maintainable software.
In this lesson, you will learn how to use Claude Code for structured code review, documentation generation, and automated CI/CD integration. By the end, you will be able to catch bugs before they reach production and keep your project well-documented with minimal effort.
Code Review with Claude Code
Reviewing Changes in a Pull Request
The most common code review scenario is reviewing a pull request before it gets merged. Claude Code can do this directly from your terminal.
Start by checking out the branch you want to review:
git checkout feature/new-payment-system
claude
Then ask Claude Code to review the changes:
Review the changes in this branch compared to main.
Look for bugs, security issues, performance problems,
and code style inconsistencies.
Claude Code will:
- Run
git diff mainto see all the changes - Read the modified files in full (not just the diff) to understand context
- Identify potential issues across several categories
- Present a structured review
A typical review output might look like this:
## Code Review Summary
### Critical Issues
1. **SQL Injection in src/routes/payments.ts:45**
The query string is built with string concatenation instead
of parameterized queries. This is exploitable.
2. **Missing authentication on POST /refunds**
The refund endpoint does not use the auth middleware,
allowing unauthenticated users to issue refunds.
### Warnings
3. **No transaction wrapping in processPayment()**
The payment creation and inventory update are separate
queries. If the inventory update fails, the payment
record will exist without the inventory being adjusted.
4. **Hardcoded API key in src/services/stripe.ts:12**
The Stripe API key is hardcoded. Move it to an
environment variable.
### Suggestions
5. **Missing error handling in webhook handler**
The Stripe webhook handler does not verify the webhook
signature. Add signature verification to prevent
spoofed webhook events.
6. **Consider adding rate limiting to the payment endpoint**
High-value endpoints like payment processing should
have rate limiting to prevent abuse.
This is far more thorough than what most manual reviews catch in a first pass.
Using the /review Command
Claude Code provides a built-in /review command for streamlined code review. Instead of writing a long prompt, simply type:
/review
Claude Code will automatically diff your current working tree against the base branch and provide a structured review. This is useful for quick checks before you push.
You can also scope the review:
Review only the files in src/routes/ for security issues
Or focus on a specific concern:
Review the database migration in migrations/20240315_add_payments.sql
for data loss risks
What Claude Code Looks For
Claude Code's reviews cover several categories:
Bugs and Logic Errors
- Off-by-one errors in loops or pagination
- Null/undefined access without guards
- Missing return statements in conditional branches
- Race conditions in async code
Security Issues
- SQL injection via string concatenation
- Cross-site scripting (XSS) in rendered output
- Missing authentication or authorization checks
- Exposed secrets or API keys
- Insecure cryptographic practices
Performance Problems
- N+1 query patterns in database access
- Missing database indexes for frequently queried columns
- Unnecessary re-renders in React components
- Large payloads returned without pagination
Code Style and Maintainability
- Inconsistency with the rest of the codebase
- Missing TypeScript types or excessive use of
any - Dead code or unused imports
- Functions that are too long or do too many things
Generating Documentation
JSDoc Comments for Exported Functions
Well-documented functions save hours of reading code later. Ask Claude Code to document your codebase:
Write JSDoc comments for all exported functions in the src/services/
directory. Include parameter descriptions, return types, and example
usage where helpful. Follow the existing JSDoc style if any is present.
Claude Code will read each file, understand what the functions do, and add precise documentation. For example, it might transform this:
export async function processPayment(userId: string, amount: number, currency: string) {
Into this:
/**
* Processes a payment for a user and creates a payment record in the database.
*
* Charges the user's default payment method via Stripe. If the charge succeeds,
* a payment record is created in the local database. If the charge fails,
* an AppError is thrown with the Stripe error details.
*
* @param userId - The unique identifier of the user being charged
* @param amount - The payment amount in the smallest currency unit (e.g., cents for USD)
* @param currency - The three-letter ISO currency code (e.g., "usd", "eur")
* @returns The created payment record including the Stripe charge ID
* @throws {AppError} If the user has no payment method on file (status 400)
* @throws {AppError} If the Stripe charge fails (status 402)
*/
export async function processPayment(userId: string, amount: number, currency: string) {
The key difference from generic AI documentation: Claude Code reads the function body, the database schema, the error handling, and the Stripe integration to write documentation that accurately describes what the function actually does, not what it looks like it might do.
README Generation
Every project needs a README, and Claude Code can generate a comprehensive one:
Create a README.md for this project. Include:
- Project description
- Prerequisites (Node.js version, etc.)
- Installation steps
- Environment variables (reference .env.example)
- How to run the development server
- How to run tests
- API endpoint summary
- Project structure overview
- Contributing guidelines
Claude Code will scan your entire project — package.json, tsconfig.json, the directory structure, your routes, your tests, your environment variables — and produce a README that accurately reflects the current state of the project.
This is especially valuable for projects that have grown organically without documentation. Claude Code can retroactively document everything in one prompt.
API Documentation with OpenAPI
For REST APIs, generating an OpenAPI (Swagger) specification is incredibly useful:
Generate an OpenAPI 3.0 specification for all the endpoints in this API.
Save it as openapi.yaml in the project root. Include:
- All request and response schemas
- Authentication requirements (Bearer token)
- Query parameter descriptions
- Example request and response bodies
- Error response schemas
Claude Code will read every route handler, every Zod schema (or TypeScript type), and every middleware to produce a complete OpenAPI spec. This spec can then be used with tools like Swagger UI, Postman, or API client generators.
# After Claude Code generates the spec, you can validate it:
npx @redocly/cli lint openapi.yaml
Changelog Generation
When it is time to release a new version, ask Claude Code to generate a changelog:
Write a changelog entry for the upcoming release based on the
commits since the last tag. Group changes by type: Features,
Bug Fixes, Breaking Changes, and Internal. Use conventional
commit messages to determine categories.
Claude Code will run git log to read the commit history, parse the commit messages, and organize them into a readable changelog:
## [1.3.0] - 2026-03-06
### Features
- Add JWT authentication with register and login endpoints
- Add full-text search for products using SQLite FTS5
- Add pagination to GET /products with customizable page size
### Bug Fixes
- Fix race condition in concurrent payment processing
- Handle empty search queries gracefully instead of returning 500
### Internal
- Upgrade better-sqlite3 to v11.2.0
- Add test coverage for authentication middleware
CI/CD Integration
The Non-Interactive Mode: claude -p
Everything we have done so far has been in interactive mode — you type, Claude Code responds, you type again. But Claude Code also has a non-interactive mode designed for automation:
claude -p "Review the code changes in this PR and report any issues"
The -p flag (for "prompt") runs Claude Code with a single prompt and exits after producing the output. There is no back-and-forth conversation. This makes it perfect for CI/CD pipelines.
Key characteristics of the -p mode:
- Accepts a single prompt as a string argument
- Outputs the result to stdout
- Exits with a status code (0 for success)
- Can read from stdin for additional context
- Works in environments without a TTY (like CI runners)
Practical Example: Automated PR Review in GitHub Actions
Here is how you can set up Claude Code to automatically review every pull request in your repository.
Create a GitHub Actions workflow file:
# .github/workflows/claude-review.yml
The workflow configuration:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run Claude Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
git diff origin/main...HEAD > /tmp/diff.txt
claude -p "Review this git diff for bugs, security issues,
and code quality problems. Be specific about file names and
line numbers. Format the output as markdown.
$(cat /tmp/diff.txt)" > /tmp/review.md
- name: Post review comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('/tmp/review.md', 'utf8');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## Claude Code Review\n\n${review}`
});
With this workflow, every PR automatically gets a code review comment from Claude Code. The review appears as a comment on the PR, making it visible to all team members.
Other CI/CD Use Cases
The non-interactive mode opens up many automation possibilities:
Commit message validation:
COMMIT_MSG=$(git log -1 --pretty=%B)
claude -p "Does this commit message follow conventional commit format?
If not, suggest a better message: $COMMIT_MSG"
Pre-merge documentation check:
claude -p "Check if all exported functions in src/services/ have
JSDoc comments. List any functions that are missing documentation."
Dependency audit:
claude -p "Review the package.json changes in this PR. Are any new
dependencies suspicious, deprecated, or known to have security issues?
Check if the versions are pinned appropriately."
Test coverage analysis:
npx jest --coverage --json > /tmp/coverage.json
claude -p "Analyze this test coverage report and identify the most
critical untested code paths: $(cat /tmp/coverage.json)"
Setting Up the API Key
For CI/CD, you need an Anthropic API key stored as a secret in your CI provider:
GitHub Actions:
# Add the secret via GitHub CLI
gh secret set ANTHROPIC_API_KEY --body "sk-ant-..."
GitLab CI:
# Add via GitLab UI: Settings > CI/CD > Variables
# Name: ANTHROPIC_API_KEY
# Value: sk-ant-...
# Mark as "Masked" and "Protected"
The API key is used by the claude -p command through the ANTHROPIC_API_KEY environment variable. Never hardcode it in your workflow files.
Combining Review and Documentation in Your Workflow
Here is a practical workflow that combines everything from this lesson:
1. Before Starting Work
claude
> Review the current state of documentation in this project.
> What is missing or outdated?
2. After Making Changes
> Review the changes I just made. Focus on correctness and security.
3. Before Committing
> Update JSDoc comments for any functions I modified.
> Update the README if the API surface changed.
4. Before Merging
> Write a changelog entry for these changes.
> Commit everything with a descriptive message.
5. In CI/CD (Automated)
The GitHub Actions workflow runs automatically, providing a second pair of eyes on every PR.
Tips for Effective Code Review with Claude Code
Be Specific About What You Want Reviewed
"Review this code" is okay, but "Review this code for SQL injection vulnerabilities and missing input validation" is much better. Focused reviews produce more actionable results.
Review in Layers
For large PRs, review in stages:
First, review only the database migration files.
Now review the route handlers that use the new tables.
Finally, review the tests for completeness.
Combine Automated and Manual Review
Claude Code's automated review catches many issues, but it does not replace human judgment. Use it as a first pass to catch the mechanical errors, then focus your manual review on architecture decisions, user experience, and business logic.
Keep Reviews Actionable
If Claude Code identifies an issue, ask it to fix the issue right there:
Fix the SQL injection vulnerability you identified in
src/routes/payments.ts and the missing auth check on
the refunds endpoint.
This turns code review directly into code improvement, without context switching.
Key Takeaway
Claude Code is not just a code generator — it is a code reviewer, a technical writer, and a CI/CD automation tool. Using the /review command and claude -p mode, you can integrate thorough code review and up-to-date documentation into every stage of your development process.
The pattern is simple: let Claude Code review what you build, document what you ship, and automate the checks you never have time to do manually. Your codebase will be safer, better documented, and easier for the next developer to pick up.
Cuestionario
Discussion
Sign in to join the discussion.

