Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6cdf4dc59 | ||
|
|
fef11a8059 | ||
|
|
ebdc51708c | ||
|
|
41fa3734ba | ||
|
|
23f58f8705 | ||
|
|
90cf84b8bb | ||
|
|
4ee8a0361f |
20
CHANGELOG.md
20
CHANGELOG.md
@@ -7,7 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
---
|
||||
|
||||
## [2.9.0] - 2026-01-22 - "Automation & Maintenance"
|
||||
---
|
||||
|
||||
## [2.10.0] - 2026-01-22 - "Developer Excellence"
|
||||
|
||||
### Added
|
||||
|
||||
- **New Skills**:
|
||||
- `api-security-best-practices`: Comprehensive guide for secure API design and defense.
|
||||
- `environment-setup-guide`: Systematic approach to project onboarding and tool configuration.
|
||||
- `web-performance-optimization`: Methodologies for optimizing Core Web Vitals and loading speed.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Enhanced Skill**:
|
||||
- `code-review-checklist`: Replaced with a much more detailed and systematic version covering functionality, security, and quality.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Index & Registry**: Updated `skills_index.json` and `README.md` registry (Total: 238 skills).
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
11
README.md
11
README.md
@@ -1,6 +1,6 @@
|
||||
# 🌌 Antigravity Awesome Skills: 235+ Agentic Skills for Claude Code, Gemini CLI, Cursor, Copilot & More
|
||||
# 🌌 Antigravity Awesome Skills: 238+ Agentic Skills for Claude Code, Gemini CLI, Cursor, Copilot & More
|
||||
|
||||
> **The Ultimate Collection of 235+ Universal Agentic Skills for AI Coding Assistants — Claude Code, Gemini CLI, Codex CLI, Antigravity IDE, GitHub Copilot, Cursor, OpenCode**
|
||||
> **The Ultimate Collection of 238+ Universal Agentic Skills for AI Coding Assistants — Claude Code, Gemini CLI, Codex CLI, Antigravity IDE, GitHub Copilot, Cursor, OpenCode**
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://claude.ai)
|
||||
@@ -109,7 +109,7 @@ The repository is organized into several key areas of expertise:
|
||||
|
||||
---
|
||||
|
||||
## Full Skill Registry (235/235)
|
||||
## Full Skill Registry (238/238)
|
||||
|
||||
> [!NOTE] > **Document Skills**: We provide both **community** and **official Anthropic** versions for DOCX, PDF, PPTX, and XLSX. Locally, the official versions are used by default (via symlinks). In the repository, both versions are available for flexibility.
|
||||
|
||||
@@ -163,6 +163,7 @@ The repository is organized into several key areas of expertise:
|
||||
| **analytics-tracking** | When the user wants to set up, improve, or audit analytics tracking and measurement. Also use when the user mentions "set up tracking," "GA4," "Google Analytics," "conversion tracking," "event tracking," "UTM parameters," "tag manager," "GTM," "analytics implementation," or "tracking plan." For A/B test measurement, see ab-test-setup. | `skills/analytics-tracking` |
|
||||
| **api-documentation-generator** | "Generate comprehensive, developer-friendly API documentation from code, including endpoints, parameters, examples, and best practices" | `skills/api-documentation-generator` |
|
||||
| **api-patterns** | API design principles and decision-making. REST vs GraphQL vs tRPC selection, response formats, versioning, pagination. | `skills/api-patterns` |
|
||||
| **api-security-best-practices** | "Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities" | `skills/api-security-best-practices` |
|
||||
| **app-builder** | Main application building orchestrator. Creates full-stack applications from natural language requests. Determines project type, selects tech stack, coordinates agents. | `skills/app-builder` |
|
||||
| **app-store-optimization** | Complete App Store Optimization (ASO) toolkit for researching, optimizing, and tracking mobile app performance on Apple App Store and Google Play Store | `skills/app-store-optimization` |
|
||||
| **architecture** | Architectural decision-making framework. Requirements analysis, trade-off evaluation, ADR documentation. Use when making architecture decisions or analyzing system design. | `skills/architecture` |
|
||||
@@ -189,7 +190,7 @@ The repository is organized into several key areas of expertise:
|
||||
| **clean-code** | Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments | `skills/clean-code` |
|
||||
| **clerk-auth** | "Expert patterns for Clerk auth implementation, middleware, organizations, webhooks, and user sync Use when: adding authentication, clerk auth, user authentication, sign in, sign up." | `skills/clerk-auth` |
|
||||
| **clickhouse-io** | ClickHouse database patterns, query optimization, analytics, and data engineering best practices for high-performance analytical workloads. | `skills/cc-skill-clickhouse-io` |
|
||||
| **code-review-checklist** | Code review guidelines covering code quality, security, and best practices. | `skills/code-review-checklist` |
|
||||
| **code-review-checklist** | "Comprehensive checklist for conducting thorough code reviews covering functionality, security, performance, and maintainability" | `skills/code-review-checklist` |
|
||||
| **coding-standards** | Universal coding standards, best practices, and patterns for TypeScript, JavaScript, React, and Node.js development. | `skills/cc-skill-coding-standards` |
|
||||
| **competitor-alternatives** | "When the user wants to create competitor comparison or alternative pages for SEO and sales enablement. Also use when the user mentions 'alternative page,' 'vs page,' 'competitor comparison,' 'comparison page,' '[Product] vs [Product],' '[Product] alternative,' or 'competitive landing pages.' Covers four formats: singular alternative, plural alternatives, you vs competitor, and competitor vs competitor. Emphasizes deep research, modular content architecture, and varied section types beyond feature tables." | `skills/competitor-alternatives` |
|
||||
| **computer-use-agents** | "Build AI agents that interact with computers like humans do - viewing screens, moving cursors, clicking buttons, and typing text. Covers Anthropic's Computer Use, OpenAI's Operator/CUA, and open-source alternatives. Critical focus on sandboxing, security, and handling the unique challenges of vision-based control. Use when: computer use, desktop automation agent, screen control AI, vision-based agent, GUI automation." | `skills/computer-use-agents` |
|
||||
@@ -212,6 +213,7 @@ The repository is organized into several key areas of expertise:
|
||||
| **docx** | "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks" | `skills/docx-official` |
|
||||
| **email-sequence** | When the user wants to create or optimize an email sequence, drip campaign, automated email flow, or lifecycle email program. Also use when the user mentions "email sequence," "drip campaign," "nurture sequence," "onboarding emails," "welcome sequence," "re-engagement emails," "email automation," or "lifecycle emails." For in-app onboarding, see onboarding-cro. | `skills/email-sequence` |
|
||||
| **email-systems** | "Email has the highest ROI of any marketing channel. $36 for every $1 spent. Yet most startups treat it as an afterthought - bulk blasts, no personalization, landing in spam folders. This skill covers transactional email that works, marketing automation that converts, deliverability that reaches inboxes, and the infrastructure decisions that scale. Use when: keywords, file_patterns, code_patterns." | `skills/email-systems` |
|
||||
| **environment-setup-guide** | "Guide developers through setting up development environments with proper tools, dependencies, and configurations" | `skills/environment-setup-guide` |
|
||||
| **executing-plans** | Use when you have a written implementation plan to execute in a separate session with review checkpoints | `skills/executing-plans` |
|
||||
| **file-organizer** | Intelligently organizes files and folders by understanding context, finding duplicates, and suggesting better organizational structures. Use when user wants to clean up directories, organize downloads, remove duplicates, or restructure projects. | `skills/file-organizer` |
|
||||
| **file-uploads** | "Expert at handling file uploads and cloud storage. Covers S3, Cloudflare R2, presigned URLs, multipart uploads, and image optimization. Knows how to handle large files without blocking. Use when: file upload, S3, R2, presigned URL, multipart." | `skills/file-uploads` |
|
||||
@@ -344,6 +346,7 @@ The repository is organized into several key areas of expertise:
|
||||
| **web-artifacts-builder** | Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts. | `skills/web-artifacts-builder` |
|
||||
| **web-design-guidelines** | Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices". | `skills/web-design-guidelines` |
|
||||
| **web-games** | Web browser game development principles. Framework selection, WebGPU, optimization, PWA. | `skills/game-development/web-games` |
|
||||
| **web-performance-optimization** | "Optimize website and web application performance including loading speed, Core Web Vitals, bundle size, caching strategies, and runtime performance" | `skills/web-performance-optimization` |
|
||||
| **webapp-testing** | Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs. | `skills/webapp-testing` |
|
||||
| **workflow-automation** | "Workflow automation is the infrastructure that makes AI agents reliable. Without durable execution, a network hiccup during a 10-step payment flow means lost money and angry customers. With it, workflows resume exactly where they left off. This skill covers the platforms (n8n, Temporal, Inngest) and patterns (sequential, parallel, orchestrator-worker) that turn brittle scripts into production-grade automation. Key insight: The platforms make different tradeoffs. n8n optimizes for accessibility" | `skills/workflow-automation` |
|
||||
| **writing-plans** | Use when you have a spec or requirements for a multi-step task, before touching code | `skills/writing-plans` |
|
||||
|
||||
907
skills/api-security-best-practices/SKILL.md
Normal file
907
skills/api-security-best-practices/SKILL.md
Normal file
@@ -0,0 +1,907 @@
|
||||
---
|
||||
name: api-security-best-practices
|
||||
description: "Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities"
|
||||
---
|
||||
|
||||
# API Security Best Practices
|
||||
|
||||
## Overview
|
||||
|
||||
Guide developers in building secure APIs by implementing authentication, authorization, input validation, rate limiting, and protection against common vulnerabilities. This skill covers security patterns for REST, GraphQL, and WebSocket APIs.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Use when designing new API endpoints
|
||||
- Use when securing existing APIs
|
||||
- Use when implementing authentication and authorization
|
||||
- Use when protecting against API attacks (injection, DDoS, etc.)
|
||||
- Use when conducting API security reviews
|
||||
- Use when preparing for security audits
|
||||
- Use when implementing rate limiting and throttling
|
||||
- Use when handling sensitive data in APIs
|
||||
|
||||
## How It Works
|
||||
|
||||
### Step 1: Authentication & Authorization
|
||||
|
||||
I'll help you implement secure authentication:
|
||||
- Choose authentication method (JWT, OAuth 2.0, API keys)
|
||||
- Implement token-based authentication
|
||||
- Set up role-based access control (RBAC)
|
||||
- Secure session management
|
||||
- Implement multi-factor authentication (MFA)
|
||||
|
||||
### Step 2: Input Validation & Sanitization
|
||||
|
||||
Protect against injection attacks:
|
||||
- Validate all input data
|
||||
- Sanitize user inputs
|
||||
- Use parameterized queries
|
||||
- Implement request schema validation
|
||||
- Prevent SQL injection, XSS, and command injection
|
||||
|
||||
### Step 3: Rate Limiting & Throttling
|
||||
|
||||
Prevent abuse and DDoS attacks:
|
||||
- Implement rate limiting per user/IP
|
||||
- Set up API throttling
|
||||
- Configure request quotas
|
||||
- Handle rate limit errors gracefully
|
||||
- Monitor for suspicious activity
|
||||
|
||||
### Step 4: Data Protection
|
||||
|
||||
Secure sensitive data:
|
||||
- Encrypt data in transit (HTTPS/TLS)
|
||||
- Encrypt sensitive data at rest
|
||||
- Implement proper error handling (no data leaks)
|
||||
- Sanitize error messages
|
||||
- Use secure headers
|
||||
|
||||
### Step 5: API Security Testing
|
||||
|
||||
Verify security implementation:
|
||||
- Test authentication and authorization
|
||||
- Perform penetration testing
|
||||
- Check for common vulnerabilities (OWASP API Top 10)
|
||||
- Validate input handling
|
||||
- Test rate limiting
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: Implementing JWT Authentication
|
||||
|
||||
```markdown
|
||||
## Secure JWT Authentication Implementation
|
||||
|
||||
### Authentication Flow
|
||||
|
||||
1. User logs in with credentials
|
||||
2. Server validates credentials
|
||||
3. Server generates JWT token
|
||||
4. Client stores token securely
|
||||
5. Client sends token with each request
|
||||
6. Server validates token
|
||||
|
||||
### Implementation
|
||||
|
||||
#### 1. Generate Secure JWT Tokens
|
||||
|
||||
\`\`\`javascript
|
||||
// auth.js
|
||||
const jwt = require('jsonwebtoken');
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
// Login endpoint
|
||||
app.post('/api/auth/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Validate input
|
||||
if (!email || !password) {
|
||||
return res.status(400).json({
|
||||
error: 'Email and password are required'
|
||||
});
|
||||
}
|
||||
|
||||
// Find user
|
||||
const user = await db.user.findUnique({
|
||||
where: { email }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
// Don't reveal if user exists
|
||||
return res.status(401).json({
|
||||
error: 'Invalid credentials'
|
||||
});
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const validPassword = await bcrypt.compare(
|
||||
password,
|
||||
user.passwordHash
|
||||
);
|
||||
|
||||
if (!validPassword) {
|
||||
return res.status(401).json({
|
||||
error: 'Invalid credentials'
|
||||
});
|
||||
}
|
||||
|
||||
// Generate JWT token
|
||||
const token = jwt.sign(
|
||||
{
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
role: user.role
|
||||
},
|
||||
process.env.JWT_SECRET,
|
||||
{
|
||||
expiresIn: '1h',
|
||||
issuer: 'your-app',
|
||||
audience: 'your-app-users'
|
||||
}
|
||||
);
|
||||
|
||||
// Generate refresh token
|
||||
const refreshToken = jwt.sign(
|
||||
{ userId: user.id },
|
||||
process.env.JWT_REFRESH_SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
);
|
||||
|
||||
// Store refresh token in database
|
||||
await db.refreshToken.create({
|
||||
data: {
|
||||
token: refreshToken,
|
||||
userId: user.id,
|
||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||
}
|
||||
});
|
||||
|
||||
res.json({
|
||||
token,
|
||||
refreshToken,
|
||||
expiresIn: 3600
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
res.status(500).json({
|
||||
error: 'An error occurred during login'
|
||||
});
|
||||
}
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
#### 2. Verify JWT Tokens (Middleware)
|
||||
|
||||
\`\`\`javascript
|
||||
// middleware/auth.js
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
function authenticateToken(req, res, next) {
|
||||
// Get token from header
|
||||
const authHeader = req.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({
|
||||
error: 'Access token required'
|
||||
});
|
||||
}
|
||||
|
||||
// Verify token
|
||||
jwt.verify(
|
||||
token,
|
||||
process.env.JWT_SECRET,
|
||||
{
|
||||
issuer: 'your-app',
|
||||
audience: 'your-app-users'
|
||||
},
|
||||
(err, user) => {
|
||||
if (err) {
|
||||
if (err.name === 'TokenExpiredError') {
|
||||
return res.status(401).json({
|
||||
error: 'Token expired'
|
||||
});
|
||||
}
|
||||
return res.status(403).json({
|
||||
error: 'Invalid token'
|
||||
});
|
||||
}
|
||||
|
||||
// Attach user to request
|
||||
req.user = user;
|
||||
next();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = { authenticateToken };
|
||||
\`\`\`
|
||||
|
||||
#### 3. Protect Routes
|
||||
|
||||
\`\`\`javascript
|
||||
const { authenticateToken } = require('./middleware/auth');
|
||||
|
||||
// Protected route
|
||||
app.get('/api/user/profile', authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: req.user.userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
// Don't return passwordHash
|
||||
}
|
||||
});
|
||||
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Server error' });
|
||||
}
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
#### 4. Implement Token Refresh
|
||||
|
||||
\`\`\`javascript
|
||||
app.post('/api/auth/refresh', async (req, res) => {
|
||||
const { refreshToken } = req.body;
|
||||
|
||||
if (!refreshToken) {
|
||||
return res.status(401).json({
|
||||
error: 'Refresh token required'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Verify refresh token
|
||||
const decoded = jwt.verify(
|
||||
refreshToken,
|
||||
process.env.JWT_REFRESH_SECRET
|
||||
);
|
||||
|
||||
// Check if refresh token exists in database
|
||||
const storedToken = await db.refreshToken.findFirst({
|
||||
where: {
|
||||
token: refreshToken,
|
||||
userId: decoded.userId,
|
||||
expiresAt: { gt: new Date() }
|
||||
}
|
||||
});
|
||||
|
||||
if (!storedToken) {
|
||||
return res.status(403).json({
|
||||
error: 'Invalid refresh token'
|
||||
});
|
||||
}
|
||||
|
||||
// Generate new access token
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: decoded.userId }
|
||||
});
|
||||
|
||||
const newToken = jwt.sign(
|
||||
{
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
role: user.role
|
||||
},
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '1h' }
|
||||
);
|
||||
|
||||
res.json({
|
||||
token: newToken,
|
||||
expiresIn: 3600
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
res.status(403).json({
|
||||
error: 'Invalid refresh token'
|
||||
});
|
||||
}
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
### Security Best Practices
|
||||
|
||||
- ✅ Use strong JWT secrets (256-bit minimum)
|
||||
- ✅ Set short expiration times (1 hour for access tokens)
|
||||
- ✅ Implement refresh tokens for long-lived sessions
|
||||
- ✅ Store refresh tokens in database (can be revoked)
|
||||
- ✅ Use HTTPS only
|
||||
- ✅ Don't store sensitive data in JWT payload
|
||||
- ✅ Validate token issuer and audience
|
||||
- ✅ Implement token blacklisting for logout
|
||||
```
|
||||
|
||||
|
||||
### Example 2: Input Validation and SQL Injection Prevention
|
||||
|
||||
```markdown
|
||||
## Preventing SQL Injection and Input Validation
|
||||
|
||||
### The Problem
|
||||
|
||||
**❌ Vulnerable Code:**
|
||||
\`\`\`javascript
|
||||
// NEVER DO THIS - SQL Injection vulnerability
|
||||
app.get('/api/users/:id', async (req, res) => {
|
||||
const userId = req.params.id;
|
||||
|
||||
// Dangerous: User input directly in query
|
||||
const query = \`SELECT * FROM users WHERE id = '\${userId}'\`;
|
||||
const user = await db.query(query);
|
||||
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
// Attack example:
|
||||
// GET /api/users/1' OR '1'='1
|
||||
// Returns all users!
|
||||
\`\`\`
|
||||
|
||||
### The Solution
|
||||
|
||||
#### 1. Use Parameterized Queries
|
||||
|
||||
\`\`\`javascript
|
||||
// ✅ Safe: Parameterized query
|
||||
app.get('/api/users/:id', async (req, res) => {
|
||||
const userId = req.params.id;
|
||||
|
||||
// Validate input first
|
||||
if (!userId || !/^\d+$/.test(userId)) {
|
||||
return res.status(400).json({
|
||||
error: 'Invalid user ID'
|
||||
});
|
||||
}
|
||||
|
||||
// Use parameterized query
|
||||
const user = await db.query(
|
||||
'SELECT id, email, name FROM users WHERE id = $1',
|
||||
[userId]
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({
|
||||
error: 'User not found'
|
||||
});
|
||||
}
|
||||
|
||||
res.json(user);
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
#### 2. Use ORM with Proper Escaping
|
||||
|
||||
\`\`\`javascript
|
||||
// ✅ Safe: Using Prisma ORM
|
||||
app.get('/api/users/:id', async (req, res) => {
|
||||
const userId = parseInt(req.params.id);
|
||||
|
||||
if (isNaN(userId)) {
|
||||
return res.status(400).json({
|
||||
error: 'Invalid user ID'
|
||||
});
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
name: true,
|
||||
// Don't select sensitive fields
|
||||
}
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({
|
||||
error: 'User not found'
|
||||
});
|
||||
}
|
||||
|
||||
res.json(user);
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
#### 3. Implement Request Validation with Zod
|
||||
|
||||
\`\`\`javascript
|
||||
const { z } = require('zod');
|
||||
|
||||
// Define validation schema
|
||||
const createUserSchema = z.object({
|
||||
email: z.string().email('Invalid email format'),
|
||||
password: z.string()
|
||||
.min(8, 'Password must be at least 8 characters')
|
||||
.regex(/[A-Z]/, 'Password must contain uppercase letter')
|
||||
.regex(/[a-z]/, 'Password must contain lowercase letter')
|
||||
.regex(/[0-9]/, 'Password must contain number'),
|
||||
name: z.string()
|
||||
.min(2, 'Name must be at least 2 characters')
|
||||
.max(100, 'Name too long'),
|
||||
age: z.number()
|
||||
.int('Age must be an integer')
|
||||
.min(18, 'Must be 18 or older')
|
||||
.max(120, 'Invalid age')
|
||||
.optional()
|
||||
});
|
||||
|
||||
// Validation middleware
|
||||
function validateRequest(schema) {
|
||||
return (req, res, next) => {
|
||||
try {
|
||||
schema.parse(req.body);
|
||||
next();
|
||||
} catch (error) {
|
||||
res.status(400).json({
|
||||
error: 'Validation failed',
|
||||
details: error.errors
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Use validation
|
||||
app.post('/api/users',
|
||||
validateRequest(createUserSchema),
|
||||
async (req, res) => {
|
||||
// Input is validated at this point
|
||||
const { email, password, name, age } = req.body;
|
||||
|
||||
// Hash password
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
// Create user
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
name,
|
||||
age
|
||||
}
|
||||
});
|
||||
|
||||
// Don't return password hash
|
||||
const { passwordHash: _, ...userWithoutPassword } = user;
|
||||
res.status(201).json(userWithoutPassword);
|
||||
}
|
||||
);
|
||||
\`\`\`
|
||||
|
||||
#### 4. Sanitize Output to Prevent XSS
|
||||
|
||||
\`\`\`javascript
|
||||
const DOMPurify = require('isomorphic-dompurify');
|
||||
|
||||
app.post('/api/comments', authenticateToken, async (req, res) => {
|
||||
const { content } = req.body;
|
||||
|
||||
// Validate
|
||||
if (!content || content.length > 1000) {
|
||||
return res.status(400).json({
|
||||
error: 'Invalid comment content'
|
||||
});
|
||||
}
|
||||
|
||||
// Sanitize HTML to prevent XSS
|
||||
const sanitizedContent = DOMPurify.sanitize(content, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
|
||||
ALLOWED_ATTR: ['href']
|
||||
});
|
||||
|
||||
const comment = await prisma.comment.create({
|
||||
data: {
|
||||
content: sanitizedContent,
|
||||
userId: req.user.userId
|
||||
}
|
||||
});
|
||||
|
||||
res.status(201).json(comment);
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
### Validation Checklist
|
||||
|
||||
- [ ] Validate all user inputs
|
||||
- [ ] Use parameterized queries or ORM
|
||||
- [ ] Validate data types (string, number, email, etc.)
|
||||
- [ ] Validate data ranges (min/max length, value ranges)
|
||||
- [ ] Sanitize HTML content
|
||||
- [ ] Escape special characters
|
||||
- [ ] Validate file uploads (type, size, content)
|
||||
- [ ] Use allowlists, not blocklists
|
||||
```
|
||||
|
||||
|
||||
### Example 3: Rate Limiting and DDoS Protection
|
||||
|
||||
```markdown
|
||||
## Implementing Rate Limiting
|
||||
|
||||
### Why Rate Limiting?
|
||||
|
||||
- Prevent brute force attacks
|
||||
- Protect against DDoS
|
||||
- Prevent API abuse
|
||||
- Ensure fair usage
|
||||
- Reduce server costs
|
||||
|
||||
### Implementation with Express Rate Limit
|
||||
|
||||
\`\`\`javascript
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const RedisStore = require('rate-limit-redis');
|
||||
const Redis = require('ioredis');
|
||||
|
||||
// Create Redis client
|
||||
const redis = new Redis({
|
||||
host: process.env.REDIS_HOST,
|
||||
port: process.env.REDIS_PORT
|
||||
});
|
||||
|
||||
// General API rate limit
|
||||
const apiLimiter = rateLimit({
|
||||
store: new RedisStore({
|
||||
client: redis,
|
||||
prefix: 'rl:api:'
|
||||
}),
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 100, // 100 requests per window
|
||||
message: {
|
||||
error: 'Too many requests, please try again later',
|
||||
retryAfter: 900 // seconds
|
||||
},
|
||||
standardHeaders: true, // Return rate limit info in headers
|
||||
legacyHeaders: false,
|
||||
// Custom key generator (by user ID or IP)
|
||||
keyGenerator: (req) => {
|
||||
return req.user?.userId || req.ip;
|
||||
}
|
||||
});
|
||||
|
||||
// Strict rate limit for authentication endpoints
|
||||
const authLimiter = rateLimit({
|
||||
store: new RedisStore({
|
||||
client: redis,
|
||||
prefix: 'rl:auth:'
|
||||
}),
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 5, // Only 5 login attempts per 15 minutes
|
||||
skipSuccessfulRequests: true, // Don't count successful logins
|
||||
message: {
|
||||
error: 'Too many login attempts, please try again later',
|
||||
retryAfter: 900
|
||||
}
|
||||
});
|
||||
|
||||
// Apply rate limiters
|
||||
app.use('/api/', apiLimiter);
|
||||
app.use('/api/auth/login', authLimiter);
|
||||
app.use('/api/auth/register', authLimiter);
|
||||
|
||||
// Custom rate limiter for expensive operations
|
||||
const expensiveLimiter = rateLimit({
|
||||
windowMs: 60 * 60 * 1000, // 1 hour
|
||||
max: 10, // 10 requests per hour
|
||||
message: {
|
||||
error: 'Rate limit exceeded for this operation'
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/reports/generate',
|
||||
authenticateToken,
|
||||
expensiveLimiter,
|
||||
async (req, res) => {
|
||||
// Expensive operation
|
||||
}
|
||||
);
|
||||
\`\`\`
|
||||
|
||||
### Advanced: Per-User Rate Limiting
|
||||
|
||||
\`\`\`javascript
|
||||
// Different limits based on user tier
|
||||
function createTieredRateLimiter() {
|
||||
const limits = {
|
||||
free: { windowMs: 60 * 60 * 1000, max: 100 },
|
||||
pro: { windowMs: 60 * 60 * 1000, max: 1000 },
|
||||
enterprise: { windowMs: 60 * 60 * 1000, max: 10000 }
|
||||
};
|
||||
|
||||
return async (req, res, next) => {
|
||||
const user = req.user;
|
||||
const tier = user?.tier || 'free';
|
||||
const limit = limits[tier];
|
||||
|
||||
const key = \`rl:user:\${user.userId}\`;
|
||||
const current = await redis.incr(key);
|
||||
|
||||
if (current === 1) {
|
||||
await redis.expire(key, limit.windowMs / 1000);
|
||||
}
|
||||
|
||||
if (current > limit.max) {
|
||||
return res.status(429).json({
|
||||
error: 'Rate limit exceeded',
|
||||
limit: limit.max,
|
||||
remaining: 0,
|
||||
reset: await redis.ttl(key)
|
||||
});
|
||||
}
|
||||
|
||||
// Set rate limit headers
|
||||
res.set({
|
||||
'X-RateLimit-Limit': limit.max,
|
||||
'X-RateLimit-Remaining': limit.max - current,
|
||||
'X-RateLimit-Reset': await redis.ttl(key)
|
||||
});
|
||||
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
app.use('/api/', authenticateToken, createTieredRateLimiter());
|
||||
\`\`\`
|
||||
|
||||
### DDoS Protection with Helmet
|
||||
|
||||
\`\`\`javascript
|
||||
const helmet = require('helmet');
|
||||
|
||||
app.use(helmet({
|
||||
// Content Security Policy
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
scriptSrc: ["'self'"],
|
||||
imgSrc: ["'self'", 'data:', 'https:']
|
||||
}
|
||||
},
|
||||
// Prevent clickjacking
|
||||
frameguard: { action: 'deny' },
|
||||
// Hide X-Powered-By header
|
||||
hidePoweredBy: true,
|
||||
// Prevent MIME type sniffing
|
||||
noSniff: true,
|
||||
// Enable HSTS
|
||||
hsts: {
|
||||
maxAge: 31536000,
|
||||
includeSubDomains: true,
|
||||
preload: true
|
||||
}
|
||||
}));
|
||||
\`\`\`
|
||||
|
||||
### Rate Limit Response Headers
|
||||
|
||||
\`\`\`
|
||||
X-RateLimit-Limit: 100
|
||||
X-RateLimit-Remaining: 87
|
||||
X-RateLimit-Reset: 1640000000
|
||||
Retry-After: 900
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### ✅ Do This
|
||||
|
||||
- **Use HTTPS Everywhere** - Never send sensitive data over HTTP
|
||||
- **Implement Authentication** - Require authentication for protected endpoints
|
||||
- **Validate All Inputs** - Never trust user input
|
||||
- **Use Parameterized Queries** - Prevent SQL injection
|
||||
- **Implement Rate Limiting** - Protect against brute force and DDoS
|
||||
- **Hash Passwords** - Use bcrypt with salt rounds >= 10
|
||||
- **Use Short-Lived Tokens** - JWT access tokens should expire quickly
|
||||
- **Implement CORS Properly** - Only allow trusted origins
|
||||
- **Log Security Events** - Monitor for suspicious activity
|
||||
- **Keep Dependencies Updated** - Regularly update packages
|
||||
- **Use Security Headers** - Implement Helmet.js
|
||||
- **Sanitize Error Messages** - Don't leak sensitive information
|
||||
|
||||
### ❌ Don't Do This
|
||||
|
||||
- **Don't Store Passwords in Plain Text** - Always hash passwords
|
||||
- **Don't Use Weak Secrets** - Use strong, random JWT secrets
|
||||
- **Don't Trust User Input** - Always validate and sanitize
|
||||
- **Don't Expose Stack Traces** - Hide error details in production
|
||||
- **Don't Use String Concatenation for SQL** - Use parameterized queries
|
||||
- **Don't Store Sensitive Data in JWT** - JWTs are not encrypted
|
||||
- **Don't Ignore Security Updates** - Update dependencies regularly
|
||||
- **Don't Use Default Credentials** - Change all default passwords
|
||||
- **Don't Disable CORS Completely** - Configure it properly instead
|
||||
- **Don't Log Sensitive Data** - Sanitize logs
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
### Problem: JWT Secret Exposed in Code
|
||||
**Symptoms:** JWT secret hardcoded or committed to Git
|
||||
**Solution:**
|
||||
\`\`\`javascript
|
||||
// ❌ Bad
|
||||
const JWT_SECRET = 'my-secret-key';
|
||||
|
||||
// ✅ Good
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
if (!JWT_SECRET) {
|
||||
throw new Error('JWT_SECRET environment variable is required');
|
||||
}
|
||||
|
||||
// Generate strong secret
|
||||
// node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
|
||||
\`\`\`
|
||||
|
||||
### Problem: Weak Password Requirements
|
||||
**Symptoms:** Users can set weak passwords like "password123"
|
||||
**Solution:**
|
||||
\`\`\`javascript
|
||||
const passwordSchema = z.string()
|
||||
.min(12, 'Password must be at least 12 characters')
|
||||
.regex(/[A-Z]/, 'Must contain uppercase letter')
|
||||
.regex(/[a-z]/, 'Must contain lowercase letter')
|
||||
.regex(/[0-9]/, 'Must contain number')
|
||||
.regex(/[^A-Za-z0-9]/, 'Must contain special character');
|
||||
|
||||
// Or use a password strength library
|
||||
const zxcvbn = require('zxcvbn');
|
||||
const result = zxcvbn(password);
|
||||
if (result.score < 3) {
|
||||
return res.status(400).json({
|
||||
error: 'Password too weak',
|
||||
suggestions: result.feedback.suggestions
|
||||
});
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### Problem: Missing Authorization Checks
|
||||
**Symptoms:** Users can access resources they shouldn't
|
||||
**Solution:**
|
||||
\`\`\`javascript
|
||||
// ❌ Bad: Only checks authentication
|
||||
app.delete('/api/posts/:id', authenticateToken, async (req, res) => {
|
||||
await prisma.post.delete({ where: { id: req.params.id } });
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ✅ Good: Checks both authentication and authorization
|
||||
app.delete('/api/posts/:id', authenticateToken, async (req, res) => {
|
||||
const post = await prisma.post.findUnique({
|
||||
where: { id: req.params.id }
|
||||
});
|
||||
|
||||
if (!post) {
|
||||
return res.status(404).json({ error: 'Post not found' });
|
||||
}
|
||||
|
||||
// Check if user owns the post or is admin
|
||||
if (post.userId !== req.user.userId && req.user.role !== 'admin') {
|
||||
return res.status(403).json({
|
||||
error: 'Not authorized to delete this post'
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.post.delete({ where: { id: req.params.id } });
|
||||
res.json({ success: true });
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
### Problem: Verbose Error Messages
|
||||
**Symptoms:** Error messages reveal system details
|
||||
**Solution:**
|
||||
\`\`\`javascript
|
||||
// ❌ Bad: Exposes database details
|
||||
app.post('/api/users', async (req, res) => {
|
||||
try {
|
||||
const user = await prisma.user.create({ data: req.body });
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
// Error: "Unique constraint failed on the fields: (`email`)"
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ Good: Generic error message
|
||||
app.post('/api/users', async (req, res) => {
|
||||
try {
|
||||
const user = await prisma.user.create({ data: req.body });
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
console.error('User creation error:', error); // Log full error
|
||||
|
||||
if (error.code === 'P2002') {
|
||||
return res.status(400).json({
|
||||
error: 'Email already exists'
|
||||
});
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: 'An error occurred while creating user'
|
||||
});
|
||||
}
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
## Security Checklist
|
||||
|
||||
### Authentication & Authorization
|
||||
- [ ] Implement strong authentication (JWT, OAuth 2.0)
|
||||
- [ ] Use HTTPS for all endpoints
|
||||
- [ ] Hash passwords with bcrypt (salt rounds >= 10)
|
||||
- [ ] Implement token expiration
|
||||
- [ ] Add refresh token mechanism
|
||||
- [ ] Verify user authorization for each request
|
||||
- [ ] Implement role-based access control (RBAC)
|
||||
|
||||
### Input Validation
|
||||
- [ ] Validate all user inputs
|
||||
- [ ] Use parameterized queries or ORM
|
||||
- [ ] Sanitize HTML content
|
||||
- [ ] Validate file uploads
|
||||
- [ ] Implement request schema validation
|
||||
- [ ] Use allowlists, not blocklists
|
||||
|
||||
### Rate Limiting & DDoS Protection
|
||||
- [ ] Implement rate limiting per user/IP
|
||||
- [ ] Add stricter limits for auth endpoints
|
||||
- [ ] Use Redis for distributed rate limiting
|
||||
- [ ] Return proper rate limit headers
|
||||
- [ ] Implement request throttling
|
||||
|
||||
### Data Protection
|
||||
- [ ] Use HTTPS/TLS for all traffic
|
||||
- [ ] Encrypt sensitive data at rest
|
||||
- [ ] Don't store sensitive data in JWT
|
||||
- [ ] Sanitize error messages
|
||||
- [ ] Implement proper CORS configuration
|
||||
- [ ] Use security headers (Helmet.js)
|
||||
|
||||
### Monitoring & Logging
|
||||
- [ ] Log security events
|
||||
- [ ] Monitor for suspicious activity
|
||||
- [ ] Set up alerts for failed auth attempts
|
||||
- [ ] Track API usage patterns
|
||||
- [ ] Don't log sensitive data
|
||||
|
||||
## OWASP API Security Top 10
|
||||
|
||||
1. **Broken Object Level Authorization** - Always verify user can access resource
|
||||
2. **Broken Authentication** - Implement strong authentication mechanisms
|
||||
3. **Broken Object Property Level Authorization** - Validate which properties user can access
|
||||
4. **Unrestricted Resource Consumption** - Implement rate limiting and quotas
|
||||
5. **Broken Function Level Authorization** - Verify user role for each function
|
||||
6. **Unrestricted Access to Sensitive Business Flows** - Protect critical workflows
|
||||
7. **Server Side Request Forgery (SSRF)** - Validate and sanitize URLs
|
||||
8. **Security Misconfiguration** - Use security best practices and headers
|
||||
9. **Improper Inventory Management** - Document and secure all API endpoints
|
||||
10. **Unsafe Consumption of APIs** - Validate data from third-party APIs
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `@ethical-hacking-methodology` - Security testing perspective
|
||||
- `@sql-injection-testing` - Testing for SQL injection
|
||||
- `@xss-html-injection` - Testing for XSS vulnerabilities
|
||||
- `@broken-authentication` - Authentication vulnerabilities
|
||||
- `@backend-dev-guidelines` - Backend development standards
|
||||
- `@systematic-debugging` - Debug security issues
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [OWASP API Security Top 10](https://owasp.org/www-project-api-security/)
|
||||
- [JWT Best Practices](https://tools.ietf.org/html/rfc8725)
|
||||
- [Express Security Best Practices](https://expressjs.com/en/advanced/best-practice-security.html)
|
||||
- [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/)
|
||||
- [API Security Checklist](https://github.com/shieldfy/API-Security-Checklist)
|
||||
|
||||
---
|
||||
|
||||
**Pro Tip:** Security is not a one-time task - regularly audit your APIs, keep dependencies updated, and stay informed about new vulnerabilities!
|
||||
@@ -1,109 +1,444 @@
|
||||
---
|
||||
name: code-review-checklist
|
||||
description: Code review guidelines covering code quality, security, and best practices.
|
||||
allowed-tools: Read, Glob, Grep
|
||||
description: "Comprehensive checklist for conducting thorough code reviews covering functionality, security, performance, and maintainability"
|
||||
---
|
||||
|
||||
# Code Review Checklist
|
||||
|
||||
## Quick Review Checklist
|
||||
## Overview
|
||||
|
||||
### Correctness
|
||||
- [ ] Code does what it's supposed to do
|
||||
- [ ] Edge cases handled
|
||||
- [ ] Error handling in place
|
||||
- [ ] No obvious bugs
|
||||
Provide a systematic checklist for conducting thorough code reviews. This skill helps reviewers ensure code quality, catch bugs, identify security issues, and maintain consistency across the codebase.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Use when reviewing pull requests
|
||||
- Use when conducting code audits
|
||||
- Use when establishing code review standards for a team
|
||||
- Use when training new developers on code review practices
|
||||
- Use when you want to ensure nothing is missed in reviews
|
||||
- Use when creating code review documentation
|
||||
|
||||
## How It Works
|
||||
|
||||
### Step 1: Understand the Context
|
||||
|
||||
Before reviewing code, I'll help you understand:
|
||||
- What problem does this code solve?
|
||||
- What are the requirements?
|
||||
- What files were changed and why?
|
||||
- Are there related issues or tickets?
|
||||
- What's the testing strategy?
|
||||
|
||||
### Step 2: Review Functionality
|
||||
|
||||
Check if the code works correctly:
|
||||
- Does it solve the stated problem?
|
||||
- Are edge cases handled?
|
||||
- Is error handling appropriate?
|
||||
- Are there any logical errors?
|
||||
- Does it match the requirements?
|
||||
|
||||
### Step 3: Review Code Quality
|
||||
|
||||
Assess code maintainability:
|
||||
- Is the code readable and clear?
|
||||
- Are names descriptive?
|
||||
- Is it properly structured?
|
||||
- Are functions/methods focused?
|
||||
- Is there unnecessary complexity?
|
||||
|
||||
### Step 4: Review Security
|
||||
|
||||
Check for security issues:
|
||||
- Are inputs validated?
|
||||
- Is sensitive data protected?
|
||||
- Are there SQL injection risks?
|
||||
- Is authentication/authorization correct?
|
||||
- Are dependencies secure?
|
||||
|
||||
### Step 5: Review Performance
|
||||
|
||||
Look for performance issues:
|
||||
- Are there unnecessary loops?
|
||||
- Is database access optimized?
|
||||
- Are there memory leaks?
|
||||
- Is caching used appropriately?
|
||||
- Are there N+1 query problems?
|
||||
|
||||
### Step 6: Review Tests
|
||||
|
||||
Verify test coverage:
|
||||
- Are there tests for new code?
|
||||
- Do tests cover edge cases?
|
||||
- Are tests meaningful?
|
||||
- Do all tests pass?
|
||||
- Is test coverage adequate?
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: Functionality Review Checklist
|
||||
|
||||
```markdown
|
||||
## Functionality Review
|
||||
|
||||
### Requirements
|
||||
- [ ] Code solves the stated problem
|
||||
- [ ] All acceptance criteria are met
|
||||
- [ ] Edge cases are handled
|
||||
- [ ] Error cases are handled
|
||||
- [ ] User input is validated
|
||||
|
||||
### Logic
|
||||
- [ ] No logical errors or bugs
|
||||
- [ ] Conditions are correct (no off-by-one errors)
|
||||
- [ ] Loops terminate correctly
|
||||
- [ ] Recursion has proper base cases
|
||||
- [ ] State management is correct
|
||||
|
||||
### Error Handling
|
||||
- [ ] Errors are caught appropriately
|
||||
- [ ] Error messages are clear and helpful
|
||||
- [ ] Errors don't expose sensitive information
|
||||
- [ ] Failed operations are rolled back
|
||||
- [ ] Logging is appropriate
|
||||
|
||||
### Example Issues to Catch:
|
||||
|
||||
**❌ Bad - Missing validation:**
|
||||
\`\`\`javascript
|
||||
function createUser(email, password) {
|
||||
// No validation!
|
||||
return db.users.create({ email, password });
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**✅ Good - Proper validation:**
|
||||
\`\`\`javascript
|
||||
function createUser(email, password) {
|
||||
if (!email || !isValidEmail(email)) {
|
||||
throw new Error('Invalid email address');
|
||||
}
|
||||
if (!password || password.length < 8) {
|
||||
throw new Error('Password must be at least 8 characters');
|
||||
}
|
||||
return db.users.create({ email, password });
|
||||
}
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Example 2: Security Review Checklist
|
||||
|
||||
```markdown
|
||||
## Security Review
|
||||
|
||||
### Input Validation
|
||||
- [ ] All user inputs are validated
|
||||
- [ ] SQL injection is prevented (use parameterized queries)
|
||||
- [ ] XSS is prevented (escape output)
|
||||
- [ ] CSRF protection is in place
|
||||
- [ ] File uploads are validated (type, size, content)
|
||||
|
||||
### Authentication & Authorization
|
||||
- [ ] Authentication is required where needed
|
||||
- [ ] Authorization checks are present
|
||||
- [ ] Passwords are hashed (never stored plain text)
|
||||
- [ ] Sessions are managed securely
|
||||
- [ ] Tokens expire appropriately
|
||||
|
||||
### Data Protection
|
||||
- [ ] Sensitive data is encrypted
|
||||
- [ ] API keys are not hardcoded
|
||||
- [ ] Environment variables are used for secrets
|
||||
- [ ] Personal data follows privacy regulations
|
||||
- [ ] Database credentials are secure
|
||||
|
||||
### Dependencies
|
||||
- [ ] No known vulnerable dependencies
|
||||
- [ ] Dependencies are up to date
|
||||
- [ ] Unnecessary dependencies are removed
|
||||
- [ ] Dependency versions are pinned
|
||||
|
||||
### Example Issues to Catch:
|
||||
|
||||
**❌ Bad - SQL injection risk:**
|
||||
\`\`\`javascript
|
||||
const query = \`SELECT * FROM users WHERE email = '\${email}'\`;
|
||||
db.query(query);
|
||||
\`\`\`
|
||||
|
||||
**✅ Good - Parameterized query:**
|
||||
\`\`\`javascript
|
||||
const query = 'SELECT * FROM users WHERE email = $1';
|
||||
db.query(query, [email]);
|
||||
\`\`\`
|
||||
|
||||
**❌ Bad - Hardcoded secret:**
|
||||
\`\`\`javascript
|
||||
const API_KEY = 'sk_live_abc123xyz';
|
||||
\`\`\`
|
||||
|
||||
**✅ Good - Environment variable:**
|
||||
\`\`\`javascript
|
||||
const API_KEY = process.env.API_KEY;
|
||||
if (!API_KEY) {
|
||||
throw new Error('API_KEY environment variable is required');
|
||||
}
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Example 3: Code Quality Review Checklist
|
||||
|
||||
```markdown
|
||||
## Code Quality Review
|
||||
|
||||
### Readability
|
||||
- [ ] Code is easy to understand
|
||||
- [ ] Variable names are descriptive
|
||||
- [ ] Function names explain what they do
|
||||
- [ ] Complex logic has comments
|
||||
- [ ] Magic numbers are replaced with constants
|
||||
|
||||
### Structure
|
||||
- [ ] Functions are small and focused
|
||||
- [ ] Code follows DRY principle (Don't Repeat Yourself)
|
||||
- [ ] Proper separation of concerns
|
||||
- [ ] Consistent code style
|
||||
- [ ] No dead code or commented-out code
|
||||
|
||||
### Maintainability
|
||||
- [ ] Code is modular and reusable
|
||||
- [ ] Dependencies are minimal
|
||||
- [ ] Changes are backwards compatible
|
||||
- [ ] Breaking changes are documented
|
||||
- [ ] Technical debt is noted
|
||||
|
||||
### Example Issues to Catch:
|
||||
|
||||
**❌ Bad - Unclear naming:**
|
||||
\`\`\`javascript
|
||||
function calc(a, b, c) {
|
||||
return a * b + c;
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**✅ Good - Descriptive naming:**
|
||||
\`\`\`javascript
|
||||
function calculateTotalPrice(quantity, unitPrice, tax) {
|
||||
return quantity * unitPrice + tax;
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**❌ Bad - Function doing too much:**
|
||||
\`\`\`javascript
|
||||
function processOrder(order) {
|
||||
// Validate order
|
||||
if (!order.items) throw new Error('No items');
|
||||
|
||||
// Calculate total
|
||||
let total = 0;
|
||||
for (let item of order.items) {
|
||||
total += item.price * item.quantity;
|
||||
}
|
||||
|
||||
// Apply discount
|
||||
if (order.coupon) {
|
||||
total *= 0.9;
|
||||
}
|
||||
|
||||
// Process payment
|
||||
const payment = stripe.charge(total);
|
||||
|
||||
// Send email
|
||||
sendEmail(order.email, 'Order confirmed');
|
||||
|
||||
// Update inventory
|
||||
updateInventory(order.items);
|
||||
|
||||
return { orderId: order.id, total };
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**✅ Good - Separated concerns:**
|
||||
\`\`\`javascript
|
||||
function processOrder(order) {
|
||||
validateOrder(order);
|
||||
const total = calculateOrderTotal(order);
|
||||
const payment = processPayment(total);
|
||||
sendOrderConfirmation(order.email);
|
||||
updateInventory(order.items);
|
||||
|
||||
return { orderId: order.id, total };
|
||||
}
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### ✅ Do This
|
||||
|
||||
- **Review Small Changes** - Smaller PRs are easier to review thoroughly
|
||||
- **Check Tests First** - Verify tests pass and cover new code
|
||||
- **Run the Code** - Test it locally when possible
|
||||
- **Ask Questions** - Don't assume, ask for clarification
|
||||
- **Be Constructive** - Suggest improvements, don't just criticize
|
||||
- **Focus on Important Issues** - Don't nitpick minor style issues
|
||||
- **Use Automated Tools** - Linters, formatters, security scanners
|
||||
- **Review Documentation** - Check if docs are updated
|
||||
- **Consider Performance** - Think about scale and efficiency
|
||||
- **Check for Regressions** - Ensure existing functionality still works
|
||||
|
||||
### ❌ Don't Do This
|
||||
|
||||
- **Don't Approve Without Reading** - Actually review the code
|
||||
- **Don't Be Vague** - Provide specific feedback with examples
|
||||
- **Don't Ignore Security** - Security issues are critical
|
||||
- **Don't Skip Tests** - Untested code will cause problems
|
||||
- **Don't Be Rude** - Be respectful and professional
|
||||
- **Don't Rubber Stamp** - Every review should add value
|
||||
- **Don't Review When Tired** - You'll miss important issues
|
||||
- **Don't Forget Context** - Understand the bigger picture
|
||||
|
||||
## Complete Review Checklist
|
||||
|
||||
### Pre-Review
|
||||
- [ ] Read the PR description and linked issues
|
||||
- [ ] Understand what problem is being solved
|
||||
- [ ] Check if tests pass in CI/CD
|
||||
- [ ] Pull the branch and run it locally
|
||||
|
||||
### Functionality
|
||||
- [ ] Code solves the stated problem
|
||||
- [ ] Edge cases are handled
|
||||
- [ ] Error handling is appropriate
|
||||
- [ ] User input is validated
|
||||
- [ ] No logical errors
|
||||
|
||||
### Security
|
||||
- [ ] Input validated and sanitized
|
||||
- [ ] No SQL/NoSQL injection vulnerabilities
|
||||
- [ ] No XSS or CSRF vulnerabilities
|
||||
- [ ] No hardcoded secrets or sensitive credentials
|
||||
- [ ] **AI-Specific:** Protection against Prompt Injection (if applicable)
|
||||
- [ ] **AI-Specific:** Outputs are sanitized before being used in critical sinks
|
||||
- [ ] No SQL injection vulnerabilities
|
||||
- [ ] No XSS vulnerabilities
|
||||
- [ ] Authentication/authorization is correct
|
||||
- [ ] Sensitive data is protected
|
||||
- [ ] No hardcoded secrets
|
||||
|
||||
### Performance
|
||||
- [ ] No N+1 queries
|
||||
- [ ] No unnecessary loops
|
||||
- [ ] Appropriate caching
|
||||
- [ ] Bundle size impact considered
|
||||
- [ ] No unnecessary database queries
|
||||
- [ ] No N+1 query problems
|
||||
- [ ] Efficient algorithms used
|
||||
- [ ] No memory leaks
|
||||
- [ ] Caching used appropriately
|
||||
|
||||
### Code Quality
|
||||
- [ ] Clear naming
|
||||
- [ ] DRY - no duplicate code
|
||||
- [ ] SOLID principles followed
|
||||
- [ ] Appropriate abstraction level
|
||||
- [ ] Code is readable and clear
|
||||
- [ ] Names are descriptive
|
||||
- [ ] Functions are focused and small
|
||||
- [ ] No code duplication
|
||||
- [ ] Follows project conventions
|
||||
|
||||
### Testing
|
||||
- [ ] Unit tests for new code
|
||||
- [ ] Edge cases tested
|
||||
- [ ] Tests readable and maintainable
|
||||
### Tests
|
||||
- [ ] New code has tests
|
||||
- [ ] Tests cover edge cases
|
||||
- [ ] Tests are meaningful
|
||||
- [ ] All tests pass
|
||||
- [ ] Test coverage is adequate
|
||||
|
||||
### Documentation
|
||||
- [ ] Complex logic commented
|
||||
- [ ] Public APIs documented
|
||||
- [ ] README updated if needed
|
||||
- [ ] Code comments explain why, not what
|
||||
- [ ] API documentation is updated
|
||||
- [ ] README is updated if needed
|
||||
- [ ] Breaking changes are documented
|
||||
- [ ] Migration guide provided if needed
|
||||
|
||||
## AI & LLM Review Patterns (2025)
|
||||
### Git
|
||||
- [ ] Commit messages are clear
|
||||
- [ ] No merge conflicts
|
||||
- [ ] Branch is up to date with main
|
||||
- [ ] No unnecessary files committed
|
||||
- [ ] .gitignore is properly configured
|
||||
|
||||
### Logic & Hallucinations
|
||||
- [ ] **Chain of Thought:** Does the logic follow a verifiable path?
|
||||
- [ ] **Edge Cases:** Did the AI account for empty states, timeouts, and partial failures?
|
||||
- [ ] **External State:** Is the code making safe assumptions about file systems or networks?
|
||||
## Common Pitfalls
|
||||
|
||||
### Prompt Engineering Review
|
||||
### Problem: Missing Edge Cases
|
||||
**Symptoms:** Code works for happy path but fails on edge cases
|
||||
**Solution:** Ask "What if...?" questions
|
||||
- What if the input is null?
|
||||
- What if the array is empty?
|
||||
- What if the user is not authenticated?
|
||||
- What if the network request fails?
|
||||
|
||||
### Problem: Security Vulnerabilities
|
||||
**Symptoms:** Code exposes security risks
|
||||
**Solution:** Use security checklist
|
||||
- Run security scanners (npm audit, Snyk)
|
||||
- Check OWASP Top 10
|
||||
- Validate all inputs
|
||||
- Use parameterized queries
|
||||
- Never trust user input
|
||||
|
||||
### Problem: Poor Test Coverage
|
||||
**Symptoms:** New code has no tests or inadequate tests
|
||||
**Solution:** Require tests for all new code
|
||||
- Unit tests for functions
|
||||
- Integration tests for features
|
||||
- Edge case tests
|
||||
- Error case tests
|
||||
|
||||
### Problem: Unclear Code
|
||||
**Symptoms:** Reviewer can't understand what code does
|
||||
**Solution:** Request improvements
|
||||
- Better variable names
|
||||
- Explanatory comments
|
||||
- Smaller functions
|
||||
- Clear structure
|
||||
|
||||
## Review Comment Templates
|
||||
|
||||
### Requesting Changes
|
||||
```markdown
|
||||
// ❌ Vague prompt in code
|
||||
const response = await ai.generate(userInput);
|
||||
**Issue:** [Describe the problem]
|
||||
|
||||
// ✅ Structured & Safe prompt
|
||||
const response = await ai.generate({
|
||||
system: "You are a specialized parser...",
|
||||
input: sanitize(userInput),
|
||||
schema: ResponseSchema
|
||||
});
|
||||
**Current code:**
|
||||
\`\`\`javascript
|
||||
// Show problematic code
|
||||
\`\`\`
|
||||
|
||||
**Suggested fix:**
|
||||
\`\`\`javascript
|
||||
// Show improved code
|
||||
\`\`\`
|
||||
|
||||
**Why:** [Explain why this is better]
|
||||
```
|
||||
|
||||
## Anti-Patterns to Flag
|
||||
### Asking Questions
|
||||
```markdown
|
||||
**Question:** [Your question]
|
||||
|
||||
```typescript
|
||||
// ❌ Magic numbers
|
||||
if (status === 3) { ... }
|
||||
**Context:** [Why you're asking]
|
||||
|
||||
// ✅ Named constants
|
||||
if (status === Status.ACTIVE) { ... }
|
||||
|
||||
// ❌ Deep nesting
|
||||
if (a) { if (b) { if (c) { ... } } }
|
||||
|
||||
// ✅ Early returns
|
||||
if (!a) return;
|
||||
if (!b) return;
|
||||
if (!c) return;
|
||||
// do work
|
||||
|
||||
// ❌ Long functions (100+ lines)
|
||||
// ✅ Small, focused functions
|
||||
|
||||
// ❌ any type
|
||||
const data: any = ...
|
||||
|
||||
// ✅ Proper types
|
||||
const data: UserData = ...
|
||||
**Suggestion:** [If you have one]
|
||||
```
|
||||
|
||||
## Review Comments Guide
|
||||
### Praising Good Code
|
||||
```markdown
|
||||
**Nice!** [What you liked]
|
||||
|
||||
This is great because [explain why]
|
||||
```
|
||||
// Blocking issues use 🔴
|
||||
🔴 BLOCKING: SQL injection vulnerability here
|
||||
|
||||
// Important suggestions use 🟡
|
||||
🟡 SUGGESTION: Consider using useMemo for performance
|
||||
## Related Skills
|
||||
|
||||
// Minor nits use 🟢
|
||||
🟢 NIT: Prefer const over let for immutable variable
|
||||
- `@requesting-code-review` - Prepare code for review
|
||||
- `@receiving-code-review` - Handle review feedback
|
||||
- `@systematic-debugging` - Debug issues found in review
|
||||
- `@test-driven-development` - Ensure code has tests
|
||||
|
||||
// Questions use ❓
|
||||
❓ QUESTION: What happens if user is null here?
|
||||
```
|
||||
## Additional Resources
|
||||
|
||||
- [Google Code Review Guidelines](https://google.github.io/eng-practices/review/)
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [Code Review Best Practices](https://github.com/thoughtbot/guides/tree/main/code-review)
|
||||
- [How to Review Code](https://www.kevinlondon.com/2015/05/05/code-review-best-practices.html)
|
||||
|
||||
---
|
||||
|
||||
**Pro Tip:** Use a checklist template for every review to ensure consistency and thoroughness. Customize it for your team's specific needs!
|
||||
|
||||
479
skills/environment-setup-guide/SKILL.md
Normal file
479
skills/environment-setup-guide/SKILL.md
Normal file
@@ -0,0 +1,479 @@
|
||||
---
|
||||
name: environment-setup-guide
|
||||
description: "Guide developers through setting up development environments with proper tools, dependencies, and configurations"
|
||||
---
|
||||
|
||||
# Environment Setup Guide
|
||||
|
||||
## Overview
|
||||
|
||||
Help developers set up complete development environments from scratch. This skill provides step-by-step guidance for installing tools, configuring dependencies, setting up environment variables, and verifying the setup works correctly.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Use when starting a new project and need to set up the development environment
|
||||
- Use when onboarding new team members to a project
|
||||
- Use when switching to a new machine or operating system
|
||||
- Use when troubleshooting environment-related issues
|
||||
- Use when documenting setup instructions for a project
|
||||
- Use when creating development environment documentation
|
||||
|
||||
## How It Works
|
||||
|
||||
### Step 1: Identify Requirements
|
||||
|
||||
I'll help you determine what needs to be installed:
|
||||
- Programming language and version (Node.js, Python, Go, etc.)
|
||||
- Package managers (npm, pip, cargo, etc.)
|
||||
- Database systems (PostgreSQL, MongoDB, Redis, etc.)
|
||||
- Development tools (Git, Docker, IDE extensions, etc.)
|
||||
- Environment variables and configuration files
|
||||
|
||||
### Step 2: Check Current Setup
|
||||
|
||||
Before installing anything, I'll help you check what's already installed:
|
||||
```bash
|
||||
# Check versions of installed tools
|
||||
node --version
|
||||
python --version
|
||||
git --version
|
||||
docker --version
|
||||
```
|
||||
|
||||
### Step 3: Provide Installation Instructions
|
||||
|
||||
I'll give platform-specific installation commands:
|
||||
- **macOS:** Using Homebrew
|
||||
- **Linux:** Using apt, yum, or package manager
|
||||
- **Windows:** Using Chocolatey, Scoop, or direct installers
|
||||
|
||||
### Step 4: Configure the Environment
|
||||
|
||||
Help set up:
|
||||
- Environment variables (.env files)
|
||||
- Configuration files (.gitconfig, .npmrc, etc.)
|
||||
- IDE settings (VS Code, IntelliJ, etc.)
|
||||
- Shell configuration (.bashrc, .zshrc, etc.)
|
||||
|
||||
### Step 5: Verify Installation
|
||||
|
||||
Provide verification steps to ensure everything works:
|
||||
- Run version checks
|
||||
- Test basic commands
|
||||
- Verify database connections
|
||||
- Check environment variables are loaded
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: Node.js Project Setup
|
||||
|
||||
```markdown
|
||||
## Setting Up Node.js Development Environment
|
||||
|
||||
### Prerequisites
|
||||
- macOS, Linux, or Windows
|
||||
- Terminal/Command Prompt access
|
||||
- Internet connection
|
||||
|
||||
### Step 1: Install Node.js
|
||||
|
||||
**macOS (using Homebrew):**
|
||||
\`\`\`bash
|
||||
# Install Homebrew if not installed
|
||||
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
|
||||
|
||||
# Install Node.js
|
||||
brew install node
|
||||
\`\`\`
|
||||
|
||||
**Linux (Ubuntu/Debian):**
|
||||
\`\`\`bash
|
||||
# Update package list
|
||||
sudo apt update
|
||||
|
||||
# Install Node.js and npm
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
|
||||
sudo apt install -y nodejs
|
||||
\`\`\`
|
||||
|
||||
**Windows (using Chocolatey):**
|
||||
\`\`\`powershell
|
||||
# Install Chocolatey if not installed
|
||||
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
|
||||
|
||||
# Install Node.js
|
||||
choco install nodejs
|
||||
\`\`\`
|
||||
|
||||
### Step 2: Verify Installation
|
||||
|
||||
\`\`\`bash
|
||||
node --version # Should show v20.x.x or higher
|
||||
npm --version # Should show 10.x.x or higher
|
||||
\`\`\`
|
||||
|
||||
### Step 3: Install Project Dependencies
|
||||
|
||||
\`\`\`bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/your-repo/project.git
|
||||
cd project
|
||||
|
||||
# Install dependencies
|
||||
npm install
|
||||
\`\`\`
|
||||
|
||||
### Step 4: Set Up Environment Variables
|
||||
|
||||
Create a \`.env\` file:
|
||||
\`\`\`bash
|
||||
# Copy example environment file
|
||||
cp .env.example .env
|
||||
|
||||
# Edit with your values
|
||||
nano .env
|
||||
\`\`\`
|
||||
|
||||
Example \`.env\` content:
|
||||
\`\`\`
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
DATABASE_URL=postgresql://localhost:5432/mydb
|
||||
API_KEY=your-api-key-here
|
||||
\`\`\`
|
||||
|
||||
### Step 5: Run the Project
|
||||
|
||||
\`\`\`bash
|
||||
# Start development server
|
||||
npm run dev
|
||||
|
||||
# Should see: Server running on http://localhost:3000
|
||||
\`\`\`
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
**Problem:** "node: command not found"
|
||||
**Solution:** Restart your terminal or run \`source ~/.bashrc\` (Linux) or \`source ~/.zshrc\` (macOS)
|
||||
|
||||
**Problem:** "Permission denied" errors
|
||||
**Solution:** Don't use sudo with npm. Fix permissions:
|
||||
\`\`\`bash
|
||||
mkdir ~/.npm-global
|
||||
npm config set prefix '~/.npm-global'
|
||||
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Example 2: Python Project Setup
|
||||
|
||||
```markdown
|
||||
## Setting Up Python Development Environment
|
||||
|
||||
### Step 1: Install Python
|
||||
|
||||
**macOS:**
|
||||
\`\`\`bash
|
||||
brew install python@3.11
|
||||
\`\`\`
|
||||
|
||||
**Linux:**
|
||||
\`\`\`bash
|
||||
sudo apt update
|
||||
sudo apt install python3.11 python3.11-venv python3-pip
|
||||
\`\`\`
|
||||
|
||||
**Windows:**
|
||||
\`\`\`powershell
|
||||
choco install python --version=3.11
|
||||
\`\`\`
|
||||
|
||||
### Step 2: Verify Installation
|
||||
|
||||
\`\`\`bash
|
||||
python3 --version # Should show Python 3.11.x
|
||||
pip3 --version # Should show pip 23.x.x
|
||||
\`\`\`
|
||||
|
||||
### Step 3: Create Virtual Environment
|
||||
|
||||
\`\`\`bash
|
||||
# Navigate to project directory
|
||||
cd my-project
|
||||
|
||||
# Create virtual environment
|
||||
python3 -m venv venv
|
||||
|
||||
# Activate virtual environment
|
||||
# macOS/Linux:
|
||||
source venv/bin/activate
|
||||
|
||||
# Windows:
|
||||
venv\Scripts\activate
|
||||
\`\`\`
|
||||
|
||||
### Step 4: Install Dependencies
|
||||
|
||||
\`\`\`bash
|
||||
# Install from requirements.txt
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Or install packages individually
|
||||
pip install flask sqlalchemy python-dotenv
|
||||
\`\`\`
|
||||
|
||||
### Step 5: Set Up Environment Variables
|
||||
|
||||
Create \`.env\` file:
|
||||
\`\`\`
|
||||
FLASK_APP=app.py
|
||||
FLASK_ENV=development
|
||||
DATABASE_URL=sqlite:///app.db
|
||||
SECRET_KEY=your-secret-key-here
|
||||
\`\`\`
|
||||
|
||||
### Step 6: Run the Application
|
||||
|
||||
\`\`\`bash
|
||||
# Run Flask app
|
||||
flask run
|
||||
|
||||
# Should see: Running on http://127.0.0.1:5000
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Example 3: Docker Development Environment
|
||||
|
||||
```markdown
|
||||
## Setting Up Docker Development Environment
|
||||
|
||||
### Step 1: Install Docker
|
||||
|
||||
**macOS:**
|
||||
\`\`\`bash
|
||||
brew install --cask docker
|
||||
# Or download Docker Desktop from docker.com
|
||||
\`\`\`
|
||||
|
||||
**Linux:**
|
||||
\`\`\`bash
|
||||
# Install Docker
|
||||
curl -fsSL https://get.docker.com -o get-docker.sh
|
||||
sudo sh get-docker.sh
|
||||
|
||||
# Add user to docker group
|
||||
sudo usermod -aG docker $USER
|
||||
newgrp docker
|
||||
\`\`\`
|
||||
|
||||
**Windows:**
|
||||
Download Docker Desktop from docker.com
|
||||
|
||||
### Step 2: Verify Installation
|
||||
|
||||
\`\`\`bash
|
||||
docker --version # Should show Docker version 24.x.x
|
||||
docker-compose --version # Should show Docker Compose version 2.x.x
|
||||
\`\`\`
|
||||
|
||||
### Step 3: Create docker-compose.yml
|
||||
|
||||
\`\`\`yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
- DATABASE_URL=postgresql://postgres:password@db:5432/mydb
|
||||
volumes:
|
||||
- .:/app
|
||||
- /app/node_modules
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
db:
|
||||
image: postgres:15
|
||||
environment:
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=password
|
||||
- POSTGRES_DB=mydb
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
\`\`\`
|
||||
|
||||
### Step 4: Start Services
|
||||
|
||||
\`\`\`bash
|
||||
# Build and start containers
|
||||
docker-compose up -d
|
||||
|
||||
# View logs
|
||||
docker-compose logs -f
|
||||
|
||||
# Stop services
|
||||
docker-compose down
|
||||
\`\`\`
|
||||
|
||||
### Step 5: Verify Services
|
||||
|
||||
\`\`\`bash
|
||||
# Check running containers
|
||||
docker ps
|
||||
|
||||
# Test database connection
|
||||
docker-compose exec db psql -U postgres -d mydb
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### ✅ Do This
|
||||
|
||||
- **Document Everything** - Write clear setup instructions
|
||||
- **Use Version Managers** - nvm for Node, pyenv for Python
|
||||
- **Create .env.example** - Show required environment variables
|
||||
- **Test on Clean System** - Verify instructions work from scratch
|
||||
- **Include Troubleshooting** - Document common issues and solutions
|
||||
- **Use Docker** - For consistent environments across machines
|
||||
- **Pin Versions** - Specify exact versions in package files
|
||||
- **Automate Setup** - Create setup scripts when possible
|
||||
- **Check Prerequisites** - List required tools before starting
|
||||
- **Provide Verification Steps** - Help users confirm setup works
|
||||
|
||||
### ❌ Don't Do This
|
||||
|
||||
- **Don't Assume Tools Installed** - Always check and provide install instructions
|
||||
- **Don't Skip Environment Variables** - Document all required variables
|
||||
- **Don't Use Sudo with npm** - Fix permissions instead
|
||||
- **Don't Forget Platform Differences** - Provide OS-specific instructions
|
||||
- **Don't Leave Out Verification** - Always include test steps
|
||||
- **Don't Use Global Installs** - Prefer local/virtual environments
|
||||
- **Don't Ignore Errors** - Document how to handle common errors
|
||||
- **Don't Skip Database Setup** - Include database initialization steps
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
### Problem: "Command not found" after installation
|
||||
**Symptoms:** Installed tool but terminal doesn't recognize it
|
||||
**Solution:**
|
||||
- Restart terminal or source shell config
|
||||
- Check PATH environment variable
|
||||
- Verify installation location
|
||||
```bash
|
||||
# Check PATH
|
||||
echo $PATH
|
||||
|
||||
# Add to PATH (example)
|
||||
export PATH="/usr/local/bin:$PATH"
|
||||
```
|
||||
|
||||
### Problem: Permission errors with npm/pip
|
||||
**Symptoms:** "EACCES" or "Permission denied" errors
|
||||
**Solution:**
|
||||
- Don't use sudo
|
||||
- Fix npm permissions or use nvm
|
||||
- Use virtual environments for Python
|
||||
```bash
|
||||
# Fix npm permissions
|
||||
mkdir ~/.npm-global
|
||||
npm config set prefix '~/.npm-global'
|
||||
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
|
||||
```
|
||||
|
||||
### Problem: Port already in use
|
||||
**Symptoms:** "Port 3000 is already in use"
|
||||
**Solution:**
|
||||
- Find and kill process using the port
|
||||
- Use a different port
|
||||
```bash
|
||||
# Find process on port 3000
|
||||
lsof -i :3000
|
||||
|
||||
# Kill process
|
||||
kill -9 <PID>
|
||||
|
||||
# Or use different port
|
||||
PORT=3001 npm start
|
||||
```
|
||||
|
||||
### Problem: Database connection fails
|
||||
**Symptoms:** "Connection refused" or "Authentication failed"
|
||||
**Solution:**
|
||||
- Verify database is running
|
||||
- Check connection string
|
||||
- Verify credentials
|
||||
```bash
|
||||
# Check if PostgreSQL is running
|
||||
sudo systemctl status postgresql
|
||||
|
||||
# Test connection
|
||||
psql -h localhost -U postgres -d mydb
|
||||
```
|
||||
|
||||
## Setup Script Template
|
||||
|
||||
Create a `setup.sh` script to automate setup:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
echo "🚀 Setting up development environment..."
|
||||
|
||||
# Check prerequisites
|
||||
command -v node >/dev/null 2>&1 || { echo "❌ Node.js not installed"; exit 1; }
|
||||
command -v git >/dev/null 2>&1 || { echo "❌ Git not installed"; exit 1; }
|
||||
|
||||
echo "✅ Prerequisites check passed"
|
||||
|
||||
# Install dependencies
|
||||
echo "📦 Installing dependencies..."
|
||||
npm install
|
||||
|
||||
# Copy environment file
|
||||
if [ ! -f .env ]; then
|
||||
echo "📝 Creating .env file..."
|
||||
cp .env.example .env
|
||||
echo "⚠️ Please edit .env with your configuration"
|
||||
fi
|
||||
|
||||
# Run database migrations
|
||||
echo "🗄️ Running database migrations..."
|
||||
npm run migrate
|
||||
|
||||
# Verify setup
|
||||
echo "🔍 Verifying setup..."
|
||||
npm run test:setup
|
||||
|
||||
echo "✅ Setup complete! Run 'npm run dev' to start"
|
||||
```
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `@brainstorming` - Plan environment requirements before setup
|
||||
- `@systematic-debugging` - Debug environment issues
|
||||
- `@doc-coauthoring` - Create setup documentation
|
||||
- `@git-pushing` - Set up Git configuration
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Node.js Installation Guide](https://nodejs.org/en/download/)
|
||||
- [Python Virtual Environments](https://docs.python.org/3/tutorial/venv.html)
|
||||
- [Docker Documentation](https://docs.docker.com/get-started/)
|
||||
- [Homebrew (macOS)](https://brew.sh/)
|
||||
- [Chocolatey (Windows)](https://chocolatey.org/)
|
||||
- [nvm (Node Version Manager)](https://github.com/nvm-sh/nvm)
|
||||
- [pyenv (Python Version Manager)](https://github.com/pyenv/pyenv)
|
||||
|
||||
---
|
||||
|
||||
**Pro Tip:** Create a `setup.sh` or `setup.ps1` script to automate the entire setup process. Test it on a clean system to ensure it works!
|
||||
646
skills/web-performance-optimization/SKILL.md
Normal file
646
skills/web-performance-optimization/SKILL.md
Normal file
@@ -0,0 +1,646 @@
|
||||
---
|
||||
name: web-performance-optimization
|
||||
description: "Optimize website and web application performance including loading speed, Core Web Vitals, bundle size, caching strategies, and runtime performance"
|
||||
---
|
||||
|
||||
# Web Performance Optimization
|
||||
|
||||
## Overview
|
||||
|
||||
Help developers optimize website and web application performance to improve user experience, SEO rankings, and conversion rates. This skill provides systematic approaches to measure, analyze, and improve loading speed, runtime performance, and Core Web Vitals metrics.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Use when website or app is loading slowly
|
||||
- Use when optimizing for Core Web Vitals (LCP, FID, CLS)
|
||||
- Use when reducing JavaScript bundle size
|
||||
- Use when improving Time to Interactive (TTI)
|
||||
- Use when optimizing images and assets
|
||||
- Use when implementing caching strategies
|
||||
- Use when debugging performance bottlenecks
|
||||
- Use when preparing for performance audits
|
||||
|
||||
## How It Works
|
||||
|
||||
### Step 1: Measure Current Performance
|
||||
|
||||
I'll help you establish baseline metrics:
|
||||
- Run Lighthouse audits
|
||||
- Measure Core Web Vitals (LCP, FID, CLS)
|
||||
- Check bundle sizes
|
||||
- Analyze network waterfall
|
||||
- Identify performance bottlenecks
|
||||
|
||||
### Step 2: Identify Issues
|
||||
|
||||
Analyze performance problems:
|
||||
- Large JavaScript bundles
|
||||
- Unoptimized images
|
||||
- Render-blocking resources
|
||||
- Slow server response times
|
||||
- Missing caching headers
|
||||
- Layout shifts
|
||||
- Long tasks blocking main thread
|
||||
|
||||
### Step 3: Prioritize Optimizations
|
||||
|
||||
Focus on high-impact improvements:
|
||||
- Critical rendering path optimization
|
||||
- Code splitting and lazy loading
|
||||
- Image optimization
|
||||
- Caching strategies
|
||||
- Third-party script optimization
|
||||
|
||||
### Step 4: Implement Optimizations
|
||||
|
||||
Apply performance improvements:
|
||||
- Optimize assets (images, fonts, CSS, JS)
|
||||
- Implement code splitting
|
||||
- Add caching headers
|
||||
- Lazy load non-critical resources
|
||||
- Optimize critical rendering path
|
||||
|
||||
### Step 5: Verify Improvements
|
||||
|
||||
Measure impact of changes:
|
||||
- Re-run Lighthouse audits
|
||||
- Compare before/after metrics
|
||||
- Monitor real user metrics (RUM)
|
||||
- Test on different devices and networks
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: Optimizing Core Web Vitals
|
||||
|
||||
```markdown
|
||||
## Performance Audit Results
|
||||
|
||||
### Current Metrics (Before Optimization)
|
||||
- **LCP (Largest Contentful Paint):** 4.2s ❌ (should be < 2.5s)
|
||||
- **FID (First Input Delay):** 180ms ❌ (should be < 100ms)
|
||||
- **CLS (Cumulative Layout Shift):** 0.25 ❌ (should be < 0.1)
|
||||
- **Lighthouse Score:** 62/100
|
||||
|
||||
### Issues Identified
|
||||
|
||||
1. **LCP Issue:** Hero image (2.5MB) loads slowly
|
||||
2. **FID Issue:** Large JavaScript bundle (850KB) blocks main thread
|
||||
3. **CLS Issue:** Images without dimensions cause layout shifts
|
||||
|
||||
### Optimization Plan
|
||||
|
||||
#### Fix LCP (Largest Contentful Paint)
|
||||
|
||||
**Problem:** Hero image is 2.5MB and loads slowly
|
||||
|
||||
**Solutions:**
|
||||
\`\`\`html
|
||||
<!-- Before: Unoptimized image -->
|
||||
<img src="/hero.jpg" alt="Hero">
|
||||
|
||||
<!-- After: Optimized with modern formats -->
|
||||
<picture>
|
||||
<source srcset="/hero.avif" type="image/avif">
|
||||
<source srcset="/hero.webp" type="image/webp">
|
||||
<img
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
width="1200"
|
||||
height="600"
|
||||
loading="eager"
|
||||
fetchpriority="high"
|
||||
>
|
||||
</picture>
|
||||
\`\`\`
|
||||
|
||||
**Additional optimizations:**
|
||||
- Compress image to < 200KB
|
||||
- Use CDN for faster delivery
|
||||
- Preload hero image: `<link rel="preload" as="image" href="/hero.avif">`
|
||||
|
||||
#### Fix FID (First Input Delay)
|
||||
|
||||
**Problem:** 850KB JavaScript bundle blocks main thread
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. **Code Splitting:**
|
||||
\`\`\`javascript
|
||||
// Before: Everything in one bundle
|
||||
import { HeavyComponent } from './HeavyComponent';
|
||||
import { Analytics } from './analytics';
|
||||
import { ChatWidget } from './chat';
|
||||
|
||||
// After: Lazy load non-critical code
|
||||
const HeavyComponent = lazy(() => import('./HeavyComponent'));
|
||||
const ChatWidget = lazy(() => import('./chat'));
|
||||
|
||||
// Load analytics after page interactive
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('load', () => {
|
||||
import('./analytics').then(({ Analytics }) => {
|
||||
Analytics.init();
|
||||
});
|
||||
});
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
2. **Remove Unused Dependencies:**
|
||||
\`\`\`bash
|
||||
# Analyze bundle
|
||||
npx webpack-bundle-analyzer
|
||||
|
||||
# Remove unused packages
|
||||
npm uninstall moment # Use date-fns instead (smaller)
|
||||
npm install date-fns
|
||||
\`\`\`
|
||||
|
||||
3. **Defer Non-Critical Scripts:**
|
||||
\`\`\`html
|
||||
<!-- Before: Blocks rendering -->
|
||||
<script src="/analytics.js"></script>
|
||||
|
||||
<!-- After: Deferred -->
|
||||
<script src="/analytics.js" defer></script>
|
||||
\`\`\`
|
||||
|
||||
#### Fix CLS (Cumulative Layout Shift)
|
||||
|
||||
**Problem:** Images without dimensions cause layout shifts
|
||||
|
||||
**Solutions:**
|
||||
\`\`\`html
|
||||
<!-- Before: No dimensions -->
|
||||
<img src="/product.jpg" alt="Product">
|
||||
|
||||
<!-- After: With dimensions -->
|
||||
<img
|
||||
src="/product.jpg"
|
||||
alt="Product"
|
||||
width="400"
|
||||
height="300"
|
||||
style="aspect-ratio: 4/3;"
|
||||
>
|
||||
\`\`\`
|
||||
|
||||
**For dynamic content:**
|
||||
\`\`\`css
|
||||
/* Reserve space for content that loads later */
|
||||
.skeleton-loader {
|
||||
min-height: 200px;
|
||||
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: loading 1.5s infinite;
|
||||
}
|
||||
|
||||
@keyframes loading {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### Results After Optimization
|
||||
|
||||
- **LCP:** 1.8s ✅ (improved by 57%)
|
||||
- **FID:** 45ms ✅ (improved by 75%)
|
||||
- **CLS:** 0.05 ✅ (improved by 80%)
|
||||
- **Lighthouse Score:** 94/100 ✅
|
||||
```
|
||||
|
||||
### Example 2: Reducing JavaScript Bundle Size
|
||||
|
||||
```markdown
|
||||
## Bundle Size Optimization
|
||||
|
||||
### Current State
|
||||
- **Total Bundle:** 850KB (gzipped: 280KB)
|
||||
- **Main Bundle:** 650KB
|
||||
- **Vendor Bundle:** 200KB
|
||||
- **Load Time (3G):** 8.2s
|
||||
|
||||
### Analysis
|
||||
|
||||
\`\`\`bash
|
||||
# Analyze bundle composition
|
||||
npx webpack-bundle-analyzer dist/stats.json
|
||||
\`\`\`
|
||||
|
||||
**Findings:**
|
||||
1. Moment.js: 67KB (can replace with date-fns: 12KB)
|
||||
2. Lodash: 72KB (using entire library, only need 5 functions)
|
||||
3. Unused code: ~150KB of dead code
|
||||
4. No code splitting: Everything in one bundle
|
||||
|
||||
### Optimization Steps
|
||||
|
||||
#### 1. Replace Heavy Dependencies
|
||||
|
||||
\`\`\`bash
|
||||
# Remove moment.js (67KB) → Use date-fns (12KB)
|
||||
npm uninstall moment
|
||||
npm install date-fns
|
||||
|
||||
# Before
|
||||
import moment from 'moment';
|
||||
const formatted = moment(date).format('YYYY-MM-DD');
|
||||
|
||||
# After
|
||||
import { format } from 'date-fns';
|
||||
const formatted = format(date, 'yyyy-MM-dd');
|
||||
\`\`\`
|
||||
|
||||
**Savings:** 55KB
|
||||
|
||||
#### 2. Use Lodash Selectively
|
||||
|
||||
\`\`\`javascript
|
||||
// Before: Import entire library (72KB)
|
||||
import _ from 'lodash';
|
||||
const unique = _.uniq(array);
|
||||
|
||||
// After: Import only what you need (5KB)
|
||||
import uniq from 'lodash/uniq';
|
||||
const unique = uniq(array);
|
||||
|
||||
// Or use native methods
|
||||
const unique = [...new Set(array)];
|
||||
\`\`\`
|
||||
|
||||
**Savings:** 67KB
|
||||
|
||||
#### 3. Implement Code Splitting
|
||||
|
||||
\`\`\`javascript
|
||||
// Next.js example
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
// Lazy load heavy components
|
||||
const Chart = dynamic(() => import('./Chart'), {
|
||||
loading: () => <div>Loading chart...</div>,
|
||||
ssr: false
|
||||
});
|
||||
|
||||
const AdminPanel = dynamic(() => import('./AdminPanel'), {
|
||||
loading: () => <div>Loading...</div>
|
||||
});
|
||||
|
||||
// Route-based code splitting (automatic in Next.js)
|
||||
// pages/admin.js - Only loaded when visiting /admin
|
||||
// pages/dashboard.js - Only loaded when visiting /dashboard
|
||||
\`\`\`
|
||||
|
||||
#### 4. Remove Dead Code
|
||||
|
||||
\`\`\`javascript
|
||||
// Enable tree shaking in webpack.config.js
|
||||
module.exports = {
|
||||
mode: 'production',
|
||||
optimization: {
|
||||
usedExports: true,
|
||||
sideEffects: false
|
||||
}
|
||||
};
|
||||
|
||||
// In package.json
|
||||
{
|
||||
"sideEffects": false
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
#### 5. Optimize Third-Party Scripts
|
||||
|
||||
\`\`\`html
|
||||
<!-- Before: Loads immediately -->
|
||||
<script src="https://analytics.com/script.js"></script>
|
||||
|
||||
<!-- After: Load after page interactive -->
|
||||
<script>
|
||||
window.addEventListener('load', () => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://analytics.com/script.js';
|
||||
script.async = true;
|
||||
document.body.appendChild(script);
|
||||
});
|
||||
</script>
|
||||
\`\`\`
|
||||
|
||||
### Results
|
||||
|
||||
- **Total Bundle:** 380KB ✅ (reduced by 55%)
|
||||
- **Main Bundle:** 180KB ✅
|
||||
- **Vendor Bundle:** 80KB ✅
|
||||
- **Load Time (3G):** 3.1s ✅ (improved by 62%)
|
||||
```
|
||||
|
||||
### Example 3: Image Optimization Strategy
|
||||
|
||||
```markdown
|
||||
## Image Optimization
|
||||
|
||||
### Current Issues
|
||||
- 15 images totaling 12MB
|
||||
- No modern formats (WebP, AVIF)
|
||||
- No responsive images
|
||||
- No lazy loading
|
||||
|
||||
### Optimization Strategy
|
||||
|
||||
#### 1. Convert to Modern Formats
|
||||
|
||||
\`\`\`bash
|
||||
# Install image optimization tools
|
||||
npm install sharp
|
||||
|
||||
# Conversion script (optimize-images.js)
|
||||
const sharp = require('sharp');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
async function optimizeImage(inputPath, outputDir) {
|
||||
const filename = path.basename(inputPath, path.extname(inputPath));
|
||||
|
||||
// Generate WebP
|
||||
await sharp(inputPath)
|
||||
.webp({ quality: 80 })
|
||||
.toFile(path.join(outputDir, \`\${filename}.webp\`));
|
||||
|
||||
// Generate AVIF (best compression)
|
||||
await sharp(inputPath)
|
||||
.avif({ quality: 70 })
|
||||
.toFile(path.join(outputDir, \`\${filename}.avif\`));
|
||||
|
||||
// Generate optimized JPEG fallback
|
||||
await sharp(inputPath)
|
||||
.jpeg({ quality: 80, progressive: true })
|
||||
.toFile(path.join(outputDir, \`\${filename}.jpg\`));
|
||||
}
|
||||
|
||||
// Process all images
|
||||
const images = fs.readdirSync('./images');
|
||||
images.forEach(img => {
|
||||
optimizeImage(\`./images/\${img}\`, './images/optimized');
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
#### 2. Implement Responsive Images
|
||||
|
||||
\`\`\`html
|
||||
<!-- Responsive images with modern formats -->
|
||||
<picture>
|
||||
<!-- AVIF for browsers that support it (best compression) -->
|
||||
<source
|
||||
srcset="
|
||||
/images/hero-400.avif 400w,
|
||||
/images/hero-800.avif 800w,
|
||||
/images/hero-1200.avif 1200w
|
||||
"
|
||||
type="image/avif"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
>
|
||||
|
||||
<!-- WebP for browsers that support it -->
|
||||
<source
|
||||
srcset="
|
||||
/images/hero-400.webp 400w,
|
||||
/images/hero-800.webp 800w,
|
||||
/images/hero-1200.webp 1200w
|
||||
"
|
||||
type="image/webp"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
>
|
||||
|
||||
<!-- JPEG fallback -->
|
||||
<img
|
||||
src="/images/hero-800.jpg"
|
||||
srcset="
|
||||
/images/hero-400.jpg 400w,
|
||||
/images/hero-800.jpg 800w,
|
||||
/images/hero-1200.jpg 1200w
|
||||
"
|
||||
sizes="(max-width: 768px) 100vw, 50vw"
|
||||
alt="Hero image"
|
||||
width="1200"
|
||||
height="600"
|
||||
loading="lazy"
|
||||
>
|
||||
</picture>
|
||||
\`\`\`
|
||||
|
||||
#### 3. Lazy Loading
|
||||
|
||||
\`\`\`html
|
||||
<!-- Native lazy loading -->
|
||||
<img
|
||||
src="/image.jpg"
|
||||
alt="Description"
|
||||
loading="lazy"
|
||||
width="800"
|
||||
height="600"
|
||||
>
|
||||
|
||||
<!-- Eager loading for above-the-fold images -->
|
||||
<img
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
loading="eager"
|
||||
fetchpriority="high"
|
||||
>
|
||||
\`\`\`
|
||||
|
||||
#### 4. Next.js Image Component
|
||||
|
||||
\`\`\`javascript
|
||||
import Image from 'next/image';
|
||||
|
||||
// Automatic optimization
|
||||
<Image
|
||||
src="/hero.jpg"
|
||||
alt="Hero"
|
||||
width={1200}
|
||||
height={600}
|
||||
priority // For above-the-fold images
|
||||
quality={80}
|
||||
/>
|
||||
|
||||
// Lazy loaded
|
||||
<Image
|
||||
src="/product.jpg"
|
||||
alt="Product"
|
||||
width={400}
|
||||
height={300}
|
||||
loading="lazy"
|
||||
/>
|
||||
\`\`\`
|
||||
|
||||
### Results
|
||||
|
||||
| Metric | Before | After | Improvement |
|
||||
|--------|--------|-------|-------------|
|
||||
| Total Image Size | 12MB | 1.8MB | 85% reduction |
|
||||
| LCP | 4.5s | 1.6s | 64% faster |
|
||||
| Page Load (3G) | 18s | 4.2s | 77% faster |
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### ✅ Do This
|
||||
|
||||
- **Measure First** - Always establish baseline metrics before optimizing
|
||||
- **Use Lighthouse** - Run audits regularly to track progress
|
||||
- **Optimize Images** - Use modern formats (WebP, AVIF) and responsive images
|
||||
- **Code Split** - Break large bundles into smaller chunks
|
||||
- **Lazy Load** - Defer non-critical resources
|
||||
- **Cache Aggressively** - Set proper cache headers for static assets
|
||||
- **Minimize Main Thread Work** - Keep JavaScript execution under 50ms chunks
|
||||
- **Preload Critical Resources** - Use `<link rel="preload">` for critical assets
|
||||
- **Use CDN** - Serve static assets from CDN for faster delivery
|
||||
- **Monitor Real Users** - Track Core Web Vitals from real users
|
||||
|
||||
### ❌ Don't Do This
|
||||
|
||||
- **Don't Optimize Blindly** - Measure first, then optimize
|
||||
- **Don't Ignore Mobile** - Test on real mobile devices and slow networks
|
||||
- **Don't Block Rendering** - Avoid render-blocking CSS and JavaScript
|
||||
- **Don't Load Everything Upfront** - Lazy load non-critical resources
|
||||
- **Don't Forget Dimensions** - Always specify image width/height
|
||||
- **Don't Use Synchronous Scripts** - Use async or defer attributes
|
||||
- **Don't Ignore Third-Party Scripts** - They often cause performance issues
|
||||
- **Don't Skip Compression** - Always compress and minify assets
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
### Problem: Optimized for Desktop but Slow on Mobile
|
||||
**Symptoms:** Good Lighthouse score on desktop, poor on mobile
|
||||
**Solution:**
|
||||
- Test on real mobile devices
|
||||
- Use Chrome DevTools mobile throttling
|
||||
- Optimize for 3G/4G networks
|
||||
- Reduce JavaScript execution time
|
||||
```bash
|
||||
# Test with throttling
|
||||
lighthouse https://yoursite.com --throttling.cpuSlowdownMultiplier=4
|
||||
```
|
||||
|
||||
### Problem: Large JavaScript Bundle
|
||||
**Symptoms:** Long Time to Interactive (TTI), high FID
|
||||
**Solution:**
|
||||
- Analyze bundle with webpack-bundle-analyzer
|
||||
- Remove unused dependencies
|
||||
- Implement code splitting
|
||||
- Lazy load non-critical code
|
||||
```bash
|
||||
# Analyze bundle
|
||||
npx webpack-bundle-analyzer dist/stats.json
|
||||
```
|
||||
|
||||
### Problem: Images Causing Layout Shifts
|
||||
**Symptoms:** High CLS score, content jumping
|
||||
**Solution:**
|
||||
- Always specify width and height
|
||||
- Use aspect-ratio CSS property
|
||||
- Reserve space with skeleton loaders
|
||||
```css
|
||||
img {
|
||||
aspect-ratio: 16 / 9;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
```
|
||||
|
||||
### Problem: Slow Server Response Time
|
||||
**Symptoms:** High TTFB (Time to First Byte)
|
||||
**Solution:**
|
||||
- Implement server-side caching
|
||||
- Use CDN for static assets
|
||||
- Optimize database queries
|
||||
- Consider static site generation (SSG)
|
||||
```javascript
|
||||
// Next.js: Static generation
|
||||
export async function getStaticProps() {
|
||||
const data = await fetchData();
|
||||
return {
|
||||
props: { data },
|
||||
revalidate: 60 // Regenerate every 60 seconds
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Checklist
|
||||
|
||||
### Images
|
||||
- [ ] Convert to modern formats (WebP, AVIF)
|
||||
- [ ] Implement responsive images
|
||||
- [ ] Add lazy loading
|
||||
- [ ] Specify dimensions (width/height)
|
||||
- [ ] Compress images (< 200KB each)
|
||||
- [ ] Use CDN for delivery
|
||||
|
||||
### JavaScript
|
||||
- [ ] Bundle size < 200KB (gzipped)
|
||||
- [ ] Implement code splitting
|
||||
- [ ] Lazy load non-critical code
|
||||
- [ ] Remove unused dependencies
|
||||
- [ ] Minify and compress
|
||||
- [ ] Use async/defer for scripts
|
||||
|
||||
### CSS
|
||||
- [ ] Inline critical CSS
|
||||
- [ ] Defer non-critical CSS
|
||||
- [ ] Remove unused CSS
|
||||
- [ ] Minify CSS files
|
||||
- [ ] Use CSS containment
|
||||
|
||||
### Caching
|
||||
- [ ] Set cache headers for static assets
|
||||
- [ ] Implement service worker
|
||||
- [ ] Use CDN caching
|
||||
- [ ] Cache API responses
|
||||
- [ ] Version static assets
|
||||
|
||||
### Core Web Vitals
|
||||
- [ ] LCP < 2.5s
|
||||
- [ ] FID < 100ms
|
||||
- [ ] CLS < 0.1
|
||||
- [ ] TTFB < 600ms
|
||||
- [ ] TTI < 3.8s
|
||||
|
||||
## Performance Tools
|
||||
|
||||
### Measurement Tools
|
||||
- **Lighthouse** - Comprehensive performance audit
|
||||
- **WebPageTest** - Detailed waterfall analysis
|
||||
- **Chrome DevTools** - Performance profiling
|
||||
- **PageSpeed Insights** - Real user metrics
|
||||
- **Web Vitals Extension** - Monitor Core Web Vitals
|
||||
|
||||
### Analysis Tools
|
||||
- **webpack-bundle-analyzer** - Visualize bundle composition
|
||||
- **source-map-explorer** - Analyze bundle size
|
||||
- **Bundlephobia** - Check package sizes before installing
|
||||
- **ImageOptim** - Image compression tool
|
||||
|
||||
### Monitoring Tools
|
||||
- **Google Analytics** - Track Core Web Vitals
|
||||
- **Sentry** - Performance monitoring
|
||||
- **New Relic** - Application performance monitoring
|
||||
- **Datadog** - Real user monitoring
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `@react-best-practices` - React performance patterns
|
||||
- `@frontend-dev-guidelines` - Frontend development standards
|
||||
- `@systematic-debugging` - Debug performance issues
|
||||
- `@senior-architect` - Architecture for performance
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Web.dev Performance](https://web.dev/performance/)
|
||||
- [Core Web Vitals](https://web.dev/vitals/)
|
||||
- [Lighthouse Documentation](https://developers.google.com/web/tools/lighthouse)
|
||||
- [MDN Performance Guide](https://developer.mozilla.org/en-US/docs/Web/Performance)
|
||||
- [Next.js Performance](https://nextjs.org/docs/advanced-features/measuring-performance)
|
||||
- [Image Optimization Guide](https://web.dev/fast/#optimize-your-images)
|
||||
|
||||
---
|
||||
|
||||
**Pro Tip:** Focus on Core Web Vitals (LCP, FID, CLS) first - they have the biggest impact on user experience and SEO rankings!
|
||||
@@ -287,6 +287,12 @@
|
||||
"name": "api-patterns",
|
||||
"description": "API design principles and decision-making. REST vs GraphQL vs tRPC selection, response formats, versioning, pagination."
|
||||
},
|
||||
{
|
||||
"id": "api-security-best-practices",
|
||||
"path": "skills/api-security-best-practices",
|
||||
"name": "api-security-best-practices",
|
||||
"description": "\"Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities\""
|
||||
},
|
||||
{
|
||||
"id": "app-builder",
|
||||
"path": "skills/app-builder",
|
||||
@@ -447,7 +453,7 @@
|
||||
"id": "code-review-checklist",
|
||||
"path": "skills/code-review-checklist",
|
||||
"name": "code-review-checklist",
|
||||
"description": "Code review guidelines covering code quality, security, and best practices."
|
||||
"description": "\"Comprehensive checklist for conducting thorough code reviews covering functionality, security, performance, and maintainability\""
|
||||
},
|
||||
{
|
||||
"id": "cc-skill-coding-standards",
|
||||
@@ -581,6 +587,12 @@
|
||||
"name": "email-systems",
|
||||
"description": "\"Email has the highest ROI of any marketing channel. $36 for every $1 spent. Yet most startups treat it as an afterthought - bulk blasts, no personalization, landing in spam folders. This skill covers transactional email that works, marketing automation that converts, deliverability that reaches inboxes, and the infrastructure decisions that scale. Use when: keywords, file_patterns, code_patterns.\""
|
||||
},
|
||||
{
|
||||
"id": "environment-setup-guide",
|
||||
"path": "skills/environment-setup-guide",
|
||||
"name": "environment-setup-guide",
|
||||
"description": "\"Guide developers through setting up development environments with proper tools, dependencies, and configurations\""
|
||||
},
|
||||
{
|
||||
"id": "executing-plans",
|
||||
"path": "skills/executing-plans",
|
||||
@@ -1373,6 +1385,12 @@
|
||||
"name": "web-games",
|
||||
"description": "Web browser game development principles. Framework selection, WebGPU, optimization, PWA."
|
||||
},
|
||||
{
|
||||
"id": "web-performance-optimization",
|
||||
"path": "skills/web-performance-optimization",
|
||||
"name": "web-performance-optimization",
|
||||
"description": "\"Optimize website and web application performance including loading speed, Core Web Vitals, bundle size, caching strategies, and runtime performance\""
|
||||
},
|
||||
{
|
||||
"id": "webapp-testing",
|
||||
"path": "skills/webapp-testing",
|
||||
|
||||
Reference in New Issue
Block a user