Prompts Guide Claude Code Configuration

CLAUDE.md: The Complete Guide for Claude Code

Configure Claude Code with project context, coding standards, and security rules

Quick Answer

CLAUDE.md is a configuration file that customizes Claude Code's behavior for your project. Place it in your project root with tech stack info, coding standards, and security rules. Claude Code reads it automatically using a 4-tier hierarchy with support for imports (@path) and path-specific rules. This guide includes copy-paste templates.

What is CLAUDE.md?

CLAUDE.md is the configuration file for Claude Code, Anthropic's official CLI coding assistant. It contains project context, coding standards, development commands, and security rules that guide how Claude Code generates and modifies your code.

Think of CLAUDE.md as persistent memory for your project. Instead of repeating "use TypeScript strict mode" or "always validate with Zod" in every conversation, you write it once. Claude Code reads these instructions at session start and applies them to all code generation.

For vibe coders, CLAUDE.md is essential because it lets you encode security rules that prevent common vulnerabilities. Rules like "never use template literals for SQL" guide Claude Code toward secure patterns from the start - addressing issues we document across our vulnerability guides.

The four-tier memory hierarchy

Claude Code uses a sophisticated 4-tier system for configuration. Higher tiers override lower ones, so enterprise policies take precedence over personal preferences. Based on the official Claude Code documentation:

Tier 1

Enterprise Policy

/Library/Application Support/ClaudeCode/CLAUDE.md

Organization-wide rules managed by IT/DevOps. Highest priority.

Use for: Company security policies, compliance requirements

Tier 2

Project Memory

./CLAUDE.md or ./.claude/CLAUDE.md

Team-shared, version controlled project configuration.

Use for: Tech stack, coding standards, project-specific rules

Tier 3

Project Rules

./.claude/rules/*.md

Modular, path-specific rules for different contexts.

Use for: TypeScript rules, testing patterns, security rules

Tier 4

User Memory

~/.claude/CLAUDE.md

Personal preferences. Lowest priority. Local variant: ./CLAUDE.local.md (auto-gitignored)

Use for: Personal coding style, response format preferences

Recursive discovery: Claude Code searches upward to the git root and downward into subtrees to find all applicable CLAUDE.md files. You don't need to manually configure paths - just place the files and they're discovered automatically.

How to create a CLAUDE.md file

Create a file named CLAUDE.md in your project root. Claude Code automatically detects and loads it. Here's the recommended structure:

Project Structure
your-project/
├── CLAUDE.md                 # Main project config (Tier 2)
├── CLAUDE.local.md           # Personal overrides (auto-gitignored)
├── .claude/
│   ├── CLAUDE.md             # Alternative location
│   └── rules/                # Modular rules (Tier 3)
│       ├── security.md       # Security patterns
│       ├── typescript.md     # TS conventions
│       └── testing.md        # Test patterns
├── src/
└── package.json

Essential sections

CLAUDE.md Template
# CLAUDE.md

## Project Overview
[What this project does - 2-3 sentences]

## Tech Stack
- Framework: [Next.js 14 / SvelteKit / etc.]
- Language: [TypeScript / Python / etc.]
- Database: [Supabase / Prisma / MongoDB]
- Styling: [Tailwind / CSS Modules]

## Development Commands
- `npm run dev` - Start development server
- `npm run build` - Build for production
- `npm test` - Run tests
- `npm run lint` - Run linter

## Architecture
[Key patterns, folder structure, important files]

## Code Conventions
[Naming, formatting, patterns to follow]

## Security Rules
@.claude/rules/security.md

## Common Gotchas
[Things that often trip people up]

Imports and path-specific rules

CLAUDE.md supports two powerful features for organizing rules: imports and path-specific rules.

Imports (@path syntax)

Use @path/to/file.md to import other markdown files. This keeps your main CLAUDE.md clean while organizing rules into focused modules. Maximum import depth is 5 hops.

Using Imports
# CLAUDE.md

## Security Rules
@.claude/rules/security.md

## TypeScript Conventions
@.claude/rules/typescript.md

## Testing Patterns
@.claude/rules/testing.md

Path-specific rules (YAML frontmatter)

Apply rules only to specific file paths using YAML frontmatter. This is useful for language-specific conventions or different standards for different parts of your codebase.

.claude/rules/api-routes.md
---
paths: src/app/api/**/*.ts
---

# API Route Rules

These rules apply only to API routes.

## Authentication
- Check auth at the start of every handler
- Return 401 for unauthenticated requests
- Return 403 for unauthorized requests

## Response Format
- Always return JSON
- Include appropriate status codes
- Never expose internal error details

Security rules for CLAUDE.md (copy-paste ready)

These security rules prevent the most common vulnerabilities in vibe coded projects. Save this as .claude/rules/security.md and import it in your main CLAUDE.md.

.claude/rules/security.md
# Security Rules

## Database Security
- NEVER use template literals for SQL queries
- ALWAYS use parameterized queries or ORM methods
- Validate input types before any database operation
- Use allowlists for dynamic table/column names

Patterns:
- SECURE: db.query('SELECT * FROM users WHERE id = $1', [userId])
- SECURE: prisma.user.findUnique({ where: { id: userId } })
- VULNERABLE: db.query(`SELECT * FROM users WHERE id = ${userId}`)

## Authentication
- Check authentication on EVERY API route and Server Action
- Use middleware for auth checks, not inline code
- Never trust client-side auth state for server decisions
- Implement proper session validation

Pattern for protected routes:
1. Get session/token
2. Validate session exists and is valid
3. Check user permissions if needed
4. THEN process the request

## Input Validation
- Validate ALL user input on the server
- Use Zod or similar for schema validation
- Never pass raw user input to:
  - Database queries
  - File system operations
  - Shell commands
  - URL redirects
  - HTML rendering

Pattern:
const schema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100)
})
const result = schema.safeParse(input)
if (!result.success) return error(400, 'Invalid input')

## Secret Handling
- NEVER hardcode API keys, passwords, or tokens
- Use environment variables: process.env.SECRET_NAME
- Never log secrets or include in error messages
- Never commit .env files (add to .gitignore)
- Use different secrets for dev/staging/prod

Pattern:
- SECURE: const apiKey = process.env.STRIPE_SECRET_KEY
- VULNERABLE: const apiKey = "sk_live_abc123..."

## Path Traversal Prevention
- Validate file paths before any file operation
- Use allowlists for permitted directories
- Sanitize user-provided filenames
- Never construct paths with user input directly

Pattern:
- SECURE: const safePath = path.join(UPLOAD_DIR, path.basename(userFile))
- VULNERABLE: const unsafePath = path.join('/uploads', userProvidedPath)

## Authorization (Beyond Auth)
- Check resource OWNERSHIP, not just authentication
- Verify user can access the specific resource requested
- Use WHERE clauses that include user ID
- Never expose internal IDs without ownership check

Pattern:
- SECURE: where: { id: resourceId, userId: session.user.id }
- VULNERABLE: where: { id: resourceId } // Missing ownership check

## NoSQL Security (MongoDB, Firestore)
- Validate input is string, not object (prevents operator injection)
- Never pass raw req.body to queries
- Use schema validation (Zod) to reject objects like {"$ne": ""}

Pattern:
- SECURE: if (typeof input !== 'string') throw new Error('Invalid')
- VULNERABLE: db.collection('users').findOne({ username: req.body.username })

These rules address vulnerabilities covered in our security guides: SQL injection, hardcoded secrets, missing authentication, IDOR, path traversal, and NoSQL injection.

CLAUDE.md templates by stack

Complete CLAUDE.md templates for popular vibe coding stacks. Copy the one that matches your project and customize as needed.

Next.js + Supabase

Full-stack with App Router and Supabase backend

# CLAUDE.md

## Project Overview
E-commerce platform built with Next.js 14 and Supabase.

## Tech Stack
- Next.js 14 (App Router)
- TypeScript (strict mode)
- Supabase (auth + database + storage)
- Tailwind CSS
- Zod for validation

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

## Architecture
- /app - Routes and layouts (App Router)
- /components - Reusable UI components
- /lib - Utilities, Supabase client, helpers
- /types - TypeScript interfaces

## Code Conventions
- Use Server Components by default
- Client Components only for interactivity
- Use Server Actions for mutations
- Prefer named exports over default

## Security Rules
@.claude/rules/security.md

## Database Patterns
- Enable RLS on ALL tables
- Use auth.uid() in RLS policies
- Never expose service_role key in client code
- Use getUser() not getSession() for auth checks

SvelteKit + Prisma

SvelteKit with Prisma ORM and PostgreSQL

# CLAUDE.md

## Project Overview
SaaS application built with SvelteKit and Prisma.

## Tech Stack
- SvelteKit 2.0
- TypeScript (strict)
- Prisma ORM
- PostgreSQL
- Tailwind CSS

## Development Commands
- `npm run dev` - Start dev server
- `npm run build` - Build for production
- `npx prisma studio` - Database GUI
- `npx prisma migrate dev` - Run migrations

## Architecture
- /src/routes - SvelteKit routes
- /src/lib - Shared code, components
- /src/lib/server - Server-only code
- /prisma - Schema and migrations

## Code Conventions
- Use Svelte 5 runes ($state, $derived, $effect)
- Load data in +page.server.ts
- Mutations via form actions
- Use $lib alias for imports

## Security Rules
- NEVER use $queryRaw with template literals
- Always use Prisma's parameterized methods
- Validate input with Zod in form actions
- Check auth in every +page.server.ts load function
- Use hooks.server.ts for session management

Python + FastAPI

Modern Python API with async support

# CLAUDE.md

## Project Overview
REST API built with FastAPI and SQLAlchemy.

## Tech Stack
- Python 3.11+
- FastAPI
- SQLAlchemy (async)
- Pydantic v2
- PostgreSQL

## Development Commands
- `uvicorn main:app --reload` - Start dev server
- `pytest` - Run tests
- `alembic upgrade head` - Run migrations
- `ruff check .` - Lint code

## Architecture
- /app/api - Route handlers
- /app/models - SQLAlchemy models
- /app/schemas - Pydantic schemas
- /app/services - Business logic
- /app/core - Config, security, deps

## Code Conventions
- Type hints on all functions
- Async/await for database operations
- Dependency injection for auth
- Pydantic models for all request/response

## Security Rules
- Use Pydantic for ALL input validation
- NEVER use f-strings for SQL
- Use SQLAlchemy ORM methods or text() with bindparams
- Hash passwords with bcrypt
- Rate limit auth endpoints
- Never expose stack traces in production

CLAUDE.md best practices

Based on the official Claude Code documentation:

Do

  • Be specific ("Use 2-space indentation" not "Format properly")
  • Use markdown structure to organize related rules
  • Review and update as project evolves
  • Keep rules focused on single topics
  • Use imports to organize large rule sets
  • Include actual code patterns (secure vs vulnerable)
  • Version control your CLAUDE.md

Don't

  • Use vague instructions ("write good code")
  • Duplicate rules across multiple files
  • Include sensitive information (secrets, credentials)
  • Overuse path-specific rules (keep simple)
  • Set and forget (review quarterly)
  • Make rules conflict with each other
  • Put everything in one giant file

CLAUDE.md vs .cursorrules

If you use both Claude Code and Cursor, here's how their configuration systems compare:

FeatureCLAUDE.md.cursorrules
ToolClaude Code (CLI)Cursor IDE
Hierarchy4-tier (Enterprise → Project → Rules → User)3-tier (Team → Project → User)
ImportsYes (@path/to/file.md)No (file references only)
Path-specificYAML frontmatterglobs in frontmatter
DiscoveryRecursive (up to git root, down into subtrees)Project root only
Local overrideCLAUDE.local.md (auto-gitignored)User rules folder

Using both tools?

Create an AGENTS.md file in your project root. It's supported by both Claude Code and Cursor as a universal fallback, plus Cline and other tools. Put your shared rules there and tool-specific rules in their respective files.

AGENTS.md (Cross-tool compatibility)
# AGENTS.md

## Project Context
E-commerce platform with Next.js frontend and Supabase backend.

## Coding Standards
- TypeScript strict mode
- Functional components with hooks
- Zod for all input validation

## Security Requirements
- Parameterized queries only
- Auth check on every API route
- Never hardcode secrets

See our Cursor Rules guide for detailed .cursorrules configuration.

Frequently asked questions

What is CLAUDE.md?

CLAUDE.md is a configuration file that customizes Claude Code behavior for your project. It contains project context, coding standards, commands, and security rules. Claude Code automatically reads it at session start and uses the instructions to guide code generation.

Where do I put CLAUDE.md?

Place CLAUDE.md in your project root for project-specific rules. Claude Code supports a 4-tier hierarchy: Enterprise Policy (organization-wide), Project Memory (./CLAUDE.md), Project Rules (./.claude/rules/*.md), and User Memory (~/.claude/CLAUDE.md). Higher tiers override lower ones.

Does Claude Code automatically read CLAUDE.md?

Yes. Claude Code automatically discovers and loads CLAUDE.md files using recursive discovery - it searches upward to the git root and downward into subtrees. No manual configuration needed. The file is read at session start and when you change directories.

What is the difference between CLAUDE.md and .cursorrules?

CLAUDE.md is for Claude Code (Anthropic's CLI tool) while .cursorrules is for Cursor IDE. CLAUDE.md supports imports (@path syntax), 4-tier hierarchy, and path-specific rules via frontmatter. Both serve similar purposes - project configuration for AI tools. If using both tools, create an AGENTS.md file as a universal fallback.

How long should CLAUDE.md be?

Keep CLAUDE.md focused and scannable. A good target is 200-500 lines for the main file. For larger projects, split rules into .claude/rules/*.md modules. Each rule should be specific and actionable. Claude Code handles long contexts well, but concise rules are easier to maintain.

Can I have a global CLAUDE.md?

Yes. Place a CLAUDE.md file at ~/.claude/CLAUDE.md for user-wide preferences that apply to all projects. This is Tier 4 (lowest priority) and gets overridden by project-specific rules. Use it for personal coding style preferences, not project-specific requirements.

How do imports work in CLAUDE.md?

Use @path/to/file.md syntax to import other markdown files into your CLAUDE.md. This keeps the main file clean while organizing rules into modules. Maximum import depth is 5 hops. Example: @.claude/rules/security.md imports your security rules.

Scan Your Claude Code Projects for Vulnerabilities

CLAUDE.md rules help prevent vulnerabilities, but they can't catch everything. VibeShip Scanner automatically detects SQL injection, XSS, hardcoded secrets, and more in your vibe coded projects.

Scan Your Code Free →

Related content

External resources