Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

CLAUDE.md Mastery: Custom Commands & Configuration for Claude Code Power Users

6 min read

MacBook Pro showing programming language - CLAUDE.md configuration

⏱ Reading time: ~13 min | 🗓 Updated: June 2026

Every Claude Code user knows you can just type tasks in plain English. But power users know that CLAUDE.md — Claude Code’s project memory file — combined with custom slash commands and a well-tuned settings.json can transform Claude from a capable assistant into a domain expert deeply embedded in your codebase, tech stack, and team conventions.

Searches for “CLAUDE.md best practices” and “Claude Code custom commands” are up 500%+ in 2026 as more developers discover that this configuration layer is where the real productivity gains live. This guide covers everything: structuring CLAUDE.md, writing effective custom commands, configuring settings.json, and the patterns that senior engineers are using to 10× their Claude Code output.

What Is CLAUDE.md?

CLAUDE.md is a Markdown file that Claude Code reads at the start of every session. It acts as persistent memory: instructions, context, conventions, and rules that you don’t want to repeat every time you start a new conversation. Think of it as your project’s “AI onboarding document” — everything a new developer (or AI) would need to understand to work effectively on your codebase.

CLAUDE.md File Locations

LocationScopeBest For
~/.claude/CLAUDE.mdGlobal (all projects)Personal preferences, global tools, coding style
./CLAUDE.md (project root)Project-wideTech stack info, team conventions, project architecture
./src/CLAUDE.md (subdirectory)Directory-specificModule-level context, component patterns

Claude reads all applicable CLAUDE.md files — global, project, and any directory-level files — and merges them into its context at session start. More specific files take precedence over more general ones.

The Anatomy of a Great CLAUDE.md

A well-structured CLAUDE.md has several key sections. Here’s the template used by senior engineers in 2026:

# CLAUDE.md — [Project Name]

## Project Overview
Brief description of what this project does, who uses it, and why it exists.
[2-3 sentences max]

## Tech Stack
- Runtime: Node.js 22 / Python 3.12 / Go 1.22
- Framework: Next.js 15 / FastAPI / Gin
- Database: PostgreSQL 16 with Drizzle ORM
- Testing: Vitest + Playwright
- CI/CD: GitHub Actions + Railway

## Architecture
Describe the key architectural patterns:
- Service boundaries and responsibilities
- Data flow between services
- Key design decisions and WHY they were made

## Directory Structure
src/
  api/          # REST API routes
  services/     # Business logic layer
  db/           # Database models and migrations
  types/        # TypeScript type definitions
tests/
  unit/         # Unit tests (Vitest)
  integration/  # Integration tests
  e2e/          # End-to-end tests (Playwright)

## Coding Conventions
- Use TypeScript strict mode, no "any" types
- Function names: camelCase. Classes: PascalCase. Constants: SCREAMING_SNAKE
- Error handling: always use Result pattern, never throw in service layer
- API responses: always use { data, error, meta } structure
- Database: always use transactions for multi-table writes

## Testing Requirements
- Every new function MUST have unit tests
- Every new API endpoint MUST have integration tests
- Test coverage must stay above 80%
- Run tests before reporting task completion

## Do NOT
- Never modify .env files directly; use .env.example
- Never commit node_modules, dist/, or .next/
- Never use console.log in production code; use the logger service
- Never bypass TypeScript errors with // @ts-ignore

## Key Files to Know
- src/types/index.ts — global type definitions
- src/lib/logger.ts — logging utility (use this, not console)
- src/db/schema.ts — database schema (Drizzle)
- .env.example — all required environment variables

Writing a Global CLAUDE.md

Your ~/.claude/CLAUDE.md applies to all projects. Use it for personal preferences and global tools:

# ~/.claude/CLAUDE.md — Global Personal Config

## My Preferences
- Communication: Be concise. Skip preamble. Provide code directly.
- When uncertain: Ask ONE clarifying question rather than guessing
- After each task: Run tests and show me a summary of what changed
- Commit style: Use conventional commits (feat:, fix:, chore:, docs:)

## Tools I Always Have Available
- GitHub CLI: `gh` (for PRs, issues, releases)
- Docker: always running, use for test databases
- jq, ripgrep, fd — prefer these over grep/find

## Code Style (applies everywhere unless project overrides)
- Prefer explicit over implicit
- No commented-out code
- Short functions (<30 lines)
- Meaningful variable names (no single-letter vars except loop counters)

## Never Do (globally)
- Never suggest or use deprecated APIs
- Never add console.log statements without my explicit request
- Never run sudo commands without asking first

Custom Slash Commands

Custom commands are one of the most underused Claude Code features. They let you define reusable workflows as Markdown files that you invoke with a slash command. Think of them as macro programs for your most common tasks.

Creating a Custom Command

Create a Markdown file in .claude/commands/ (project commands) or ~/.claude/commands/ (global commands):

# .claude/commands/review-pr.md

Review the current branch's changes against main.

Perform a comprehensive code review that includes:
1. Correctness: Logic errors, edge cases, off-by-one errors
2. Security: SQL injection, XSS, authentication bypasses, exposed secrets
3. Performance: N+1 queries, missing indexes, unnecessary computations
4. Testing: Missing test cases, untested edge cases
5. Style: Violations of our coding conventions in CLAUDE.md

For each issue found:
- Specify the file and line number
- Explain why it's a problem
- Provide the corrected code

Produce a structured report with sections for Critical, Major, Minor issues.
End with an overall assessment: Approve, Request Changes, or Needs Discussion.

Use it in Claude Code with: /review-pr

More Useful Custom Commands

Generate Comprehensive Tests

# .claude/commands/gen-tests.md

Generate comprehensive unit and integration tests for the
file or function I'll specify.

For each function/method:
- Write tests for the happy path
- Write tests for all error conditions
- Write tests for edge cases (empty inputs, null values, boundaries)
- Mock external dependencies (database, API calls, file system)

Use Vitest syntax. Follow the AAA pattern (Arrange, Act, Assert).
Ensure tests are isolated and can run in any order.
Target 90%+ code coverage for the specified file.

Database Migration Generator

# .claude/commands/new-migration.md

Create a new database migration for the change I describe.

1. Read the current schema in src/db/schema.ts
2. Create a new migration file in src/db/migrations/ with
   timestamp prefix (YYYYMMDD_HHMMSS_description.ts)
3. Write UP and DOWN functions
4. Add appropriate indexes for any new foreign keys or
   frequently-queried columns
5. Update the schema.ts file to reflect the changes
6. Run the migration to verify it works: npm run db:migrate
7. Generate the updated TypeScript types: npm run db:generate

API Endpoint Generator

# .claude/commands/new-endpoint.md

Create a new REST API endpoint following our project conventions.

I will describe the endpoint. You should:
1. Create the route handler in src/api/
2. Create the service function in src/services/
3. Add input validation using Zod schema
4. Add proper error handling using our Result pattern
5. Write integration tests in tests/integration/
6. Update the API documentation in docs/api/
7. Run the test suite to verify nothing is broken

Debug Session Helper

# .claude/commands/debug.md

Help me debug the issue I'm about to describe.

Approach:
1. Ask me for the error message, stack trace, and reproduction steps
2. Read the relevant source files
3. Form 3 hypotheses about the root cause, ranked by likelihood
4. For each hypothesis, describe a test to confirm or rule it out
5. After I run the tests, update your hypotheses
6. Continue until root cause is identified
7. Implement and verify the fix
8. Write a regression test to prevent recurrence

Advanced settings.json Configuration

Beyond hooks, settings.json controls Claude Code’s behavior, tool access, and safety settings:

{
  "model": "claude-sonnet-4-5",
  "autoAccept": {
    "bash": false,
    "write_file": false,
    "read_file": true
  },
  "permissions": {
    "allowedTools": [
      "bash", "write_file", "read_file", "list_directory",
      "web_search", "mcp_*"
    ],
    "blockedCommands": [
      "rm -rf /", "sudo", "chmod 777",
      "curl | bash", "wget | sh"
    ]
  },
  "context": {
    "maxFiles": 100,
    "excludePatterns": [
      "node_modules/**", "dist/**", ".next/**",
      "*.lock", "*.min.js", "coverage/**"
    ]
  },
  "output": {
    "verbosity": "normal",
    "showCost": true,
    "showTokenCount": true
  }
}

CLAUDE.md Anti-Patterns to Avoid

1. Information Overload

Problem: CLAUDE.md is 5,000+ words long with exhaustive detail about every aspect of the project. Every session burns thousands of tokens just reading it.
Fix: Keep CLAUDE.md under 500-800 tokens. Focus on things Claude genuinely can’t figure out from reading the code.

2. Contradictory Instructions

Problem: Global CLAUDE.md says “always use spaces” but project CLAUDE.md says “use tabs”. Claude picks one inconsistently.
Fix: Project CLAUDE.md overrides global on conflicts. Be explicit: “This project uses 2-space indentation (overrides global preference)”.

3. Stale Information

Problem: CLAUDE.md says “use PostgreSQL 14” but you migrated to PostgreSQL 16 six months ago. Claude makes outdated assumptions.
Fix: Add a “Last Updated” date to CLAUDE.md and make updating it part of your major refactoring/upgrade checklist.

4. Instructions Without Context

Problem: “Never use async/await” with no explanation. Claude doesn’t understand the constraint and may work around it in unintended ways.
Fix: Explain the why: “Never use async/await in route handlers — we use our custom Promise wrapper (src/lib/promise.ts) for error handling consistency”.

Real-World CLAUDE.md Examples by Stack

Django + PostgreSQL API

## Tech Stack
- Django 5.0, Django REST Framework 3.15
- PostgreSQL 16, psycopg3
- Celery + Redis for background tasks
- pytest + factory_boy for testing

## Conventions
- Views: use ViewSets, never function-based views
- Serializers: always validate in serializer, not in view
- DB queries: use select_related/prefetch_related, never N+1
- Background tasks: all emails/notifications go through Celery
- Migrations: squash migrations quarterly

## Never
- Never put business logic in views
- Never access request.user in serializers (use context)
- Never use raw SQL except in custom QuerySet methods

React + Zustand Frontend

## Tech Stack
- React 19, TypeScript 5.5
- Zustand for global state, React Query for server state
- Tailwind CSS v4, shadcn/ui components
- Vite, Vitest, Playwright

## Conventions
- Components: always functional, never class components
- State: use React Query for ALL server data, Zustand only for pure UI state
- Styling: Tailwind classes only, no custom CSS files
- Forms: use react-hook-form + Zod for all forms
- API calls: always through src/lib/api.ts, never fetch() directly

## Component Pattern
Every component file should have:
1. TypeScript interface for props (ComponentNameProps)
2. The component function (export default)
3. Unit tests in [ComponentName].test.tsx same directory

Conclusion

CLAUDE.md and custom commands are the configuration layer that separates casual Claude Code users from power users. A well-crafted CLAUDE.md means Claude Code understands your codebase’s architecture, conventions, and constraints from session one. Custom commands package your best workflows into reusable macros. Together, they let you work with Claude as a genuine expert on your specific codebase — not just a general-purpose coding assistant.

Start by writing a project CLAUDE.md with your tech stack, key conventions, and “never do” rules. Then create one custom command for your most repetitive task. Iterate from there. The Claude Code settings documentation covers all available configuration options.

📚 Resources & Further Reading

Official Documentation

Community Resources

Collabnix Related Posts

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

Function Calling with Ollama: Building Local Tool-Using AI Agents

A practical guide to function/tool calling with Ollama: how it works, which local models support it, a minimal agent loop, and common pitfalls to...
Collabnix Team
2 min read

Leave a Reply

Join our Discord Server
Index