Claude Code isn't just another AI coding assistant. It's a command-line powerhouse that transforms your terminal into an intelligent development environment. After extensive testing and real-world use, here's everything you need to know to use it like a professional developer.
What is Claude Code CLI?
Claude Code CLI is Anthropic's official command-line interface for AI-powered development. Think of it as having an expert pair programmer in your terminal who can:
- Read and understand your entire codebase
- Make multi-file changes with precision
- Execute shell commands and Git operations
- Connect to external tools via MCP servers
- Learn your project patterns through configuration
Unlike web-based AI tools, Claude Code integrates directly into your development workflow. No context switching, no copy-pasting code. Just pure terminal-based coding at machine speed.
Installation and Setup
Quick Install
# Install Claude Code CLI
npm install -g @anthropic-ai/claude-code
# Verify installation
claude --version
# Start your first session
claude
Initial Configuration
On first run, Claude Code creates a settings directory at ~/.claude/. This stores your preferences, MCP configurations, and project memory.
# Check your configuration
claude --config
# Initialize project-specific settings
claude --init
The --init command generates a .claude/ directory in your project with starter configurations. This is where your project's intelligence lives.
Choosing the Right Model: Sonnet 4.5 vs Opus vs Haiku
Claude Code gives you access to three powerful models. Choosing the right one dramatically impacts your productivity and costs.
Claude Sonnet 4.5 (Default – Best for Most Work)
When to use:
- Complex coding tasks requiring multi-step reasoning
- Building AI agents with tool orchestration
- Refactoring large codebases
- Computer use tasks and file manipulation
Performance:
- Balanced intelligence and speed
- Excellent at sustained reasoning
- Strong context awareness (200K tokens, 1M in preview)
- $3/MTok input, $15/MTok output
Real example:
# Switch to Sonnet for complex refactoring
claude --model claude-sonnet-4-5
> "Refactor the authentication system to use JWT tokens instead of sessions. Update all middleware, tests, and documentation."
Sonnet handles this multi-file, multi-concern task with precision. It understands dependencies and makes consistent changes across your codebase.
Claude Opus 4.1 (Deep Thinking)
When to use:
- Architecture decisions requiring deep analysis
- Code reviews for critical systems
- Complex debugging sessions
- Research and planning phases
Performance:
- Exceptional reasoning depth
- Catches subtle bugs other models miss
- More thorough explanations
- $15/MTok input, $75/MTok output (5x cost of Sonnet)
Real example:
# Use Opus for critical code review
claude --model claude-opus-4-1
> "Review this payment processing module for security vulnerabilities, race conditions, and edge cases. Be thorough."
Opus provides analysis that would take a senior developer hours. It's expensive but worth it for mission-critical code.
Claude Haiku 4.5 (Speed and Scale)
When to use:
- Simple, repetitive tasks
- Real-time interactive coding
- High-volume operations
- Free-tier applications
- Quick questions and clarifications
Performance:
- 4-5x faster than Sonnet
- Near-frontier intelligence at 1/3 the cost
- Excellent for scripting and automation
- $1/MTok input, $5/MTok output
Real example:
# Use Haiku for quick tasks
claude --model claude-haiku-4-5
> "Add error handling to all functions in utils.js"
Haiku completes this in seconds. Perfect for tasks that don't require deep reasoning.
Model Selection Strategy
Here's my workflow for choosing models:
1. Start with Haiku for simple tasks (formatting, adding types, quick fixes)
2. Switch to Sonnet when you need multi-file reasoning or complex logic
3. Use Opus for critical decisions, architecture, and deep debugging
4. Return to Haiku for implementation of planned changes
# Interactive model switching
> /model
# Select from list or specify directly
> /model sonnet # Quick switch to Sonnet 4.5
> /model opus # Switch to Opus 4.1
> /model haiku # Switch to Haiku 4.5
CLAUDE.md: Your Project's Brain
The CLAUDE.md file is where Claude learns your project. It's automatically loaded into every conversation, giving Claude persistent knowledge without consuming conversation context.
Critical Rules
1. Keep it under 100-150 lines – Every line costs context tokens
2. Update it frequently – Treat it like living documentation
3. Be specific, not comprehensive – Patterns over explanations
4. Use hierarchy – Main file + subdirectory files for focus
Essential CLAUDE.md Structure
# Project Context for [Your Project]
## Architecture
- React 18 frontend with Vite
- Node.js/Express backend
- PostgreSQL database
- Redis for caching
## Key Commands
```bash
npm run dev # Start dev server (port 3000)
npm run test # Run tests with vitest
npm run build # Production build
npm run db:migrate # Run database migrations
Code Patterns
API Routes
Always use this error handling pattern:
try {
const result = await operation();
res.json({ success: true, data: result });
} catch (error) {
logger.error('Operation failed:', error);
res.status(500).json({ success: false, error: error.message });
}
Component Structure
- Use TypeScript strict mode
- Props interface named
{ComponentName}Props - Export default at bottom
- Use custom hooks from
src/hooks/
Testing Requirements
- Unit test for every utility function
- Integration test for every API route
- E2E test for critical user flows
- Minimum 80% coverage
Don'ts
- Never commit
.envfiles - Don't use
anytype in TypeScript - Avoid inline styles (use Tailwind classes)
- Don't skip error boundaries in React components
### Hierarchical CLAUDE.md Files
Claude reads CLAUDE.md files in this order:
1. `~/.claude/CLAUDE.md` (global user preferences)
2. `~/projects/CLAUDE.md` (organization standards)
3. `~/projects/your-app/CLAUDE.md` (project-specific)
4. `~/projects/your-app/backend/CLAUDE.md` (subdirectory-specific)
Most specific wins. Use this to provide focused context:
**Backend CLAUDE.md:**
```markdown
# Backend Patterns
## Database Access
Always use connection pooling:
```javascript
const pool = require('./db/pool');
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
Authentication
JWT tokens expire in 15 minutes
Refresh tokens expire in 7 days
Always validate on both edge and API layer
**Frontend CLAUDE.md:**
```markdown
# Frontend Patterns
## State Management
Use Zustand for global state:
```javascript
const useStore = create((set) => ({
user: null,
setUser: (user) => set({ user })
}));
API Calls
Always use the centralized API client:
import api from '@/lib/api';
const data = await api.get('/users/me');
## MCP Servers: Connect Claude to External Tools
Model Context Protocol (MCP) servers extend Claude's capabilities by connecting it to external tools and services.
### Essential MCP Servers
#### GitHub MCP Server
```bash
# Add GitHub integration
claude mcp add --transport http github --scope user
# In Claude session, authenticate
> /mcp
# Select GitHub, follow OAuth flow
# Now use GitHub naturally
> "Review PR #456 and suggest improvements"
> "Create an issue for the bug we just found"
> "List all open PRs in the repo"
#### File System MCP Server
# Add filesystem access beyond project root
claude mcp add --transport stdio filesystem --scope project \
-- npx -y @modelcontextprotocol/server-filesystem /path/to/docs
# Access external documentation
> "Read the API docs from /docs/api-reference.md"
#### Database MCP Server
# Add PostgreSQL access
claude mcp add --transport stdio postgres --scope project \
--env DATABASE_URL=postgresql://user:pass@localhost:5432/db \
-- npx -y @modelcontextprotocol/server-postgres
# Query database directly
> "Show me all users created in the last 7 days"
> "What's the average order value this month?"
MCP Configuration Best Practices
Use scopes wisely:
--scope user– Available across all projects (GitHub, Slack)--scope project– Project-specific, tracked in.mcp.json(database, APIs)--scope local– Just you, gitignored (personal tokens, credentials)
List and manage servers:
# View configured servers
claude mcp list
# Remove a server
claude mcp remove github
# Test server connection
claude mcp get github
MCP Server Configuration File
For complex setups, edit directly: ~/.claude/claude_desktop_config.json
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://mcp.github.com"
},
"postgres": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://localhost:5432/mydb"
}
},
"slack": {
"type": "http",
"url": "https://mcp.slack.com",
"auth": {
"type": "oauth"
}
}
}
}
Hooks: Automate Your Workflow
Hooks are event-driven triggers that run at specific points in Claude's workflow. They're incredibly powerful for enforcing code quality and automating repetitive tasks.
Hook Types
- PreToolUse – Runs before tool execution (can block)
- PostToolUse – Runs after tool execution
- UserPromptSubmit – Before processing user input
- Stop – When Claude finishes responding
- SubagentStop – When subagent tasks complete
Real-World Hook Examples
#### Auto-Format Python Code
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write(.*.py)",
"hooks": [
{
"type": "command",
"command": "python -m black \"$CLAUDE_FILE_PATHS\""
}
]
}
]
}
}
Every time Claude writes a Python file, Black auto-formats it. No manual formatting needed.
#### Run Tests After Code Changes
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write(src/.*\\.ts)",
"hooks": [
{
"type": "command",
"command": "npm run test -- \"$CLAUDE_FILE_PATHS\""
}
]
}
]
}
}
Immediate feedback on test failures. Catches regressions instantly.
#### Protect Sensitive Files
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/protect-secrets.sh"
}
]
}
]
}
}
protect-secrets.sh:
#!/bin/bash
json=$(cat)
file_path=$(echo "$json" | jq -r '.file_path // empty')
if [[ "$file_path" =~ \\.env || "$file_path" =~ production\\.config ]]; then
echo "Error: Cannot edit sensitive files"
exit 1 # Block the action
fi
exit 0 # Allow the action
#### Git Commit After Each Change
{
"hooks": {
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "git add -A && git commit -m \"Claude: $(date +%Y-%m-%d_%H-%M-%S)\""
}
]
}
]
}
}
Automatic version control for every Claude session. Never lose work.
Hook Environment Variables
Your hooks receive these variables:
$CLAUDE_PROJECT_DIR– Project root$CLAUDE_FILE_PATHS– Space-separated file paths$CLAUDE_TOOL_OUTPUT– Tool output (PostToolUse only)$CLAUDE_NOTIFICATION– Notification message
Hook Exit Codes
Control Claude's behavior with exit codes:
exit 0– Success, continue normallyexit 1– Error, show error message to userexit 2– Block, prevent the action from happening
Interactive Hook Configuration
# Configure hooks interactively
> /hooks
# Select hook type: PostToolUse
# Add matcher: Write(.*.py)
# Add command: black "$CLAUDE_FILE_PATHS"
Claude generates the JSON configuration for you.
Context Management: The Most Critical Skill
Claude's context window is finite. Managing it well is the difference between productive sessions and confused AI.
The /clear Command (Use It Frequently)
Rule: Clear context every 1-3 messages when completing a distinct task.
# Complete a feature
> "Add user authentication to the API"
# Claude implements it
# CLEAR before moving to next task
> /clear
# Start fresh
> "Now add password reset functionality"
Why this matters: Each message adds to context. Old context confuses Claude about what you're currently working on. Fresh context = focused Claude.
Checkpointing and Rewind
Claude automatically creates checkpoints before each code change. This is your safety net.
Rewind when:
- Claude went down the wrong path
- You want to try a different approach
- Changes broke something
- You need to undo the last 3-5 steps
# Quick rewind: Press ESC twice
ESC + ESC
# Or use command
> /rewind
# Choose what to restore:
# 1. Code only (keep conversation)
# 2. Conversation only (keep code)
# 3. Both code and conversation
Real scenario:
> "Refactor the database layer to use Prisma"
# Claude starts making changes
# After 3 files, you realize this is too big
ESC + ESC
# Restore both code and conversation
# Back to clean state
> "Let's start smaller. Just migrate the User model to Prisma first"
# Claude takes incremental approach
Checkpoints persist across sessions for 30 days. You can resume yesterday's work and still rewind to any point.
The /compact Command (Use Sparingly)
When you absolutely cannot clear context but it's getting full:
> /compact Focus on preserving our authentication implementation and database schema decisions
Claude compresses the conversation while keeping critical context. However, you lose control over what's kept. Prefer /clear and well-structured CLAUDE.md files.
Disable Auto-Compact
Auto-compact sounds good in theory but often adds irrelevant old context.
> /config
# Find "Auto-compact conversations"
# Toggle OFF
Better alternatives:
- Comprehensive
CLAUDE.mdfiles - Custom slash commands
- Plan files for complex tasks
Custom Slash Commands
Create reusable workflows that you can trigger with a simple command.
Creating Commands
Personal commands (all projects):
mkdir -p ~/.claude/commands
# Create security review command
cat > ~/.claude/commands/security.md << 'EOF'
Review this code for security vulnerabilities:
- SQL injection risks
- XSS vulnerabilities
- Authentication bypasses
- Race conditions
- Input validation issues
Provide specific code examples of fixes.
EOF
Project commands:
mkdir -p .claude/commands
# Create fix-issue command with arguments
cat > .claude/commands/fix-issue.md << 'EOF'
Fix issue #$ARGUMENTS following our coding standards:
1. Read the issue from GitHub
2. Write failing tests first
3. Implement the fix
4. Ensure all tests pass
5. Update documentation if needed
EOF
Using Commands
# Personal command
> /security
# Project command with arguments
> /fix-issue 123
# Claude reads GitHub issue #123 and follows the workflow
Advanced Command Examples
API endpoint generator:
# .claude/commands/api-endpoint.md
Create a new API endpoint for $ARGUMENTS:
1. Add route in `src/routes/`
2. Create controller in `src/controllers/`
3. Add validation schema using Zod
4. Write integration tests
5. Update API documentation
6. Add error handling per our pattern
Follow the patterns in CLAUDE.md for error handling and response format.
Component scaffolding:
# .claude/commands/react-component.md
Create a new React component named $ARGUMENTS:
1. Create `src/components/$ARGUMENTS.tsx`
2. Add TypeScript interface `${ARGUMENTS}Props`
3. Include error boundary
4. Add basic tests in `src/components/__tests__/`
5. Export from `src/components/index.ts`
6. Add Storybook story if UI component
Use Tailwind for styling. Follow our component patterns in CLAUDE.md.
Essential Slash Commands
Master these commands for maximum productivity:
/clear # Clear context (use frequently)
/rewind # Undo changes with checkpoint restore
/compact # Compress conversation (use rarely)
/model # Switch between Sonnet/Opus/Haiku
/usage # Check token usage and costs
/resume # Resume previous conversation
/mcp # Authenticate MCP servers
/hooks # Configure automation hooks
/config # Adjust Claude Code settings
/help # List all commands
Production Workflow: Real-World Examples
Feature Development Flow
# 1. Start fresh
> /clear
# 2. Create feature branch
> "Create a new branch called feature/user-profiles"
# 3. High-level planning (use Opus for architecture)
> /model opus
> "Plan the architecture for user profile feature. Include:
- Database schema changes
- API endpoints needed
- Frontend components
- Security considerations
"
# 4. Review plan, then implement (switch to Sonnet)
> /model sonnet
> "Implement the user profile backend following the plan"
# 5. Test as you go (Haiku for quick checks)
> /model haiku
> "Run tests and show me any failures"
# 6. Fix issues (Sonnet for complex fixes)
> /model sonnet
> "Fix the failing test in UserProfile.test.ts"
# 7. Final review (Opus for thoroughness)
> /model opus
> "Review all changes for security, performance, and code quality"
# 8. Commit
> "Commit these changes with a descriptive message"
Bug Fix Flow
# 1. Gather context
> "Show me the last 10 lines of the error log"
# 2. Reproduce (Haiku for speed)
> /model haiku
> "Run the test that's failing and show output"
# 3. Investigate (Sonnet for reasoning)
> /model sonnet
> "Analyze the error. Check related files and show me what's wrong"
# 4. Fix
> "Implement the fix and add a regression test"
# 5. Verify
> "Run all tests to ensure nothing else broke"
# 6. If tests pass
> "Create a hotfix branch and commit"
Code Review Flow
# 1. Get latest changes
> "Show me what changed in the last commit"
# 2. Comprehensive review (Opus for depth)
> /model opus
> "Review this commit for:
- Code quality and best practices
- Performance issues
- Security vulnerabilities
- Test coverage
- Documentation completeness
"
# 3. Create issues for findings
> "Create GitHub issues for each concern you found"
Status Line and Progress Visibility
Claude Code 2.0 improved status visibility significantly:
What you see during execution:
- Current tool being used
- Files being read/edited
- Commands being executed
- MCP servers being called
- Progress on multi-step tasks
Searchable prompt history:
# Press Ctrl+R (like bash reverse search)
Ctrl+R
# Type to search your previous prompts
# Press enter to reuse or edit
This is invaluable for repeating similar tasks across sessions.
Permission Management
Control what Claude can and cannot do:
{
"permissions": {
"allowedTools": [
"Read",
"Write(src/)",
"Bash(git )",
"Bash(npm )"
],
"deny": [
"Read(.env)",
"Read(.env.)",
"Write(production.config.)",
"Bash(rm -rf)",
"Bash(sudo )"
]
}
}
Best practices:
- Whitelist allowed commands, not just blacklist dangerous ones
- Restrict file system access to project directories
- Block modification of sensitive config files
- Disable destructive shell commands
- Use
askfor operations requiring confirmation
Common Pitfalls and Solutions
1. Context Bloat
Problem: Conversations become confused after 10+ messages
Solution:
- Clear context every 1-3 distinct tasks
- Use
CLAUDE.mdfor permanent knowledge - Create custom commands for repetitive workflows
- Use
/rewindinstead of explaining what went wrong
2. Wrong Model for the Job
Problem: Haiku makes architectural mistakes, Opus is too slow for simple tasks
Solution:
- Start with Haiku for simple tasks
- Switch to Sonnet for multi-file logic
- Use Opus only for critical decisions
- Check
/usageregularly to monitor costs
3. Unclear Instructions
Problem: Claude produces code that's close but not quite right
Solution:
- Be specific about patterns in
CLAUDE.md - Reference existing code: "Follow the pattern in
UserController.ts" - Provide examples in your prompts
- Use Plan Mode (Shift+Tab twice) to review before execution
4. Losing Track of Changes
Problem: Hard to know what Claude changed
Solution:
- Always work in a feature branch
- Use checkpoints liberally
- Set up a
PostToolUsehook for auto-commits - Review diffs before merging
5. MCP Server Issues
Problem: MCP servers fail authentication or connection
Solution:
# Re-authenticate
> /mcp
# Select the server and follow prompts
# Check server status
claude mcp list
# Remove and re-add
claude mcp remove <server>
claude mcp add <server> --scope user
Advanced Tips for Pro Users
1. Plan Mode
Press Shift+Tab twice to activate Plan Mode. Claude shows you what it plans to do before doing it.
Perfect for:
- Large refactors
- Multi-file changes
- When you want review control
- Learning Claude's thought process
2. Git Integration
Create a hook that automatically creates semantic commits:
# .claude/hooks/smart-commit.sh
#!/bin/bash
# Get changed files
files=$(git diff --name-only)
# Generate commit message using AI
commit_msg=$(claude -p "Generate a conventional commit message for these changes: $files")
# Commit with generated message
git add -A
git commit -m "$commit_msg"
3. Multi-Agent Workflows
Use subagents for complex tasks:
> "Create a subagent to handle database migrations while you work on the API"
# Main agent continues API work
# Subagent handles DB changes independently
4. Custom Tool Definitions
Define project-specific tools in your configuration:
{
"tools": {
"deploy": {
"command": "./scripts/deploy.sh",
"description": "Deploy to staging environment"
},
"seed-db": {
"command": "npm run db:seed",
"description": "Seed database with test data"
}
}
}
Now Claude can use these tools naturally:
> "Deploy the changes to staging and seed the database"
5. Output Format Control
For programmatic use:
# JSON output
claude -p "What's in package.json?" --output-format json
# Stream JSON for real-time processing
claude -p "Analyze codebase" --output-format stream-json
Key Takeaways
Start here:
1. Install Claude Code and run /init in your project
2. Create a focused CLAUDE.md under 100 lines
3. Use /clear frequently (every 1-3 tasks)
4. Start with Haiku, switch to Sonnet for complexity
Level up:
5. Add GitHub MCP server for PR reviews
6. Configure PostToolUse hooks for auto-formatting
7. Create custom commands for common workflows
8. Use checkpoints fearlessly with /rewind
Go pro:
9. Set up hierarchical CLAUDE.md files
10. Configure permissions to restrict dangerous operations
11. Use Plan Mode for complex changes
12. Switch models strategically based on task complexity
Remember:
- Sonnet 4.5 for most coding work
- Opus 4.1 for critical decisions and deep review
- Haiku 4.5 for speed and simple tasks
- Clear context religiously
- Trust checkpoints, use rewind
Claude Code transforms how you write software. Master these patterns and you'll ship faster, with fewer bugs, and more confidence than ever before.
The future of development is conversational. Welcome to the vibe.