Claude Code in Action
Complete guide to leveraging Claude Code as your AI-powered development assistant.
What is Claude Code?
Claude Code is Anthropic's official CLI tool that brings Claude AI directly into your development workflow, enabling AI-assisted coding, debugging, and project management.
Key Features:
Available Platforms:
Installation
Prerequisites
Before installing, ensure you have:
Install Claude Code CLI
# ========== macOS (Homebrew) ==========
brew install anthropics/claude/claude
# ========== Linux (Shell Script) ==========
curl -fsSL https://claude.ai/install.sh | sh
# ========== Windows (PowerShell) ==========
irm https://claude.ai/install.ps1 | iex
# ========== Verify Installation ==========
claude --version
First-time Setup:
# Initialize Claude Code
claude auth login
# This will:
# 1. Open browser for authentication
# 2. Store credentials securely
# 3. Configure default settings
Basic Usage
Starting a Conversation
# ========== Start in Current Directory ==========
claude
# ========== Start in Specific Directory ==========
claude /path/to/project
# ========== Quick Question (No Session) ==========
claude -q "How do I read a file in Python?"
# ========== Continue Previous Session ==========
claude --continue
Interactive Mode:
$ claude
Welcome to Claude Code!
Working directory: /home/user/myproject
You: help me fix the bug in app.py
Claude: I'll analyze the file and help you fix it...
File Operations
Reading Files:You: read app/main.py
Claude: I'll read that file...
[Shows file contents with syntax highlighting]
Editing Files:
You: add error handling to the login function in auth.py
Claude: I'll add try-catch blocks and proper error handling...
[Shows the changes made]
Creating Files:
You: create a new component called UserProfile in components/
Claude: I'll create a new React component...
[Creates components/UserProfile.tsx]
Built-in Commands
Essential Commands
# ========== File Management ==========
/read <file> # Read file contents
/glob **/*.py # Find files by pattern
/grep "function" # Search code for text
# ========== Git Operations ==========
/git status # Show git status
/git diff # Show changes
/git log # View commit history
# ========== Session Management ==========
/clear # Clear conversation
/help # Show available commands
/settings # View/edit settings
# ========== Skills (Custom Commands) ==========
/init # Initialize CLAUDE.md
/review # Review pull request
/security-review # Security analysis
Advanced Commands
# ========== Code Analysis ==========
/explore # Explore codebase structure
/impact <symbol> # Analyze change impact
/trace <error> # Debug error traces
# ========== Automation ==========
/loop 5m /check-tests # Run command every 5 minutes
/hook # Configure automation hooks
Skills System
What are Skills?
Skills are reusable, specialized workflows that Claude can execute. Think of them as "slash commands" with superpowers.
Using Built-in Skills
Initialize Project Documentation:# Inside your project
claude
You: /init
Claude: I'll create a CLAUDE.md file documenting your codebase...
[Analyzes project and creates comprehensive documentation]
Review Pull Request:
You: /review
Claude: I'll review the current PR...
Pull Request Review:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Code Quality: Good
⚠️ Security: 1 issue found
📊 Test Coverage: 85%
Issues Found:
1. Potential SQL injection in user_query.py:45
Recommendation: Use parameterized queries
Security Review:
You: /security-review
Claude: Running comprehensive security analysis...
Security Report:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔴 Critical: 0
🟠 High: 1
🟡 Medium: 3
🟢 Low: 5
Details:
[Lists vulnerabilities with file locations and fixes]
Creating Custom Skills
Create .claude/skills/deploy/SKILL.md:
---
name: deploy
description: Deploy application to production
---
# Deploy Skill
This skill handles deployment workflow:
1. Run tests
2. Build application
3. Deploy to server
4. Verify deployment
## Usage
/deploy [environment]
## Implementation
- Check git status (must be clean)
- Run `npm test`
- Run `npm run build`
- Deploy using configured method
- Run health checks
Use Custom Skill:
You: /deploy production
Claude: Starting deployment to production...
✓ Git status clean
✓ Tests passed (42 tests)
✓ Build successful
✓ Deployed to production
✓ Health check passed
Deployment completed successfully!
URL: https://myapp.com
Hooks System
What are Hooks?
Hooks are automated actions that trigger before or after certain events.
Configuring Hooks
Edit .claude/settings.json:
{
"hooks": {
"before:commit": "npm run lint && npm test",
"after:commit": "echo 'Commit created successfully'",
"before:push": "npm run build",
"on:file:save": "npx prettier --write"
}
}
Common Hook Patterns
Pre-commit Validation:{
"hooks": {
"before:commit": [
"npm run lint",
"npm run type-check",
"npm test"
]
}
}
Automated Documentation:
{
"hooks": {
"after:edit": "npx typedoc --out docs"
}
}
Code Quality Gates:
{
"hooks": {
"before:push": [
"npm run lint",
"npm run test:coverage",
"npm run build"
]
}
}
MCP Integration
What is MCP?
Model Context Protocol (MCP) allows Claude Code to integrate with external tools and services.
Using MCP Tools
List Available MCP Tools:You: show me available MCP tools
Claude: Available MCP integrations:
- gitnexus: Code intelligence and impact analysis
- database: Query and manage databases
- slack: Send notifications and messages
- github: Create issues, PRs, and manage repos
Example: GitNexus Integration
You: what will break if I change the User model?
Claude: I'll use GitNexus to analyze the impact...
Impact Analysis: User model
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Direct Dependencies (23 files):
• app/controllers/user_controller.py
• app/services/auth_service.py
• app/models/order.py
...
🔗 Indirect Dependencies (67 files):
• app/api/routes/users.py
• app/api/routes/orders.py
...
⚠️ Risk Level: HIGH
💡 Recommendation: Run full test suite before merging
Installing MCP Servers
Add MCP Server to Configuration:
{
"mcpServers": {
"gitnexus": {
"command": "npx",
"args": ["-y", "@gitnexus/mcp-server"]
},
"database": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://localhost/mydb"
}
}
}
}
Workflow Examples
Debugging Workflow
Step 1: Identify the IssueYou: I'm getting "TypeError: Cannot read property 'name' of undefined" in UserProfile component
Claude: I'll help debug this. Let me check the UserProfile component...
[Reads the file and analyzes the error]
Found the issue at line 45:
const userName = user.name;
The 'user' object might be undefined when the component first renders.
Step 2: Trace the Data Flow
You: trace where the user object comes from
Claude: Tracing data flow...
1. UserProfile.tsx receives 'user' as prop
2. Prop comes from Dashboard.tsx:getUserData()
3. getUserData() is async and initially returns undefined
4. Component renders before data loads
Recommendation: Add null check or loading state
Step 3: Fix the Issue
You: add proper null checks and loading state
Claude: I'll update UserProfile.tsx with null checks and loading state...
[Shows the changes]
Changes made:
✓ Added null check for user object
✓ Added loading state
✓ Added error boundary
✓ Updated PropTypes
Refactoring Workflow
Step 1: Assess ImpactYou: I want to rename validateUser to validateUserInput. Is it safe?
Claude: I'll check the impact using GitNexus...
Impact Analysis: validateUser function
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Used in 12 files:
• auth.py (3 calls)
• user_service.py (2 calls)
• api/routes.py (5 calls)
• tests/test_auth.py (4 calls)
Risk: MEDIUM
It's safe to rename, but all 14 usages must be updated.
Step 2: Perform Refactoring
You: rename it safely across the codebase
Claude: I'll use GitNexus to rename the function safely...
Renaming 'validateUser' → 'validateUserInput'
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ Updated auth.py (3 occurrences)
✓ Updated user_service.py (2 occurrences)
✓ Updated api/routes.py (5 occurrences)
✓ Updated tests/test_auth.py (4 occurrences)
Total: 14 updates across 12 files
Step 3: Verify Changes
You: /git diff
Claude: Here are the changes:
[Shows unified diff of all modified files]
You: run the tests
Claude: Running tests...
✓ All tests passed (156 tests in 12.3s)
Feature Development Workflow
Step 1: Plan the FeatureYou: I need to add email verification to the user registration flow
Claude: I'll help you plan this feature. Here's what we'll need:
1. Database Changes:
- Add 'email_verified' boolean to User model
- Add 'verification_token' string to User model
- Create migration
2. Backend:
- Generate verification token on signup
- Send verification email
- Create /verify endpoint
- Update login to check email_verified
3. Frontend:
- Show verification message after signup
- Create verification page
- Handle already-verified state
4. Tests:
- Unit tests for token generation
- Integration tests for verification flow
- E2E tests for user journey
Should I proceed with implementation?
Step 2: Implement Backend
You: yes, start with the database migration
Claude: I'll create the migration...
[Creates migration file]
Created: migrations/20240420_add_email_verification.py
Next, I'll update the User model...
[Updates models/user.py]
Should I continue with the email service?
Step 3: Test as You Go
You: yes, but write tests first
Claude: Great! Test-driven approach. Creating tests first...
Created: tests/test_email_verification.py
- test_generate_verification_token()
- test_send_verification_email()
- test_verify_email_endpoint()
- test_prevent_unverified_login()
Now I'll implement the features to make these tests pass...
Code Review Workflow
You: review my changes before I commit
Claude: I'll review your changes...
Code Review Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Files Changed: 5
➕ Additions: 142 lines
➖ Deletions: 38 lines
✅ Strengths:
• Good error handling in auth_service.py
• Comprehensive test coverage (94%)
• Clear variable naming
⚠️ Suggestions:
1. user_controller.py:45
- Add input validation for email format
2. email_service.py:23
- Use environment variable for SMTP host
3. Consider adding:
- Rate limiting for verification endpoint
- Expiry time for verification tokens
Overall: Ready to commit with minor improvements
Best Practices
Writing Effective Prompts
❌ Bad Prompts:You: fix the bug
You: make it better
You: update the code
✅ Good Prompts:
You: fix the authentication bug in auth.py where users can't log in after password reset
You: refactor the getUserData function to use async/await instead of callbacks
You: add error handling to the file upload feature in components/FileUpload.tsx
Using Context Effectively
Provide Relevant Context:You: I'm getting a 500 error when submitting the contact form.
The error happens in api/contact.js around line 45.
The request payload includes name, email, and message fields.
Can you help debug this?
Claude: Let me check api/contact.js...
[Provides targeted help with full context]
Reference Specific Files:
You: in components/Header.tsx, update the navigation menu to include a new "Blog" link
Claude: I'll update the Header component...
[Makes precise changes to the right file]
Leveraging Skills
Use Skills for Common Tasks:# Instead of manually describing what you want
You: /init # Generate project documentation
You: /review # Review current changes
You: /security # Run security scan
# Skills provide consistent, high-quality results
Managing Context Window
Keep Context Relevant:# Start fresh for unrelated tasks
You: /clear
# Focus on specific areas
You: let's focus only on the authentication module
# Summarize before continuing
You: summarize what we've done so far
Project Setup
Initialize Claude for Your Project
Create CLAUDE.md in project root:
# Project Name
Description of your project.
## Tech Stack
- Frontend: React + TypeScript
- Backend: Node.js + Express
- Database: PostgreSQL
- Testing: Jest + Cypress
## Development Guidelines
### Code Style
- Use TypeScript strict mode
- Follow ESLint configuration
- Run Prettier before committing
### Testing
- Write tests for all new features
- Maintain >80% coverage
- Run tests before pushing
### Git Workflow
- Create feature branches
- Write descriptive commit messages
- Squash commits before merging
## Important Files
- `src/App.tsx` - Main application entry
- `src/api/` - API route handlers
- `src/components/` - React components
- `tests/` - Test files
## Common Tasks
### Development
bash
npm run dev # Start dev server
npm test # Run tests
npm run lint # Check code quality
### Deployment
bash
npm run build # Production build
npm run deploy # Deploy to production
## Notes
- Always run migrations before deploying
- API keys stored in .env (never commit)
- Database backups run daily at 2 AM UTC
Configure Settings
Create .claude/settings.json:
{
"model": "claude-sonnet-4.5",
"autoSave": true,
"permissions": {
"read": "allow",
"write": "prompt",
"bash": "prompt",
"git": "allow"
},
"hooks": {
"before:commit": "npm test"
},
"mcpServers": {
"gitnexus": {
"command": "npx",
"args": ["-y", "@gitnexus/mcp-server"]
}
}
}
Advanced Features
Multi-file Editing
Edit Multiple Files Simultaneously:You: update the API to use async/await across all route handlers in src/api/
Claude: I'll update all route handlers...
Updating 8 files:
✓ src/api/users.js
✓ src/api/auth.js
✓ src/api/posts.js
✓ src/api/comments.js
✓ src/api/profile.js
✓ src/api/search.js
✓ src/api/notifications.js
✓ src/api/settings.js
All route handlers now use async/await!
Codebase Exploration
Understand Unfamiliar Code:You: explain how the authentication flow works in this codebase
Claude: I'll analyze the authentication system...
Authentication Flow:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. User submits credentials (Login.tsx)
↓
2. POST /api/auth/login (auth.js:23)
↓
3. Validate credentials (auth_service.py:45)
↓
4. Generate JWT token (token_utils.py:12)
↓
5. Set HTTP-only cookie (auth.js:67)
↓
6. Return user data (auth.js:72)
Key Files:
• components/Login.tsx - Frontend form
• api/auth.js - Authentication endpoint
• services/auth_service.py - Business logic
• utils/token_utils.py - JWT handling
• middleware/auth_middleware.js - Route protection
Automated Workflows
Setup Recurring Tasks:You: /loop 10m run tests and notify me if they fail
Claude: Setting up recurring task...
Task: Run tests every 10 minutes
Command: npm test
Notify: On failure
Task ID: loop_2024_04_20_001
Status: Active
I'll notify you if any tests fail.
Keyboard Shortcuts
Essential Shortcuts
Ctrl+C # Cancel current operation
Ctrl+D # Exit Claude Code
Ctrl+L # Clear screen (keep context)
Ctrl+R # Search command history
Tab # Autocomplete commands
↑/↓ # Navigate command history
Advanced Shortcuts
Ctrl+K # Quick command palette
Ctrl+P # Search files
Ctrl+Shift+P # Search and open file
Troubleshooting
Common Issues
Authentication Problems:# Re-authenticate
claude auth logout
claude auth login
# Check authentication status
claude auth status
Permission Errors:
# Check settings
claude settings
# Allow specific operations
# Edit .claude/settings.json and adjust permissions
Performance Issues:
# Clear cache
claude cache clear
# Reduce context size
You: /clear
# Use smaller model for simple tasks
claude --model haiku
Getting Help
# View documentation
claude help
# Show available commands
/help
# Check version
claude --version
# View logs
claude logs
Tips and Tricks
Productivity Boosters
1. Use Keyboard Shortcuts
2. Create Custom Skills
3. Leverage MCP Integrations
4. Write Good CLAUDE.md
5. Use Git Integration
Power User Tips
Chaining Commands:You: read api/users.js, find the bug, fix it, and run tests
Claude: I'll do that step by step...
[Executes all steps sequentially]
Context Preservation:
You: remember that we're using PostgreSQL and TypeScript strict mode
Claude: Noted! I'll keep that in mind for this session.
Batch Operations:
You: update all components in src/components/ to use the new Button component
Claude: I'll update all components...
[Processes all files matching the pattern]
Real-World Examples
Example 1: Adding a Feature
You: Add a dark mode toggle to the app
Claude: I'll implement dark mode. Here's my plan:
1. Add theme context (src/context/ThemeContext.tsx)
2. Create toggle component (src/components/ThemeToggle.tsx)
3. Update global styles (src/styles/theme.css)
4. Add toggle to navbar (src/components/Navbar.tsx)
5. Persist preference to localStorage
Proceeding with implementation...
✓ Created ThemeContext.tsx
✓ Created ThemeToggle.tsx
✓ Updated theme.css with dark mode variables
✓ Added toggle to Navbar
✓ Added localStorage persistence
Dark mode is now fully functional!
Test it by clicking the toggle in the navbar.
Example 2: Debugging Production Issue
You: Users are reporting slow page loads. The server logs show high database query times. Help me investigate.
Claude: I'll investigate the database performance issue.
Step 1: Analyzing database queries...
[Reads database query code]
Found potential issues:
1. Missing index on users.email (used in auth queries)
2. N+1 query problem in getPosts() - loads comments individually
3. No query result caching
Step 2: Let me check query execution plans...
[Analyzes query patterns]
Recommendations:
1. Add index: CREATE INDEX idx_users_email ON users(email)
2. Use JOIN to load comments with posts
3. Implement Redis caching for frequent queries
Would you like me to implement these fixes?
Example 3: Code Refactoring
You: The UserService class has grown to 500 lines. Help me refactor it.
Claude: I'll help refactor UserService.
Current structure analysis:
- Authentication methods (8 methods, 120 lines)
- Profile management (6 methods, 90 lines)
- User CRUD (10 methods, 180 lines)
- Email operations (4 methods, 80 lines)
- Utility methods (5 methods, 30 lines)
Recommended split:
1. AuthService - authentication methods
2. ProfileService - profile management
3. UserRepository - CRUD operations
4. EmailService - email operations
5. UserService - orchestrates other services
Should I proceed with this refactoring?
Resources
Quick Reference Card
# ========== Getting Started ==========
claude # Start in current directory
claude /path/to/project # Start in specific directory
claude -q "question" # Quick question
# ========== Essential Commands ==========
/help # Show all commands
/clear # Clear conversation
/read <file> # Read file
/git status # Git status
# ========== Skills ==========
/init # Initialize CLAUDE.md
/review # Review PR
/security-review # Security scan
# ========== Settings ==========
claude settings # View settings
claude auth login # Authenticate
claude cache clear # Clear cache
Next Steps
CLAUDE.md for your project.claude/settings.json/init, /review)---
Last Updated: 2026-04-20 Claude Code Version: Latest Difficulty: Intermediate