The gap between ad-hoc prompting and structured Claude Code workflows shows up as inconsistent outputs and manual rework on every iteration. This guide provides a structured taxonomy of CLAUDE.md best practices and five repeatable workflow patterns built around them.
Table of Contents
Why Workflow Patterns Matter for Claude Code
The gap between ad-hoc prompting and structured Claude Code workflows shows up as inconsistent outputs and manual rework on every iteration. Developers who treat Claude Code as an interactive chatbot rather than a configurable development tool routinely encounter hallucinated imports, ignored project conventions, and outputs that require line-by-line correction. Claude Code workflow patterns, anchored by well-crafted CLAUDE.md configuration, transform this dynamic by giving the agent persistent, project-aware context it can reference across every session.
This guide provides a structured taxonomy of CLAUDE.md best practices and five repeatable workflow patterns built around them. It targets intermediate developers already comfortable with CLI tools and AI-assisted coding who want to move past trial-and-error into deliberate, reproducible workflows using a JavaScript and Node.js stack.
Version note: Claude Code’s behavior around session management, CLAUDE.md loading, and the
Prerequisites
Before following the patterns in this guide, ensure you have:
- Claude Code CLI installed and available on your system PATH. Run
claude --versionto confirm. - Node.js ≥20 LTS and npm ≥8.x installed (verify with
node --versionandnpm --version). - Claude Code authenticated for your environment. In CI or non-interactive environments (no TTY), configure authentication before invoking
claude; see the official documentation for non-interactive authentication methods. - Bash ≥4.0 available via
#!/usr/bin/env bash. On macOS, the default Bash is version 3.2; the shell scripts in this guide require Bash 4.0+ for reliabletrap ERRbehavior. Install a newer version via Homebrew (brew install bash) if needed. - A
package.jsonwith the npm scripts referenced in this guide (test,lint,build,dev,db:migrate) defined for your project.
What Is CLAUDE.md and Why It’s the Foundation of Every Workflow
How CLAUDE.md Shapes Claude Code’s Behavior
CLAUDE.md is a Markdown file that functions as a project-level instruction set for Claude Code. Unlike ephemeral system prompts that vanish between sessions, CLAUDE.md persists in the repository. Claude Code reads it at the start of every session, picking up the project’s tech stack, coding conventions, preferred commands, and behavioral constraints. The result: Claude Code operates with a baseline understanding of the project without the developer re-explaining fundamentals each time.
Claude Code reads the file before processing any user prompt, shaping how it interprets and responds to every subsequent instruction within that project.
Claude Code workflow patterns, anchored by well-crafted CLAUDE.md configuration, transform this dynamic by giving the agent persistent, project-aware context it can reference across every session.
The Three Scopes of CLAUDE.md
CLAUDE.md supports three distinct scopes. A project-level CLAUDE.md sits at the repository root and applies globally to all interactions within that project. Directory-level CLAUDE.md files can be nested inside subpackages or modules, allowing different conventions for different parts of a monorepo. A user-level file at ~/.claude/CLAUDE.md sets personal defaults that apply across all projects, useful for preferences like preferred response verbosity or general coding style.
When multiple scopes exist, they layer together. Directory-level files supplement (rather than replace) the root-level configuration, and user-level defaults yield to project-specific directives. In cases of conflict, consult the official Claude Code documentation for the precedence rules that apply to your version.
# CLAUDE.md
## Tech Stack
- Runtime: Node.js 20 LTS
- Framework: Express 4.x
- Language: JavaScript (ES2022+)
## Style
- Use named exports exclusively
- Prefer async/await over raw Promises
## Commands
- Run tests: `npm test`
CLAUDE.md Best Practices: What to Include
Project Context and Tech Stack Declaration
Declaring the runtime, framework, and key dependencies explicitly in CLAUDE.md reduces one of the most common failure modes: hallucinated imports and version-mismatched API usage. When Claude Code knows the project uses Express 4.x rather than 5.x, it avoids suggesting APIs that do not exist in the installed version. The same applies to specifying Node.js version constraints, database drivers, and ORM versions.
Beyond dependencies, a brief project structure overview helps Claude Code understand where to place new files and how existing modules relate to each other.
# CLAUDE.md
## Project Overview
E-commerce REST API serving a React frontend.
## Tech Stack
# Replace all version numbers below with your project's actual installed versions
- Runtime: Node.js 20.11 LTS
- Framework: Express 4.18.2
- Database: PostgreSQL 15 via `pg` 8.11
- ORM: None — raw SQL with parameterized queries
- Auth: `jsonwebtoken` 9.0, `bcrypt` 5.1
## Project Structure
- `src/routes/` — Express route handlers
- `src/middleware/` — Auth, validation, error handling
- `src/db/` — Database queries and connection pool
- `tests/` — Jest test files mirroring `src/` structure
Coding Conventions and Style Rules
Rather than duplicating every ESLint or Prettier rule, CLAUDE.md should reference existing configuration files and highlight conventions that static analysis tools do not enforce. This includes architectural patterns (such as always using a service layer between routes and database queries), error handling strategies (like wrapping async route handlers in a centralized error wrapper), and naming conventions for files and functions.
Command References and Build Scripts
Providing the exact commands Claude Code can invoke removes guesswork. When shell execution is enabled, Claude Code can run these commands directly; see the official documentation for how to configure and restrict permitted commands before enabling this capability. Listing test, build, lint, and deploy commands ensures it runs the right toolchain.
## Commands
- Test all: `npm test`
- Test single file: `npm test -- --testPathPattern='routes/orders'`
# Accepts a regex matched against the full file path.
# Replace 'routes/orders' with your target path segment.
- Lint: `npm run lint`
- Lint fix: `npm run lint:fix`
- Dev server: `npm run dev`
- Build: `npm run build`
- DB migrate: `npm run db:migrate`
Note: --testPathPattern accepts a regex matched against the full file path, not a literal filename. For example, --testPathPattern='routes/orders' will match any test file whose path contains routes/orders.
Behavioral Guardrails
Guardrails define what Claude Code should never do autonomously. These are critical for preventing destructive operations. Examples include directives like “never modify package-lock.json directly,” “do not delete or overwrite migration files,” and “always write tests before implementation.” Guardrails also set scope boundaries, such as “do not make changes outside the src/ directory without explicit approval.”
CLAUDE.md Anti-Patterns: What to Exclude
Overly Verbose Instructions
Excessively long CLAUDE.md files reduce the context available for your actual prompts. Every token Claude Code spends reading bloated instructions is a token it cannot spend on your code. The goal is density: maximum useful signal in minimum token count.
Contradictory or Redundant Directives
Conflicting style rules, such as one section demanding semicolons and another section showing examples without them, produce inconsistent outputs. Similarly, re-specifying rules already enforced by tsconfig.json, .eslintrc, or .prettierrc wastes context space and creates drift when those config files are updated but CLAUDE.md is not.
Secrets, Credentials, and Environment-Specific Values
CLAUDE.md is typically committed to version control, making it visible to all team members and third-party code scanning tools. Including API keys, database connection strings, or other secrets creates a security vulnerability. Instead, reference .env patterns and instruct Claude Code to use environment variables.
Here is a bloated CLAUDE.md section refactored into a concise version:
# ❌ Before — Bloated
## Database
We use PostgreSQL.
Connection string format: postgres://<user>:<password>@<host>:<port>/<dbname>
# Never embed real credentials — use environment variables only
Always use PostgreSQL. Do not use MySQL. Do not use SQLite. Do not use MongoDB.
When writing queries, always use parameterized queries. Never use string
concatenation for queries. This is very important. String concatenation is
dangerous because of SQL injection attacks which can compromise the database...
[continues for 200 more words]
# ✅ After — Concise
## Database
- PostgreSQL 15 via `pg` 8.11
- Connection config: see `.env` and `src/db/pool.js`
- Always use parameterized queries — no string concatenation
Five Practical Workflow Patterns for Everyday Development
Pattern 1: The Feature Implementation Workflow
This pattern structures feature development as a sequential chain: specification, scaffold, implement, test, review. Defining the expected output format for each step in CLAUDE.md prevents Claude Code from jumping ahead or producing incomplete artifacts.
## Workflow: Feature Implementation
### Steps
1. **Spec**: Summarize the feature requirements in a bullet list. Do not write code yet.
2. **Scaffold**: Create file stubs with exported function signatures and JSDoc comments only.
3. **Implement**: Fill in the function bodies. Follow patterns in existing `src/routes/` handlers.
4. **Test**: Write Jest tests covering happy path, error cases, and edge cases.
5. **Review**: Self-review against the Review Checklist below. List any concerns.
### Output Format
- Each step must be completed and confirmed before proceeding to the next.
- Tests must pass (`npm test`) before the Review step.
A sample prompt invoking this workflow for a JavaScript REST endpoint:
Follow the Feature Implementation workflow. The feature: a GET /api/products/:id
endpoint that returns a single product by ID from the products table. Return 404
with { error: "Product not found" } if the ID doesn't exist. Include input
validation for the ID parameter.
Pattern 2: The Bug Triage and Fix Workflow
Rather than pasting a stack trace and asking “fix this,” a structured bug workflow provides reproduction steps, relevant log output, expected versus actual behavior, and the file(s) likely involved. A CLAUDE.md directive enforcing “diagnose before fixing” prevents Claude Code from immediately rewriting code before understanding root cause:
## Workflow: Bug Triage
When given a bug report, first explain the probable cause and affected code paths.
Do not modify files until you confirm the diagnosis.
Pattern 3: The Code Review and Refactor Workflow
Instructing Claude Code to analyze code against project conventions before suggesting changes produces reviews that catch more convention violations and flag missing test coverage. A review checklist section in CLAUDE.md gives Claude Code a concrete rubric to evaluate against, and limiting the scope of autonomous refactors prevents sprawling changes that are difficult to review.
## Review Checklist
When reviewing code, check each item and report pass/fail:
- [ ] Named exports used (no default exports)
- [ ] Async route handlers wrapped in `asyncHandler` middleware (using `express-async-handler` or an equivalent wrapper)
- [ ] Input validation present for all request parameters
- [ ] Database queries use parameterized placeholders
- [ ] Error responses follow `{ error: string }` format
- [ ] Corresponding test file exists and covers error cases
- [ ] No hardcoded configuration values — use `process.env`
A sample review prompt paired with this checklist:
Review src/routes/orders.js against the Review Checklist. Report each item as
pass or fail with a one-line explanation. Then suggest specific fixes for any failures.
Pattern 4: The Test Generation Workflow
Defining the test framework, assertion style, and coverage expectations in CLAUDE.md standardizes generated tests. Directives should specify: “Use Jest with expect assertions. Group tests with describe blocks per function. Include at least one test for the happy path, one for invalid input, and one for error propagation.”
Point Claude Code at an existing implementation file and ask it to generate the corresponding test file following these constraints:
Generate a Jest test file for src/routes/orders.js. Follow the test conventions
in CLAUDE.md. Cover the happy path, one invalid-input case, and one error
propagation case. Output only the test file.
Patterns 4 and 5 are intentionally shorter than Patterns 1-3. They require fewer CLAUDE.md directives because the workflow itself is simpler: one input file, one output file, one pass.
Pattern 5: The Documentation Workflow
CLAUDE.md can set documentation standards such as JSDoc format for all exported functions, README structure conventions, and changelog entry format. A documentation workflow pattern instructs Claude Code to generate or update JSDoc comments for modified files, produce API documentation from route handler signatures, and append changelog entries using a keep-a-changelog format. Explicit output format expectations make this work: “Each JSDoc comment must include @param with type annotations, @returns, and @throws.”
Update JSDoc comments for all exported functions in src/routes/orders.js.
Each comment must include @param with type, @returns, and @throws. Do not
modify function bodies.
Composing Workflows: Chaining Patterns with Claude Code
Session Continuity and Multi-Step Orchestration
Claude Code’s session management allows chaining the five patterns into a full feature delivery cycle: implement, then test, then review, then document, all within a persistent context that references the same project conventions throughout.
The practical constraint is context window size. After 3-4 chained steps, accumulated code output can crowd out the working context. Break chains at natural boundaries (after tests pass, for instance) and resume in a new session for a pragmatic balance between continuity and available context.
Every token Claude Code spends reading bloated instructions is a token it cannot spend on your code. The goal is density: maximum useful signal in minimum token count.
Using Shell Scripts to Automate Workflow Sequences
For CI pipelines and repeatable workflows, wrapping Claude Code invocations in shell scripts using the --print flag (which outputs results to stdout without interactive mode) enables automation. In CI environments, ensure Claude Code is authenticated using the appropriate non-interactive method before invoking this flag; see the official documentation for details.
#!/usr/bin/env bash
set -euo pipefail
if [[ "${BASH_VERSINFO[0]}" -lt 4 ]]; then
echo "Error: Bash >= 4.0 required. Current: ${BASH_VERSION}" >&2
echo "On macOS, install via: brew install bash" >&2
exit 1
fi
CURRENT_STEP="init"
trap 'echo "Workflow failed at step: ${CURRENT_STEP}" >&2' ERR
mkdir -p output || { echo "Cannot create output/ directory." >&2; exit 1; }
FEATURE_DESC="${1:-}"
if [[ -z "${FEATURE_DESC}" ]]; then
echo "Usage: $0 ''" >&2
exit 1
fi
if [[ ${#FEATURE_DESC} -gt 500 ]]; then
echo "Error: Feature description exceeds 500 characters." >&2
exit 1
fi
if [[ "${FEATURE_DESC}" =~ [\`\$\;\|\&\<\>] ]]; then
echo "Error: Feature description contains disallowed characters." >&2
exit 1
fi
CURRENT_STEP="1: Implement"
echo "=== Step 1: Implement ==="
timeout 300 claude --print \
"Follow the Feature Implementation workflow for: ${FEATURE_DESC}" \
> output/implement.md
CURRENT_STEP="2: Run Tests"
echo "=== Step 2: Run Tests ==="
npm test 2>&1 | tee output/test.log
CURRENT_STEP="3: Review"
echo "=== Step 3: Review ==="
timeout 300 claude --print \
"Review all files modified in the last commit against the Review Checklist" \
> output/review.md
echo "=== Done ==="
echo "Implementation : output/implement.md"
echo "Test log : output/test.log"
echo "Review : output/review.md"
Note: The timeout command is from GNU coreutils (available by default on Linux; on macOS install via brew install coreutils and use gtimeout). Ensure the output/ directory is listed in your .gitignore to avoid accidentally committing generated artifacts.
Register this script as an npm script ("workflow:feature": "bash scripts/feature-workflow.sh") for team-wide consistency.
Implementation Checklist
| Task | |
|---|---|
| ☐ | Create root-level CLAUDE.md with tech stack and project structure |
| ☐ | Add coding conventions section or reference existing config files |
| ☐ | Define common commands (test, build, lint, deploy) |
| ☐ | Set behavioral guardrails with explicit do’s and don’ts |
| ☐ | Remove secrets, redundancies, and contradictions |
| ☐ | Add workflow-specific sections for your most common tasks |
| ☐ | Create directory-level CLAUDE.md files for complex monorepos |
| ☐ | Set up user-level ~/.claude/CLAUDE.md for personal defaults |
| ☐ | Test workflows with --print flag before interactive use |
| ☐ | Schedule quarterly reviews to trim CLAUDE.md and prevent bloat |
Building Your Own Pattern Library
Start with a single workflow pattern and iterate. The feature implementation workflow is a natural starting point because it touches the most common development activity and exposes gaps in CLAUDE.md configuration quickly.
CLAUDE.md is a living document. It belongs in version control, should be reviewed in pull requests alongside code changes, and benefits from periodic trimming as the project evolves and earlier directives become obsolete. The implementation checklist above works as both a starting point and a recurring audit tool.
Claude Code’s capabilities continue to expand, with improvements to context handling, tool use, and multi-file editing arriving in successive releases. Workflow patterns that are explicit and modular today will adapt cleanly to those changes. Tightly coupled or overly rigid configurations will need rework.

