The Complete Claude Code Handbook

A comprehensive guide to Claude Code - from basics to advanced features, best practices, and power user tips.

1. What is Claude Code?

The Elevator Pitch

Claude Code is an agentic AI coding assistant that lives in your terminal (or IDE). Unlike chatbots that just suggest code, Claude Code can:

  • Read your entire codebase
  • Write and edit files directly
  • Run terminal commands
  • Create commits and PRs
  • Debug by reading errors and fixing them

How It's Different from Copilot & Cursor

All three now offer chat, autocomplete, multi-file edits, and agentic capabilities. Here's where they actually differ:

AspectGitHub CopilotCursorClaude Code
InterfaceVS Code extensionFork of VS CodeTerminal-first + IDE extensions
StrengthsGitHub integration, polished UXFast inline edits, ComposerDeep reasoning, complex refactors
Project Rules.github/copilot-instructions.md.cursorrulesCLAUDE.md + persistent memory
External ToolsGitHub ecosystemMCP supportMCP protocol (DBs, APIs, custom)
Model OptionsGPT-4, Claude, GeminiMultiple (GPT, Claude, etc.)Claude only (Sonnet, Opus, Haiku)
Pricing$10-39/mo subscription$20/mo subscriptionPay-per-use (API) or Max plan
Best ForEveryday coding in VS CodeQuick iterations, visual editsLarge refactors, autonomous tasks

The Mental Model

Think of Claude Code as a junior developer with perfect memory who:

  • Can read every file instantly
  • Never forgets project conventions
  • Always asks before making changes
  • Works 24/7 without getting tired
  • Needs clear instructions to do their best work

2. Installation & Setup

Installation Methods

Method 1: Native Install (Recommended)

# macOS / Linux / WSL
curl -fsSL https://claude.ai/install.sh | bash

Method 2: Homebrew (macOS)

brew install --cask claude-code

Method 3: NPM (requires Node.js 18+)

npm install -g @anthropic-ai/claude-code

Method 4: Manual Download

Download from: https://claude.ai/download

First Run & Authentication

# Start Claude Code
claude

# You'll be prompted to login:
# Option 1: Claude.ai (subscription - recommended for individuals)
# Option 2: API Key (pay-per-use - recommended for teams/enterprise)

Verify Installation

claude --version
claude --help

Configuration Locations

FilePurpose
~/.claude/settings.jsonUser settings (all projects)
~/.claude/CLAUDE.mdPersonal memory (all projects)
~/.claude/commands/Personal slash commands
~/.claude/skills/Personal skills (hot-reload enabled)
.claude/settings.jsonProject settings (shared)
./CLAUDE.mdProject memory (shared)

Useful Settings

{
  "language": "english",           // Response language (english, japanese, etc.)
  "respectGitignore": true,        // Hide gitignored files from @-mentions
  "preferredNotifChannel": "terminal_bell"  // Sound on task completion
}

3. CLI vs VS Code Extension

Feature Comparison

FeatureCLIVS Code Extension
InterfaceTerminal textGUI panel
File diffsInline text diffVisual side-by-side
Approve changesType y/nClick buttons
Multi-line inputShift+EnterRegular Enter
File referencesType @file.jsDrag & drop or Alt+K
Multiple sessionsMultiple terminalsTabs (Cmd+Shift+Esc)
Background tasksFull supportLimited
Scripting/CIFull supportNot available
Remote/SSHFull supportNeeds Remote extension

CLI Advantages

  • Speed: Faster startup, no GUI overhead
  • Scripting: Can pipe input/output, use in scripts
  • CI/CD: Integrate into build pipelines
  • SSH: Works on remote servers
  • Power users: Full keyboard workflow
  • Clickable paths: File paths in output are clickable (iTerm, Kitty, WezTerm)
  • Shift+Enter: Works out of the box in iTerm2, WezTerm, Ghostty, Kitty

Extension Advantages

  • Visual diffs: Easier to review changes
  • Click to approve: Less typing
  • IDE integration: Don't leave your editor
  • File navigation: Click to jump to files
  • Beginners: Gentler learning curve

Extension-Specific Shortcuts

ShortcutAction
Cmd+Shift+EscNew Claude tab
Alt+KInsert @-mention with line numbers
Click file in chatOpen in editor
Drag file to panelAdd as context

CLI-Specific Features

FeatureHow to use
One-shot modeclaude "fix the bug"
Continue sessionclaude -c
Resume by nameclaude -r "session-name"
Print mode (no interaction)claude -p "query"
Pipe inputcat file.js | claude "review this"
Background tasks> !long-running-command

4. Core Concepts & How It Works

The Agentic Loop

Claude Code operates in a continuous loop:

  1. User Prompt - You describe what you want
  2. Analysis - Claude analyzes the request and plans an approach
  3. Tool Selection - Determines which tools to use (Read, Edit, Bash, etc.)
  4. Permission Check - Asks for approval (or uses pre-approved settings)
  5. Execution - Runs the tool and observes results
  6. Iteration - Decides next action, loops until complete

Available Tools

File Operations

ToolPurposeExample
ReadRead file contentsRead src/app.js
WriteCreate new fileWrite index.html
EditModify existing fileChange function name
GlobFind files by patternFind all *.tsx files
GrepSearch file contentsFind "TODO" comments

System Operations

ToolPurposeExample
BashRun terminal commandsnpm install, git status
TaskDelegate to subagentComplex multi-step research

Web Operations

ToolPurposeExample
WebSearchSearch the internetFind documentation
WebFetchFetch URL contentRead API docs

Code Intelligence (LSP)

ToolPurposeExample
GoToDefinitionJump to symbol definitionFind where function is defined
FindReferencesFind all usagesWhere is this function called?
HoverGet type/documentationWhat type is this variable?

Context Operations

ToolPurposeExample
TodoWriteTrack task progressMulti-step implementation
AskUserQuestionGet user inputClarify requirements

How Context Works

The context window contains everything Claude can "see":

  • System Prompt - Claude Code instructions and tool definitions
  • CLAUDE.md - Auto-loaded project context and coding standards
  • Conversation History - Your messages, Claude's responses, tool calls & results
  • File Contents - Files you've read stay in context until compacted

Token Economics

ModelInput CostOutput CostContext Window
Claude Sonnet$3/1M tokens$15/1M tokens200K tokens
Claude Opus$15/1M tokens$75/1M tokens200K tokens
Claude Haiku$0.25/1M tokens$1.25/1M tokens200K tokens

Rule of thumb: 1 token ≈ 4 characters or 0.75 words


5. Essential Commands Reference

CLI Arguments

# Start interactive session
claude

# One-shot task (exits after completion)
claude "add error handling to login function"

# Print mode (outputs response, no interaction)
claude -p "explain this error: <paste error>"

# Continue last conversation
claude -c

# Resume named session
claude -r "feature-auth"

# Start with specific model
claude --model opus

# Start in plan mode (read-only)
claude --mode plan

# Use specific permission mode
claude --permission-mode auto-accept

Slash Commands

Navigation & Session

CommandDescription
/helpShow all commands
/clearClear conversation history
/resume [id]Resume previous session
/rename <name>Name current session
/export [file]Export conversation
/quit or /exitExit Claude Code

Configuration

CommandDescription
/configOpen settings UI
/modelChange AI model
/loginSwitch account
/logoutSign out
/statusShow version, model, connectivity

Project Features

CommandDescription
/initCreate CLAUDE.md for project
/memoryEdit project memory
/agentsManage subagents
/mcpManage MCP servers
/hooksConfigure automation hooks

Context Management

CommandDescription
/contextVisualize token usage
/costShow session costs
/compact [focus]Compress context with optional focus

Special Modes

CommandDescription
/vimEnable vim-style editing
/themeCustomize syntax highlighting (Ctrl+T to toggle)
/doctorCheck installation health
/bugReport a bug
/release-notesView latest release notes

Vim Mode Motions

When /vim is enabled, these motions work:

  • Movement: h, j, k, l, w, b, e, 0, $, gg, G
  • Editing: i, a, o, O, x, dd, yy, p, u, J
  • Text objects: iw, aw, i", a", i(, a(
  • Find: f, F, t, T, ;, ,
  • Indent: >>, <<

Remote Sessions (Max Subscribers)

CommandDescription
/teleportMove session between local and web
/remote-envConfigure remote environment
/tasksView running background tasks

Keyboard Shortcuts

Universal

ShortcutAction
?Show all shortcuts
Ctrl+CCancel/interrupt
Ctrl+DExit
Ctrl+LClear screen

Input

ShortcutAction
Shift+EnterMulti-line input
TabAutocomplete
Ctrl+RReverse search history
/ Navigate history

Session

ShortcutAction
Shift+TabToggle permission mode (normal → auto-accept → plan)
Ctrl+BBackground current task (bash or agent)
Ctrl+OToggle verbose output
Ctrl+GOpen external editor for complex prompts
Esc+EscRewind changes
Option+P (Mac)Switch model

Real-time Steering

ShortcutAction
Type while Claude worksAdd guidance mid-task
Ctrl+CInterrupt and redirect

6. CLAUDE.md - Project Memory

What It Is

A markdown file that Claude automatically loads when starting a session. Think of it as a "briefing document" that gives Claude context about your project.

Why It Matters

  • Consistency: Claude follows the same rules every session
  • Team alignment: Everyone shares the same context
  • Efficiency: No need to repeat project info each time
  • Quality: Better outputs when Claude understands conventions

File Locations & Loading Order

Loading priority (later overrides earlier):

1. Enterprise policy (if set)
   └── /Library/Application Support/ClaudeCode/CLAUDE.md (macOS)
   └── /etc/claude-code/CLAUDE.md (Linux)

2. User defaults (your preferences across all projects)
   └── ~/.claude/CLAUDE.md

3. Project shared (committed to git, team-wide)
   └── ./CLAUDE.md
   └── ./.claude/CLAUDE.md

4. Project local (your overrides, gitignored)
   └── ./CLAUDE.local.md

Template: Comprehensive CLAUDE.md

# ProjectName

## Overview
Brief description of what this project does and its purpose.

## Tech Stack
- **Frontend**: React 18 + TypeScript + Vite
- **Backend**: Node.js + Express + TypeScript
- **Database**: PostgreSQL with Prisma ORM
- **Testing**: Jest + React Testing Library
- **CI/CD**: GitHub Actions

## Project Structure
src/
├── components/     # React components
├── hooks/          # Custom React hooks
├── services/       # API services
├── utils/          # Helper functions
├── types/          # TypeScript types
└── __tests__/      # Test files

## Commands
- **Dev server**: npm run dev
- **Build**: npm run build
- **Test**: npm test
- **Lint**: npm run lint
- **Type check**: npm run typecheck

## Coding Standards

### TypeScript
- Use strict mode
- Prefer interface over type for objects
- Always define return types for functions
- Use unknown instead of any

### React
- Use functional components with hooks
- Keep components under 200 lines
- Extract logic to custom hooks
- Use React Query for data fetching

### Naming Conventions
- Components: PascalCase (UserProfile.tsx)
- Hooks: camelCase with use prefix (useAuth.ts)
- Utils: camelCase (formatDate.ts)
- Types: PascalCase with suffix (UserType, ApiResponse)

Advanced Features

Importing Other Files

# Reference other documentation
@docs/api-reference.md
@docs/coding-standards.md
@../shared/common-patterns.md

Path-Specific Rules

Create .claude/rules/ directory with targeted rules:

.claude/rules/api.md:

---
paths: src/api/**/*.ts
---

# API Development Rules
- All endpoints must have request/response types
- Use middleware for authentication
- Always validate input with Zod
- Return consistent error format

Best Practices

  1. Keep it concise: Under 500 lines (use imports for more)
  2. Update regularly: Evolve with the project
  3. Be specific: Vague rules lead to vague outputs
  4. Include examples: Show, don't just tell
  5. Document the "why": Help Claude understand reasoning

7. Custom Slash Commands

What They Are

Reusable prompt templates triggered with /command-name. Like aliases for complex prompts.

Why Use Them

  • Consistency: Same process every time
  • Efficiency: Save typing for common tasks
  • Team sharing: Standardize workflows
  • Best practices: Encode expertise

File Locations

Personal commands (all your projects):
~/.claude/commands/command-name.md

Project commands (shared with team):
.claude/commands/command-name.md

Command Anatomy

---
description: Brief description shown in /help
argument-hint: [optional-arg]
allowed-tools: Bash(git:*), Read, Grep, Glob
---

# Command instructions

Your detailed instructions here.

Use $ARGUMENTS for all arguments passed.
Use $1, $2, etc. for specific arguments.

Include file content with @path/to/file.js
Execute commands with !git status

Example Commands

/review - Code Review

---
description: Review code for quality, security, and best practices
allowed-tools: Read, Grep, Glob, Bash(git:*)
---

# Code Review

Review the current changes for:

## 1. Code Quality
- Readability and clarity
- DRY principles
- Proper error handling
- Edge cases covered

## 2. Security (OWASP Top 10)
- SQL injection
- XSS vulnerabilities
- Hardcoded secrets
- Input validation

## 3. Performance
- Unnecessary loops
- Memory leaks
- N+1 queries
- Expensive operations

Current staged changes:
!git diff --staged

Provide feedback organized by severity:
- **Critical** - must fix before merge
- **High** - should fix
- **Medium** - consider fixing
- **Low** - suggestion

/commit - Smart Commit

---
description: Create a well-formatted commit with conventional format
allowed-tools: Bash(git:*)
---

# Smart Commit

1. Check current changes:
!git status
!git diff --staged

2. If nothing staged, stage all changes:
!git add -A

3. Analyze changes and create commit message following Conventional Commits:
   - feat: New feature
   - fix: Bug fix
   - docs: Documentation
   - style: Formatting
   - refactor: Code restructure
   - test: Tests
   - chore: Maintenance

Format:
type(scope): brief description

- Bullet point details
- What changed and why

Command Syntax Reference

SyntaxPurposeExample
$ARGUMENTSAll arguments/review $ARGUMENTS
$1, $2Specific args$1 = first word
@file.jsInclude file@src/config.js
!cmdRun command!git status
allowed-toolsRestrict toolsBash(git:*), Read

8. MCP Servers - External Integrations

What MCP Is

Model Context Protocol (MCP) is an open standard that lets Claude connect to external tools, databases, and APIs. Think of it as "plugins" for Claude Code.

Why Use MCP

  • Direct database access: Query your DB without copy-pasting
  • GitHub integration: Manage issues, PRs from Claude
  • Third-party tools: Slack, Jira, monitoring systems
  • Custom tools: Build your own integrations

Setting Up MCP Servers

Method 1: CLI Commands

# Add HTTP server (GitHub)
claude mcp add github --transport http https://api.githubcopilot.com/mcp/

# Add stdio server (filesystem)
claude mcp add filesystem -- npx -y @anthropic-ai/mcp-filesystem ./docs

# Add with specific scope
claude mcp add --scope project db -- npx -y @bytebase/dbhub \
  --dsn "postgresql://user:pass@localhost:5432/mydb"

# List servers
claude mcp list

# Remove server
claude mcp remove github

# Authenticate with OAuth
/mcp auth github

Method 2: Configuration File

Project config (.mcp.json - committed to git):

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/"
    },
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@anthropic-ai/mcp-filesystem", "./docs", "./specs"]
    }
  }
}
ServerPurposeInstall
GitHubIssues, PRs, reposBuilt-in
FilesystemEnhanced file access@anthropic-ai/mcp-filesystem
DatabaseSQL queries@bytebase/dbhub
MemoryPersistent knowledge@anthropic-ai/mcp-memory
SentryError monitoringhttps://mcp.sentry.dev
PuppeteerBrowser automation@anthropic-ai/mcp-puppeteer

Usage Examples

Query Database

> What are the top 10 customers by revenue?
(Claude uses db MCP to run SQL query)

> Show me users who signed up last week but haven't made a purchase
(Complex query handled automatically)

GitHub Integration

> List all open issues labeled "bug"
> Create a PR from current branch to main
> Add a comment to issue #42

Security Considerations

  1. Use read-only credentials for databases
  2. Scope servers appropriately (project vs user)
  3. Don't commit secrets - use environment variables
  4. Review server permissions before enabling

9. Hooks - Automation

What Hooks Are

Scripts that run automatically before/after Claude takes actions. Like git hooks, but for Claude Code.

Why Use Hooks

  • Auto-format: Run Prettier after edits
  • Security: Block changes to sensitive files
  • Validation: Check code before commits
  • Logging: Audit all actions
  • Notifications: Alert on completions

Hook Events

EventWhenCan Block?
PreToolUseBefore any tool runsYes (exit 2)
PostToolUseAfter tool completesNo
NotificationClaude sends notificationNo
StopClaude finishes taskNo
SubagentStopSubagent completesNo
SessionStartSession beginsNo
SessionEndSession endsNo

Setting Up Hooks

Method 1: Interactive Setup

> /hooks
# Select event type
# Define matcher (tool pattern)
# Enter command to run
# Choose save location

Method 2: Configuration File

.claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "scripts/pre-edit-check.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
          }
        ]
      }
    ]
  }
}

Example Hooks

Auto-Format on Edit

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{
          "type": "command",
          "command": "if [[ \"$CLAUDE_FILE_PATH\" =~ \\.(js|ts|jsx|tsx)$ ]]; then npx prettier --write \"$CLAUDE_FILE_PATH\"; fi"
        }]
      }
    ]
  }
}

Block Sensitive Files

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|Read",
        "hooks": [{
          "type": "command",
          "command": "if [[ \"$CLAUDE_FILE_PATH\" =~ (\\.env|secrets|credentials) ]]; then echo 'Blocked: sensitive file' && exit 2; fi"
        }]
      }
    ]
  }
}

Environment Variables in Hooks

VariableDescription
CLAUDE_TOOL_NAMEName of tool being used
CLAUDE_FILE_PATHFile being operated on
CLAUDE_TOOL_INPUTJSON of tool input
CLAUDE_TOOL_OUTPUTJSON of tool output (PostToolUse)

Exit Codes

CodeMeaning
0Success, continue
1Error, continue anyway
2Block action (PreToolUse only)

10. Subagents - Specialized Helpers

What Subagents Are

Specialized AI assistants with their own personality, tools, and context. Like having expert consultants on call.

Why Use Subagents

  • Specialization: Dedicated reviewer, debugger, etc.
  • Isolation: Separate context windows
  • Efficiency: Use cheaper models for simple tasks
  • Consistency: Same approach every time

Built-in Subagents

AgentModelPurpose
ExploreHaikuFast codebase search
PlanSonnetDesign and planning
GeneralSonnetComplex multi-step tasks

Creating Custom Subagents

Location

Project agents (shared): .claude/agents/agent-name/AGENT.md
User agents (personal): ~/.claude/agents/agent-name/AGENT.md

Agent Definition Structure

---
name: agent-name
description: When to use this agent. Be specific so Claude knows when to invoke it.
tools: Read, Edit, Grep, Glob, Bash
model: sonnet  # or haiku, opus
---

# Agent Personality

You are a [role] who specializes in [domain].

## When Invoked

1. First, do this
2. Then, do that
3. Finally, report findings

## Guidelines

- Always do X
- Never do Y
- Consider Z

## Output Format

Provide results as:
- Category 1: findings
- Category 2: findings

Example: Security Auditor Agent

.claude/agents/security-auditor/AGENT.md:

---
name: security-auditor
description: Security vulnerability scanner. Use after writing authentication, API endpoints, or user input handling code.
tools: Read, Grep, Glob
model: sonnet
---

# Security Auditor

You are a senior security engineer specializing in application security.

## Scan Process

1. **Identify scope**: Find files matching the request
2. **Static analysis**: Search for vulnerability patterns
3. **Logic review**: Understand data flow
4. **Report findings**: Organized by severity

## Output Format

### Critical
Must fix immediately - active exploit risk

### High
Should fix soon - significant risk

### Medium
Fix when possible - moderate risk

### Low
Suggestions - hardening recommendations

Managing Agents

# List available agents
/agents

# Create new agent interactively
/agents
# Select "Create New"

# Agents are invoked automatically when relevant
# Or explicitly:
> Use the security-auditor to check the auth module

11. Skills - Knowledge Modules

What Skills Are

Specialized knowledge modules that Claude automatically applies when relevant topics come up. Like giving Claude expertise on demand.

Hot-Reload: Skills in ~/.claude/skills or .claude/skills are instantly available without restart - just save and they're live.

Difference: Skills vs Subagents

AspectSkillsSubagents
ContextLoaded into main contextSeparate context window
When triggeredTopic matches descriptionTask delegation
Best forKnowledge, patterns, referencesComplex multi-step tasks
CostAdds to main token usageSeparate token usage

Creating Skills

Location

Project skills: .claude/skills/skill-name/SKILL.md
User skills: ~/.claude/skills/skill-name/SKILL.md

Skill Structure

---
name: skill-name
description: Detailed description of when this skill applies. Be specific!
allowed-tools: Read, Write, Edit
context: fork          # Optional: run in isolated subagent context
agent: sonnet          # Optional: specify agent/model for execution
---

# Skill Title

## Quick Reference
Essential information for immediate use.

## Detailed Guide
More comprehensive information.

## Examples
Code examples and patterns.

## Common Pitfalls
What to avoid.

Multi-File Skills

For complex skills, use a directory structure:

.claude/skills/deployment/
├── SKILL.md              # Entry point (under 500 lines)
├── kubernetes.md         # K8s specifics
├── docker.md             # Docker patterns
├── ci-cd.md              # Pipeline configs
└── scripts/
    ├── healthcheck.sh    # Utility scripts
    └── deploy.sh

Reference in SKILL.md:

For Kubernetes details, see [kubernetes.md](kubernetes.md)
For Docker patterns, see [docker.md](docker.md)

12. Permissions & Security

Permission Model

Claude Code always asks permission before taking actions. You control:

  • What tools can run automatically
  • What files can be accessed
  • What commands can execute

Permission Modes

ModeBehaviorBest For
NormalAsks for everythingLearning, sensitive work
Auto-AcceptAccepts safe editsTrusted workflows
PlanRead-only, plans onlyAnalysis, review

Switching Modes

# At startup
claude --permission-mode auto-accept
claude --mode plan

# During session
Shift+Tab  # Cycle through modes

Settings Configuration

Project Settings (.claude/settings.json)

{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(npm run:*)",
      "Bash(npm test:*)",
      "Bash(git status)",
      "Bash(git diff:*)",
      "Bash(git log:*)"
    ],
    "deny": [
      "Bash(rm -rf:*)",
      "Bash(sudo:*)",
      "Bash(chmod:*)",
      "Read(.env)",
      "Read(.env.*)",
      "Read(**/secrets/**)",
      "Read(**/*.pem)",
      "Read(**/*credential*)",
      "WebFetch"
    ]
  },
  "env": {
    "NODE_ENV": "development"
  }
}

Permission Pattern Syntax

PatternMatches
ReadAll file reads
Read(.env)Only .env file
Read(**/*.ts)All TypeScript files
Bash(npm:*)Any npm command
Bash(git status)Exact command
WebFetch(docs.*)URLs starting with docs.

Security Best Practices

1. Protect Sensitive Files

{
  "permissions": {
    "deny": [
      "Read(.env*)",
      "Read(**/*secret*)",
      "Read(**/*credential*)",
      "Read(**/*.pem)",
      "Read(**/*.key)",
      "Edit(.env*)",
      "Write(.env*)"
    ]
  }
}

2. Restrict Dangerous Commands

{
  "permissions": {
    "deny": [
      "Bash(rm -rf:*)",
      "Bash(sudo:*)",
      "Bash(chmod 777:*)",
      "Bash(curl|wget:*)",
      "Bash(eval:*)",
      "Bash(*>/dev/*)",
      "Bash(*|sh)",
      "Bash(*|bash)"
    ]
  }
}

Enterprise Controls

Managed Settings

Enterprise admins can deploy settings that users cannot override:

macOS: /Library/Application Support/ClaudeCode/settings.json Linux: /etc/claude-code/settings.json


13. Context & Token Management

Understanding Context

What Uses Tokens

ItemToken Impact
System prompt~2-3K tokens (fixed)
CLAUDE.mdVaries by size
Each messageVaries
File contents readFull file size
Tool resultsVaries
Conversation historyGrows over time

Token Limits

ModelContext Window
Sonnet200K tokens
Opus200K tokens
Haiku200K tokens

Managing Context

View Usage

/context  # Visual breakdown
/cost     # Dollar amounts

Compact Context

/compact                    # General compaction
/compact "focus on auth"    # Keep auth-related context

Clear Context

/clear  # Start fresh

Resume Sessions

# Name current session
/rename "feature-auth"

# Resume later
claude -r "feature-auth"

# Or continue last session
claude -c

Cost Optimization Tips

1. Use Haiku for Simple Tasks

/model haiku
> What files handle authentication?
/model sonnet  # Switch back for complex work

2. Be Specific to Reduce Exploration

Bad: "Fix the bug" (Claude reads many files)
Good: "Fix the null check in src/auth/login.ts line 42"

3. Use Subagents

Subagents have separate context windows, so they don't bloat main context.

4. Compact Regularly

If session is long, /compact periodically.

5. Use Plan Mode for Analysis

Plan mode doesn't make changes, good for exploration without commitment.


14. Git Integration

Built-in Git Commands

Create Commits

> Create a commit for the changes I made
> Commit with message "Add user authentication"

Or use the command:

claude commit

Create Pull Requests

> Create a PR for this feature
> Create PR to main with title "Add OAuth support"

View Changes

> Show me what changed since yesterday
> What commits are on this branch?
> Show the diff for the last commit

Git Best Practices with Claude

  1. Review before committing: Always check what Claude staged
  2. Use conventional commits: Consistent format helps history
  3. Don't auto-push: Review locally first
  4. Branch strategy: Let Claude create feature branches

15. Real-World Use Cases

Case 1: Onboarding to New Codebase

Scenario: Join a new team, need to understand large codebase quickly.

claude

> Give me an overview of this codebase - what does it do and how is it structured?

> What are the main entry points?

> How does authentication work here?

> Walk me through a typical user request flow

> What are the key design patterns used?

> Where would I add a new API endpoint?

Pro tips:

  • Start broad, then narrow down
  • Ask about patterns and conventions
  • Request diagrams (Claude can describe architecture)

Case 2: Bug Fixing Workflow

Scenario: User reports bug, need to find and fix it.

claude

> Users report seeing "undefined" in the dashboard after login.
> Where should I look for this bug?

> [Claude identifies potential files]

> Read src/components/Dashboard.tsx and explain the data flow

> I see - the user object might be null. Can you fix the null check?

> Now write a test to prevent this regression

Pro tips:

  • Provide exact error messages
  • Include reproduction steps
  • Ask for tests with the fix

Case 3: Feature Development

Scenario: Add new feature from scratch.

claude --mode plan

> I need to add a "favorites" feature where users can save items.
> What's the implementation plan?

# Review plan, then exit plan mode

> Create the database migration for favorites table

> Add the API endpoints for add/remove/list favorites

> Create the React components for the favorites UI

> Write tests for the new feature

> Create a PR with all the changes

Pro tips:

  • Use plan mode first
  • Break into small steps
  • Test at each step

Case 4: Code Review

Scenario: Review PR before merge.

claude

> Review PR #123 for code quality and potential issues

# Or for local changes:
> Review my staged changes

/review  # If you have the custom command

Pro tips:

  • Create a /review command
  • Focus on specific concerns
  • Ask for security review separately

Case 5: Refactoring Legacy Code

Scenario: Modernize old code without breaking it.

claude

> I need to refactor src/legacy/utils.js to TypeScript.
> First, analyze what it does and what depends on it.

> What's the safest refactoring approach?

> Proceed with the refactoring, maintaining all existing behavior

> Run the tests to verify nothing broke

> Are there any type issues I should address?

Pro tips:

  • Understand before changing
  • Keep tests green throughout
  • Refactor in small steps

Case 6: Documentation Generation

Scenario: Create documentation for undocumented code.

claude

> Generate API documentation for all endpoints in src/api/

> Create a README for the authentication module

> Document the database schema

> Write JSDoc comments for the utility functions

Pro tips:

  • Be specific about format
  • Review generated docs
  • Keep docs close to code

16. Community Best Practices & Twitter Tips

From the Creator: Boris Cherny

Boris Cherny created Claude Code in September 2024. Here's how he uses it:

His setup is surprisingly vanilla. Claude Code works great out of the box, so he doesn't customize it much. There's no one correct way to use it - each person on the Claude Code team uses it differently.

Key principles:

  1. Almost always use Plan mode - Start by planning before making changes

  2. Give Claude a way to verify its work - This is the most important tip. If Claude has a feedback loop, it will 2-3x the quality of the final result. Verification looks different for each domain:

    • Running a bash command
    • Running a test suite
    • Testing in a browser or phone simulator
  3. Hold the same bar for human and Claude code - Use /code-review to automate most of code review

  4. Use PostToolUse hooks to format code - Claude usually generates well-formatted code, but hooks handle the last 10% to avoid CI errors

His results: In 30 days, Boris landed 259 PRs (497 commits, 40k lines added, 38k removed). Every line was written by Claude Code + Opus 4.5.

Top Tips from the Community

Prompt Engineering

1. Be specific about output format

Bad: "Write tests"
Good: "Write Jest tests using describe/it blocks, mock external deps, test happy path and error cases"

2. Provide context upfront

Good: "This is a Next.js 14 app using App Router, Prisma ORM, and TailwindCSS. I need to add a user settings page."

3. Ask for explanation first

Good: "Before making changes, explain your approach and what files you'll modify"

4. Use incremental approach

Good: "Let's do this step by step: 1. First, create the database model 2. Then, add the API endpoint 3. Finally, build the UI"

Workflow Tips

5. Name your sessions

/rename "auth-feature"
# Easy to resume later with claude -r "auth-feature"

6. Use plan mode for exploration

claude --mode plan
> Analyze the codebase and identify performance bottlenecks
# No changes made, just analysis

7. Check costs regularly

/cost
# Know what you're spending

8. Compact when context grows

/compact "keep focus on authentication code"

CLAUDE.md Tips

9. Include example commands

## Common Tasks
- Run dev server: `npm run dev`
- Run specific test: `npm test -- --grep "auth"`
- Generate migration: `npx prisma migrate dev --name <name>`

10. Document architectural decisions

## Architecture Decisions
- We use Redux Toolkit instead of Context for state (performance reasons)
- API routes are in /api, not /pages/api (App Router migration)
- We don't use ORMs for read-heavy queries (direct SQL in /db/queries)

Safety Tips

11. Review before approving

Take 5 seconds to scan the diff before hitting 'y'

12. Use hooks for guardrails

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "echo 'Running: $CLAUDE_TOOL_INPUT'"
      }]
    }]
  }
}

13. Git commit frequently

Make small commits so you can easily revert

Power User Tips

14. Pipe for quick answers

cat error.log | claude -p "explain this error"
git diff | claude -p "review these changes"

15. Use subagents for parallel work

> Use the Explore agent to find all database queries
> while I work on the API changes

16. Create team commands

# Everyone on team has same review process
.claude/commands/review.md
.claude/commands/deploy-checklist.md

Common Mistakes to Avoid

Mistake: Vague prompts

"Fix the code"  # Too vague

Better:

"Fix the null pointer exception in UserService.getUser()
when the user ID doesn't exist in the database"

Mistake: Approving blindly

y y y y y  # Dangerous

Better:

Read each diff, understand the change, then approve

Mistake: Huge single prompts

"Build me a complete e-commerce site with auth, payments, inventory, shipping, and admin panel"

Better:

Break into 10+ separate tasks, tackle one at a time

Mistake: Ignoring context limits

Reading 50 files without compacting

Better:

/compact regularly, use specific file paths

Mistake: Not using CLAUDE.md

Repeating "we use TypeScript" every session

Better:

/init and maintain CLAUDE.md

Viral Twitter Tips & Power User Hacks

These tips have gained significant traction in the developer community:

Parallel Claude Sessions

Run 5+ Claudes at once - Boris Cherny runs 5 Claude instances in parallel in his terminal, numbered 1-5, with system notifications to know when each needs input.

# Terminal tab naming for parallel sessions
# Tab 1: Auth feature
# Tab 2: API endpoints
# Tab 3: Tests
# Tab 4: Documentation
# Tab 5: Code review

Hand off to web sessions - Use & to send tasks to Claude Code on the web, and --teleport to move between local and web sessions.

Fresh Context = Better Performance

Start new conversations for each topic. Performance degrades as context accumulates.

# Instead of continuing a long session:
/clear  # Start fresh for new topics

# Or use /compact to summarize and continue
/compact

The Two-Claude Technique

Spin up a second Claude instance to review the first one's work. Each Claude finds it easier to criticize other Claudes than its own work.

# Terminal 1: Write code
# Terminal 2: Review with fresh context
cat src/feature.ts | claude -p "Review this code critically"

YOLO Mode (Use Carefully)

Bypass permissions for maximum speed. Only use in sandboxed environments.

alias cc="claude --dangerously-skip-permissions"

# Safer alternative: pre-approve specific commands
/permissions
# Add commonly used safe commands

Sound Notifications

Get notified when Claude finishes a task:

claude config set --global preferredNotifChannel terminal_bell

Plan with Opus, Execute with Sonnet

Use model switching strategically:

# Start planning with the best model
/model opus
> Plan how to implement user authentication

# Switch to faster model for execution
/model sonnet
> Implement the plan

The EPCT Workflow

Explore → Plan → Code → Test

  1. Explore: Let Claude understand the codebase first
  2. Plan: Use plan mode (Shift+Tab twice) to design approach
  3. Code: Execute with auto-accept in trusted scenarios
  4. Test: Always verify with tests or manual checks

Git Worktree for True Parallelism

Run independent Claude instances on the same repo:

# Create separate working directories
git worktree add ../feature-auth feature-auth
git worktree add ../feature-api feature-api

# Run Claude in each
cd ../feature-auth && claude
cd ../feature-api && claude

Container Isolation for Risky Work

Run experiments in Docker to prevent host system damage:

docker run -it -v $(pwd):/app -w /app node:20 bash
# Inside container: install and run Claude with skip-permissions

Reduce System Prompt Overhead

Tools consume 8-30% of context just by being available. Check and optimize:

/context  # See what's consuming tokens
# Remove unused MCP servers
# Keep CLAUDE.md concise

The 500-Line Rule for Skills

Keep SKILL.md files under 500 lines with concrete examples. Include 3 evaluation scenarios and test across multiple models.

Auto-Format with Hooks

Never waste context on formatting discussions:

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "npx prettier --write $CLAUDE_FILE_PATH"
      }]
    }]
  }
}

Memory Mode Shortcut

Use # to enter memory mode and save learnings:

# Remember: This project uses pnpm, not npm
# Remember: API routes need authentication middleware

External Editor for Complex Prompts

Press Ctrl + G to compose prompts in your preferred editor (vim, VS Code, etc.) for complex multi-line instructions.


17. Troubleshooting Guide

Common Issues

Installation Issues

"command not found: claude"

# Re-run installation
curl -fsSL https://claude.ai/install.sh | bash

# Check PATH
echo $PATH

# Add to PATH if needed
export PATH="$HOME/.claude/bin:$PATH"

"npm install failed"

# Check Node version (need 18+)
node --version

# Try with different registry
npm install -g @anthropic-ai/claude-code --registry https://registry.npmjs.org

Authentication Issues

"Please login" keeps appearing

# Clear credentials and re-login
rm -rf ~/.claude/credentials
claude
# Follow login prompts

"API key invalid"

# Check key is set correctly
echo $ANTHROPIC_API_KEY

# Or use explicit login
/login

Performance Issues

"Responses are slow"

  • Check internet connection
  • Large files take time to process
  • Complex tasks need more thinking
  • Try /compact to reduce context

"Running out of context"

/context  # Check usage
/compact  # Reduce context
/clear    # Start fresh if needed

Tool Errors

"Permission denied" for Bash

# Check settings allow the command
# Edit .claude/settings.json to allow specific commands

"File not found"

# Check path is correct
# Use relative paths from project root
# Or absolute paths

Extension Issues

VS Code extension not working

# Check Claude is installed
which claude

# Check extension is enabled
# View > Extensions > Claude Code > Enable

# Restart VS Code

Diagnostic Commands

# Check installation health
/doctor

# Check status
/status

# Check configuration
/config

# View logs (if enabled)
cat ~/.claude/logs/latest.log

18. Team Setup Checklist

Essential Setup

  • Create CLAUDE.md in project root

    /init
    
  • Configure permissions in .claude/settings.json

    {
      "permissions": {
        "allow": ["safe commands"],
        "deny": ["dangerous patterns"]
      }
    }
    
  • Add to .gitignore

    .claude/settings.local.json
    CLAUDE.local.md
    
  • Create team commands in .claude/commands/

    • /review - Code review
    • /test - Generate tests
    • /commit - Conventional commits
  • Set up MCP integrations in .mcp.json

    • GitHub for issues/PRs
    • Database for queries (read-only)
  • Create subagents in .claude/agents/

    • Code reviewer
    • Security auditor
    • Test generator
  • Configure hooks for automation

    • Auto-format on edit
    • Lint checking
    • Sensitive file protection

Documentation

  • Update CLAUDE.md with:

    • Project architecture
    • Coding standards
    • Common commands
    • Team conventions
  • Document in team wiki:

    • How to install Claude Code
    • Team commands and workflows
    • Best practices

Final Directory Structure

project/
├── CLAUDE.md                    # Project context
├── .claude/
│   ├── settings.json            # Team settings
│   ├── commands/
│   │   ├── review.md
│   │   ├── test.md
│   │   └── commit.md
│   ├── agents/
│   │   ├── code-reviewer/
│   │   │   └── AGENT.md
│   │   └── security-auditor/
│   │       └── AGENT.md
│   └── skills/
│       └── api-design/
│           └── SKILL.md
├── .mcp.json                    # MCP integrations
└── .gitignore                   # Includes .claude/settings.local.json

19. Quick Reference Cards

CLI Quick Reference

STARTING SESSIONS
─────────────────
claude              Interactive session
claude "task"       One-shot task
claude -c           Continue last session
claude -r "name"    Resume named session
claude -p "query"   Print mode (no interaction)

SLASH COMMANDS
──────────────
/help               Show all commands
/clear              Clear history
/compact            Reduce context
/cost               Show costs
/model              Change model
/config             Settings
/init               Create CLAUDE.md
/memory             Edit memory
/rename "name"      Name session
/resume             Resume session

SHORTCUTS
─────────
?                   Show shortcuts
Ctrl+C              Cancel
Ctrl+D              Exit
Shift+Enter         Multi-line
Shift+Tab           Change mode
Ctrl+R              Search history

Permissions Quick Reference

ALLOW PATTERNS
──────────────
Read                All file reads
Read(src/**/*.ts)   TypeScript in src
Bash(npm:*)         Any npm command
Bash(git status)    Exact command

DENY PATTERNS
─────────────
Read(.env*)         Environment files
Bash(rm -rf:*)      Dangerous delete
Bash(sudo:*)        Elevated commands

MODES
─────
normal              Ask everything
auto-accept         Accept safe edits
plan                Read-only

Files Quick Reference

USER FILES (~/.claude/)
───────────────────────
settings.json       Personal settings
CLAUDE.md           Personal memory
commands/           Personal commands
agents/             Personal agents

PROJECT FILES (.claude/)
────────────────────────
settings.json       Team settings (commit)
settings.local.json Personal overrides (gitignore)
commands/           Team commands
agents/             Team agents
skills/             Team skills

ROOT FILES
──────────
CLAUDE.md           Project memory (commit)
CLAUDE.local.md     Personal overrides (gitignore)
.mcp.json           MCP servers (commit)

End of Handbook

This comprehensive guide covers everything you need to know about Claude Code. For the most up-to-date information, refer to the official documentation at https://docs.anthropic.com/claude-code.