Claude Code Best Practices Guide

Master agentic coding with proven patterns from Anthropic's engineering team

๐Ÿš€ Claude Code Overview

Claude Code is a low-level, unopinionated agentic coding tool that provides close to raw model access without forcing specific workflows. It's designed to be flexible, customizable, scriptable, and safe.

๐ŸŽฏ Core Philosophy

Claude Code creates a flexible power tool that meets you where you work - in your terminal, with your existing tools and workflows.

๐Ÿ› ๏ธ Low-Level Control

Direct access to Claude's capabilities without imposed frameworks or rigid workflows.

๐Ÿ”ง Highly Customizable

Adapt to any codebase, language, or development environment through configuration.

๐Ÿ“œ Scriptable

Integrate into CI/CD pipelines and automate repetitive development tasks.

๐Ÿ›ก๏ธ Safe by Default

Conservative permission system with fine-grained control over tool access.

๐ŸŽฏ What You'll Learn

  • Environment optimization and context management
  • Creating effective CLAUDE.md files for project-specific guidance
  • Structured workflows for complex development tasks
  • Safety practices and permission management
  • Advanced features like MCP integration and custom commands
  • Pro tips from Anthropic's internal engineering teams

โŒจ๏ธ Core Commands

Master all Claude Code slash commands for complete development workflow control.

๐Ÿš€ Essential Commands

๐Ÿ“ /init

Creates a CLAUDE.md file with project analysis

# Run in your project directory /init # Claude analyzes your project and creates CLAUDE.md with: # - Tech stack detection # - Project structure overview # - Key commands and scripts # - Coding conventions discovered

โ“ /help

Shows all available commands and descriptions

# Get help on available commands /help # Shows comprehensive list of: # - Built-in slash commands # - Custom project commands # - User-defined commands # - Usage examples

๐Ÿ”ง /model

Switch between different Claude models

# Switch to Claude Opus for complex tasks /model claude-3-opus-20240229 # Switch to Sonnet for quick responses /model claude-3-5-sonnet-20241022 # Each model optimized for different use cases

โš™๏ธ /config

Configure Claude Code settings and preferences

# Configure terminal theme matching /config theme dark # Set keyboard shortcuts /config keybindings # Customize default behaviors /config defaults

๐Ÿ’ฌ Conversation Management

๐Ÿ”„ /continue

Resume previous conversations

# Continue most recent conversation /continue # Continue in non-interactive mode for scripts /continue --print # Select from multiple conversations /continue --select

๐Ÿ—‘๏ธ /clear

Reset conversation context completely

# Wipe conversation history completely /clear # Gives Claude a completely fresh start # Still retains CLAUDE.md and file context # Best when conversation has gone off track

๐Ÿ—œ๏ธ /compact

Compress context while preserving key information

# Compress conversation /compact # With optional focus instructions /compact [focus instructions] # Maintains important context and decisions # Removes redundant information

๐Ÿ“Š /cost

Monitor token usage and costs

# Check current usage and costs /cost # See detailed breakdown of: # - Token consumption # - Cost estimates # - Usage patterns # - Optimization suggestions

๐Ÿ”’ Permission & Security

๐Ÿ›ก๏ธ /permissions

Manage tool permissions and security settings

# View current permissions /permissions # Add specific permissions /permissions add Edit /permissions add "Bash(git commit:*)" # Customize tool access for safety

๐Ÿง  /memory

View and manage project memory

# View current memory/context /memory # Edit memory settings /memory edit # Optimize memory usage /memory optimize

๐Ÿ“ Project & File Management

๐ŸŒณ /tree

Display project directory structure

# Show project tree structure /tree # Claude breaks down the directory tree # Perfect for understanding project layout # Helps navigate complex codebases

๐Ÿ“‹ /overview

Get high-level project overview

# Get comprehensive project overview /overview # Perfect for: # - Onboarding to new codebases # - Open source project exploration # - Understanding architecture

๐Ÿ” /structure

Analyze and explain project structure

# Analyze project structure /structure # Claude identifies: # - Architecture patterns # - Design principles # - Code organization # - Development practices

๐Ÿ’ป /ide

Connect with IDE integration

# Connect to IDE /ide # Enables Claude to: # - See open files # - Read linter warnings # - Access IDE context # - Fix issues directly

๐Ÿ”ง Development Tools

๐Ÿ‘€ /review

Code review and analysis

# Review code for issues /review # Get feedback on: # - Security vulnerabilities # - Performance optimizations # - Code style compliance # - Bug detection

๐ŸŽฏ /task

Spawn sub-agents for parallel work

# Create focused sub-agent /task # Parallel execution: # - Independent context # - Same tool access # - Focused objectives # - Context isolation

๐Ÿ”Œ /mcp

Manage MCP servers and integrations

# List MCP servers /mcp list # Add new MCP server /mcp add server-name # Configure integrations /mcp configure

๐ŸŽจ Custom Commands

๐Ÿ“‚ Project Commands (/project:name)

Create team-shared commands in .claude/commands/:

# Create project command mkdir -p .claude/commands echo "Run all unit tests and report results" > .claude/commands/test.md # Usage /project:test # Available to all team members # Shows "(project)" in /help

๐Ÿ‘ค User Commands (/user:name)

Create personal commands in ~/.claude/commands/:

# Create personal command mkdir -p ~/.claude/commands echo "Review code for security vulnerabilities" > ~/.claude/commands/security.md # Usage /user:security # Available across all projects # Shows "(user)" in /help

๐Ÿ“‹ Quick Reference

๐Ÿ”ง Core Commands

  • /help - List all commands
  • /init - Initialize project
  • /clear - Reset context
  • /compact - Compress context
  • /model - Switch models

๐Ÿ“Š Management

  • /cost - Check usage
  • /memory - Manage memory
  • /permissions - Set permissions
  • /config - Configure settings
  • /continue - Resume session

๐Ÿ—๏ธ Project Tools

  • /tree - Show structure
  • /overview - Project summary
  • /review - Code review
  • /task - Spawn sub-agent
  • /ide - IDE integration

๐ŸŽฏ Custom Commands

  • /project:name - Team commands
  • /user:name - Personal commands
  • $ARGUMENTS - Pass parameters
  • @file.js - Reference files
  • !command - Execute bash

โš™๏ธ Setup & Configuration

๐Ÿ”ง Environment Optimization

Claude Code automatically pulls context into prompts, which consumes time and tokens. Optimize through environment tuning:

Configure Tool Permissions

Customize the allowlist to permit safe tools and allow easy-to-undo operations:

# Allow file editing and git operations (easy to undo) claude --allow-edit-files --allow-git # Allow specific bash commands claude --allow-bash-commands="npm,yarn,pip"

MCP Configuration

Configure Model Context Protocol servers for enhanced capabilities:

In project directory (available when running Claude Code in that directory):

{ "mcp": { "servers": { "puppeteer": { "command": "npx", "args": ["@anthropic-ai/mcp-server-puppeteer"] }, "sentry": { "command": "npx", "args": ["@anthropic-ai/mcp-server-sentry"], "env": { "SENTRY_AUTH_TOKEN": "your-token" } } } } }

Debug Configuration

Use debug flags to identify configuration issues:

# Launch with MCP debugging claude --mcp-debug # Use verbose mode for detailed output claude --verbose

โš ๏ธ Permission Best Practices

Start with conservative permissions and gradually allow more tools as you become comfortable with Claude's behavior in your environment.

๐Ÿ“ CLAUDE.md Files

CLAUDE.md is a special file that Claude automatically pulls into prompts to provide project-specific context and instructions.

๐Ÿ“‚ File Hierarchy

Claude reads CLAUDE.md files in priority order:

  1. User's home directory (~/.claude/CLAUDE.md)
  2. Project root directory
  3. Current working directory
  4. Parent directories (walking up the tree)

๐Ÿ’ก Local vs Shared Files

  • CLAUDE.md - Shared team configuration (commit to git)
  • CLAUDE.local.md - Personal settings (add to .gitignore)
  • Use local files for personal preferences and credentials
  • Use shared files for team standards and project info

โœจ Essential Components

๐Ÿ› ๏ธ Tech Stack

Declare tools, frameworks, and versions used in your project

# Tech Stack - Node.js 18+ - React 18.2 - TypeScript 5.0 - Tailwind CSS 3.4

๐Ÿ“ Project Structure

Outline key directories and their purposes

# Project Structure - src/components/ - Reusable UI components - src/lib/ - Core business logic - src/pages/ - Next.js pages - tests/ - Test files

โšก Key Commands

List important scripts and commands

# Commands - npm run dev - Start development server - npm test - Run test suite - npm run build - Build for production - npm run lint - Run ESLint

๐Ÿ“ Code Style

Define formatting and convention rules

# Code Style - Use TypeScript strict mode - Prefer named exports - Use async/await over Promises - Destructure imports when possible

๐Ÿ”ง Dynamic Updates

Use the # key to give Claude instructions that it will automatically incorporate into the relevant CLAUDE.md:

# Press # in Claude Code, then type: "Always use semantic commit messages following conventional commits format" # This gets automatically added to your CLAUDE.md

๐Ÿ’ก Optimization Tips

  • Keep content concise - CLAUDE.md is prepended to every prompt
  • Use bullet points instead of long paragraphs
  • Run through prompt improver for better adherence
  • Add emphasis with "IMPORTANT" or "YOU MUST" for critical rules
  • Include CLAUDE.md changes in commits to benefit team members

๐Ÿ“‹ Example CLAUDE.md Template

# Project: E-commerce Platform ## Tech Stack - Next.js 14 with App Router - TypeScript 5.2 - Prisma with PostgreSQL - Tailwind CSS 3.4 ## Key Commands - npm run dev - Development server (localhost:3000) - npm run build - Production build - npm test - Run Jest tests - npm run db:migrate - Run database migrations ## Code Style - Use TypeScript strict mode - Prefer named exports over default exports - Use Prisma for all database operations - Follow conventional commit format - Write tests for new features ## Project Structure - app/ - Next.js app router pages - components/ - Reusable UI components - lib/ - Utilities and database schema - prisma/ - Database schema and migrations ## IMPORTANT - Always validate user input before database operations - Use proper error handling with try-catch blocks - Include unit tests for business logic functions

๐Ÿ”„ Proven Workflows

๐ŸŽฏ The Research โ†’ Plan โ†’ Implement Pattern

The most effective workflow for complex tasks follows this structured approach:

๐Ÿ” Research Phase

Ask Claude to research the problem and understand the codebase:

"Before implementing anything, please: 1. Read through the relevant files in our authentication system 2. Understand the current user model and session handling 3. Identify any existing patterns we should follow 4. Research best practices for OAuth2 implementation"

๐Ÿ“‹ Planning Phase

Have Claude create a detailed plan before coding:

"Now create a detailed implementation plan that: 1. Breaks down the OAuth2 integration into logical steps 2. Identifies required dependencies and configuration 3. Plans the database schema changes 4. Outlines the testing strategy 5. Consider security implications and error handling"

Pro Tip: Use keywords like "think hard" or "ultrathink" to extend Claude's reasoning time for better planning.

โšก Implementation Phase

Execute the plan with verification steps:

"Implement the plan step by step: 1. Start with the database schema changes 2. Implement the OAuth2 routes and handlers 3. Add proper error handling and validation 4. Write comprehensive tests 5. Update documentation and examples"

๐Ÿš€ Completion Phase

Finalize with proper documentation and cleanup:

"Complete the implementation by: 1. Running all tests to ensure nothing broke 2. Creating a clear pull request with description 3. Updating the README with new OAuth2 setup instructions 4. Committing all changes with semantic commit messages"

๐Ÿงช Test-Driven Development (TDD) Workflow

For features that can be verified with tests:

Red Phase

"Write failing tests for the user authentication feature: 1. Test successful login with valid credentials 2. Test failed login with invalid credentials 3. Test password reset functionality 4. Test session management and logout"

Green Phase

"Now implement the minimum code needed to make these tests pass: 1. Focus on making tests pass, not perfect code 2. Implement core authentication logic 3. Add basic error handling 4. Ensure all tests are green"

Refactor Phase

"Refactor the implementation while keeping tests green: 1. Improve code organization and readability 2. Add comprehensive error handling 3. Optimize performance where needed 4. Ensure tests still pass after refactoring"

๐Ÿ›ก๏ธ Safety & Permissions

๐Ÿ”’ Permission System

Claude Code uses a conservative permission system by default, requesting permission for any action that might modify your system.

โš ๏ธ Default Behavior

By default, Claude requests permission for:

  • File writes and modifications
  • Most bash commands
  • MCP tool usage
  • Network requests

โš™๏ธ Customizing Permissions

๐ŸŸข Safe Tools to Allow

These tools are generally safe and easy to undo:

  • File editing (changes can be reverted with git)
  • Git operations (commits, branches, etc.)
  • Package manager commands (npm, yarn, pip)
  • Test runners (jest, pytest, etc.)
  • Linting and formatting tools
# Allow common safe operations claude --allow-edit-files --allow-git --allow-bash-commands="npm,yarn,jest" # Or configure in project settings { "permissions": { "allowEditFiles": true, "allowGit": true, "allowedBashCommands": ["npm", "yarn", "jest", "eslint"] } }

๐Ÿš€ Advanced Features

โšก Custom Slash Commands

Store prompt templates in Markdown files within the .claude/commands folder for reusable workflows:

Creating Commands

# Create a custom refactoring command echo "Refactor this code to improve readability and performance: 1. Extract reusable functions 2. Add proper TypeScript types 3. Improve error handling 4. Add comprehensive comments 5. Ensure all tests still pass" > .claude/commands/refactor.md

Using Arguments

Use $ARGUMENTS to pass parameters:

# Create a GitHub issue fixer echo "Find and fix GitHub issue: $ARGUMENTS Follow these steps: 1. Understand the issue described in the ticket 2. Locate the relevant code in our codebase 3. Implement a solution that addresses the root cause 4. Add appropriate tests 5. Prepare a concise PR description" > .claude/commands/fix-issue.md # Usage: /fix-issue 123

๐Ÿ”— Model Context Protocol (MCP)

Extend Claude's capabilities with specialized tools and external services:

๐ŸŒ Web Automation

Use Puppeteer server for browser automation and visual testing

# Add to .mcp.json { "servers": { "puppeteer": { "command": "npx", "args": ["@anthropic-ai/mcp-server-puppeteer"] } } }

๐Ÿ“Š Error Monitoring

Connect to Sentry for error analysis and debugging

# Add to .mcp.json { "servers": { "sentry": { "command": "npx", "args": ["@anthropic-ai/mcp-server-sentry"], "env": { "SENTRY_AUTH_TOKEN": "your-token" } } } }

๐Ÿ’ก Pro Tips

๐ŸŽฏ Iteration and Improvement

The 2-3 Iteration Rule

The first version might be good, but after 2-3 iterations it will typically look much better. Give Claude the tools to see its outputs for best results.

๐Ÿ” Onboarding and Exploration

When onboarding to a new codebase, use Claude Code for learning and exploration:

# Ask the same questions you'd ask another engineer "Can you explain how the authentication flow works in this codebase?" "What's the pattern for handling API errors here?" "How are components typically structured in this project?" "Where should I add the new feature I'm working on?"

โšก Performance Optimization

๐Ÿ“ Context Management

Keep CLAUDE.md files concise to reduce token consumption

  • Use bullet points over paragraphs
  • Remove redundant information
  • Focus on actionable instructions

๐ŸŽฏ Targeted Prompts

Be specific about what you want Claude to focus on

  • Mention specific files or functions
  • Define clear success criteria
  • Break large tasks into smaller chunks

๐ŸŽฏ Remember the Goal

Claude Code is a tool to augment your development workflow, not replace your expertise. The best results come from combining Claude's capabilities with your domain knowledge and judgment.