Code Review Prompt Templates
AI prompt templates for thorough code reviews. Get comprehensive feedback on code quality, security, and best practices.
Overview
Code reviews catch bugs, improve maintainability, and share knowledge across teams, but they're only as good as the questions you ask. These prompts help you get thorough, actionable feedback from AI on code quality, security vulnerabilities, performance issues, and adherence to best practices. Use them to supplement human reviews or get a quick sanity check before submitting a PR.
Best Practices
Include the full context: the programming language, framework, and what the code is supposed to accomplish
Specify which aspects matter most for your review, security, performance, readability, or all of the above
Provide relevant surrounding code or interfaces when reviewing a function in isolation
Mention your team's coding standards or style guide if you have specific conventions to follow
Ask for prioritized feedback (critical issues vs. nice-to-haves) to make reviews actionable
Prompt Templates
1. Comprehensive Code Review
Review the following code for quality, maintainability, and potential issues: ```[LANGUAGE] [PASTE YOUR CODE HERE] ``` Context: - Purpose: [WHAT THIS CODE DOES] - Framework/Stack: [RELEVANT TECHNOLOGIES] - Review focus: [SECURITY / PERFORMANCE / READABILITY / ALL] Provide feedback organized by: 1. Critical issues (bugs, security vulnerabilities) 2. Performance concerns 3. Code quality and maintainability 4. Suggestions for improvement For each issue, explain WHY it's a problem and show the corrected code.
Language: Python Code: A user authentication function that checks passwords Purpose: Validates user login credentials against database Framework: Flask with SQLAlchemy Review focus: Security
**Critical Issues:**
1. **SQL Injection Vulnerability** (Line 12)
The query uses string concatenation instead of parameterized queries.
```python
# Vulnerable
query = f"SELECT * FROM users WHERE email = '{email}'"
# Fixed
user = User.query.filter_by(email=email).first()
```
2. **Timing Attack on Password Comparison** (Line 18)
Using `==` for password comparison leaks timing information.
```python
# Use constant-time comparison
from hmac import compare_digest
if compare_digest(stored_hash, computed_hash):
```Before submitting PRs, when reviewing unfamiliar code, or when you need a second opinion on implementation quality
- •Run this review before asking human reviewers, it catches obvious issues and saves everyone time
- •For large files, review in logical chunks (one class or module at a time) for more focused feedback
2. Security-Focused Code Review
Perform a security-focused review of this code: ```[LANGUAGE] [PASTE YOUR CODE HERE] ``` Application context: - Type: [WEB APP / API / MOBILE / CLI] - Handles: [USER INPUT / PAYMENTS / AUTH / FILE UPLOADS / etc.] - Exposed to: [PUBLIC INTERNET / INTERNAL ONLY] Check for: - OWASP Top 10 vulnerabilities - Authentication/authorization flaws - Input validation issues - Sensitive data exposure - Security misconfigurations Rate each finding by severity (Critical/High/Medium/Low) and provide remediation code.
Language: JavaScript/Node.js Code: File upload endpoint for user profile pictures Type: Web API Handles: File uploads from authenticated users Exposed to: Public internet
**Critical: Path Traversal Vulnerability**
The filename is used directly without sanitization, allowing `../../etc/passwd` attacks.
```javascript
// Vulnerable
const filepath = `./uploads/${req.body.filename}`;
// Fixed
const safeName = path.basename(req.body.filename);
const filepath = path.join('./uploads', safeName);
```
**High: Missing File Type Validation**
No validation of actual file contents, users could upload executable files.
```javascript
// Add magic byte validation
const fileType = await fileTypeFromBuffer(buffer);
if (!['image/jpeg', 'image/png'].includes(fileType?.mime)) {
throw new Error('Invalid file type');
}
```Reviewing code that handles user input, authentication, file operations, or any internet-exposed functionality
- •Always review authentication code with this prompt, auth bugs have the highest impact
- •Combine with a general review to catch both security and quality issues
3. Pull Request Review Assistant
Review this pull request diff for a code review: ```diff [PASTE YOUR DIFF HERE] ``` PR Context: - Title: [PR TITLE] - Purpose: [WHAT CHANGE THIS PR MAKES] - Affected areas: [WHAT PARTS OF THE APP THIS TOUCHES] Provide: 1. Summary of what the PR does (verify it matches stated purpose) 2. Potential bugs or edge cases not handled 3. Breaking changes or backward compatibility concerns 4. Test coverage gaps 5. Specific line-by-line comments in the format: `Line X: [comment]`
PR Title: Add rate limiting to login endpoint Purpose: Prevent brute force attacks by limiting login attempts Affected areas: Authentication module, middleware Diff: [Added rate limiter middleware with 5 attempts per minute]
**Summary:** PR adds IP-based rate limiting to the login endpoint, blocking IPs after 5 failed attempts within 1 minute. This matches the stated purpose. **Potential Issues:** - Line 24: Rate limit is per-IP only, attackers can distribute across IPs. Consider also rate limiting per username. - Line 31: No handling for when Redis is unavailable, requests will fail instead of falling back. **Test Coverage Gaps:** - No test for rate limit reset after the window expires - Missing test for concurrent requests at the limit boundary
When reviewing PRs from teammates or contributing to open source projects
- •Focus on the diff, not the entire file, reviewers should comment on changes, not rewrite the codebase
- •Check that tests were added or updated for the changes
4. Legacy Code Review
Review this legacy code that I need to work with: ```[LANGUAGE] [PASTE YOUR CODE HERE] ``` Context: - Age: [HOW OLD IS THIS CODE] - Documentation: [AVAILABLE / NONE / OUTDATED] - I need to: [MODIFY / EXTEND / REFACTOR / UNDERSTAND] Help me: 1. Understand what this code actually does (explain the logic) 2. Identify any hidden assumptions or implicit dependencies 3. Find potential landmines (fragile parts that might break if modified) 4. Suggest the safest approach for my intended changes 5. Recommend what tests to write before modifying anything
Language: PHP Age: 8+ years, multiple authors Documentation: None I need to: Add a new payment method to the checkout flow
**What This Code Does:** This is a payment processing controller that handles checkout. The `processPayment()` method routes to different handlers based on a `payment_type` switch statement (lines 45-78). **Hidden Assumptions:** - Assumes `$_SESSION['cart']` is always set (will error on direct URL access) - Currency is hardcoded to USD in the PayPal handler (line 89) **Landmines:** - The `validateOrder()` method modifies the cart as a side effect (line 34), calling it twice will break totals - Global variable `$PAYMENT_CONFIG` is modified during runtime (line 52) **Safest Approach:** Add your new payment type to the switch statement (line 67) following the existing pattern. Don't refactor the routing, it's fragile. **Write These Tests First:** 1. Test checkout flow with existing payment methods still works 2. Test empty cart handling
When working with inherited code, unfamiliar codebases, or code without documentation
- •Always write characterization tests before modifying legacy code, they document current behavior
- •Look for comments like 'DO NOT TOUCH' or 'HACK', they're warnings from past developers
Common Mistakes to Avoid
Pasting code without context, the AI can't assess if code is 'good' without knowing its purpose and constraints
Asking for a review of thousands of lines at once, break it into logical units for better feedback
Ignoring the 'why' behind suggestions, understanding the reasoning helps you learn and make judgment calls
Frequently Asked Questions
Code reviews catch bugs, improve maintainability, and share knowledge across teams, but they're only as good as the questions you ask. These prompts help you get thorough, actionable feedback from AI on code quality, security vulnerabilities, performance issues, and adherence to best practices. Use them to supplement human reviews or get a quick sanity check before submitting a PR.
Related Templates
Debugging Prompt Templates
AI prompt templates for debugging code. Identify issues, understand errors, and find solutions faster.
Code Documentation Prompt Templates
AI prompt templates for writing code documentation. Create clear comments, READMEs, and API docs.
API Design Prompt Templates
AI prompt templates for designing APIs. Create well-structured, intuitive API endpoints and documentation.
Have your own prompt to optimize?