You know that feeling when you’re scrolling through a codebase and stumble on a module that looks perfectly fine—imports everywhere, tests passing, code well-structured—but something’s off. It’s dead. Not obviously broken, not throwing errors, just… inactive. A ghost in your architecture.
This happens more often than teams admit. A feature gets deprecated. A refactor pulls functionality somewhere else but leaves the old module as a shell. A flag gets hardcoded to false and nobody revisits it. The code sits there, taking up space in CI, memory in your brain, and risk in your deployments. It looks active because the machinery around it still exists.
Finding these modules manually is brutal. You can grep for imports, but that only tells you the surface story. You need to dig deeper: Is this thing actually called? Is it wrapped in dead flags? Does anything depend on it truly existing?
This is where Claude Code becomes your secret weapon. We’re going to walk through a systematic approach to finding and verifying dead code—the kind of work that usually takes days of human investigation but takes minutes with the right prompts and patterns.
Why Dead Code Matters (More Than You Think)
Before we dive into the how, let’s talk about the why. Dead modules aren’t just clutter.
They’re a cognitive tax. Every developer who touches the codebase has to mentally classify: Is this active? Where does it fit? Why is it here? That’s context-switching noise that compounds across a team. When a junior dev opens a module wondering if it’s deprecated, they spend mental energy that should go to the actual feature they’re building.
They’re a testing burden. If your dead module has tests, you’re running test suites that don’t matter. If it doesn’t, you’re reducing coverage metrics in misleading ways. CI pipelines bloat. A 30-minute test suite that includes 5 minutes of dead code testing is 5 minutes you could shave off feedback loops. In a team running tests 20 times a day, that’s hundreds of minutes of wasted CPU and human waiting time.
They’re a security risk vector. Nobody’s monitoring them for vulnerabilities or outdated dependencies. A dead module with an old package manager dependency? That’s a potential exploit sitting quietly in your repo. You might have updated the active code to patch a critical CVE, but that dead module is running version 3.2.1 from 2019 because nobody thought to update it. Some automated scanner finds it, flags it, and now you have a compliance incident.
They’re migration anchors. When you need to upgrade a framework or refactor architecture, dead modules create false paths and dependencies you have to account for. You’re planning a major migration—maybe upgrading Node.js, or moving from CommonJS to ESM, or replacing an ORM. Dead code makes you ask “does this need to be migrated?” when the answer should have been obvious: delete it.
And here’s the thing: simple grep searches miss them. You can find unused imports, but you can’t easily answer: “What modules are imported but never called?” or “What code is wrapped in permanent kill-switches?” Those questions require pattern analysis across your entire codebase simultaneously. A grep search answers “is this string anywhere?” but not “is this code genuinely executed or is it orphaned?”
That’s exactly what Claude Code is built for.
The Anatomy of Dead Code (Four Categories)
Dead code comes in flavors. Understanding them matters because the detection strategy changes for each. Let me walk you through the types you’ll actually encounter, with real examples.
Category 1: The Unreferenced Module
A module exists but literally nothing imports it. This is the easiest to find but also the trickiest to verify because sometimes a module is imported dynamically (string lookups, plugin systems) and static analysis misses it. You’ve got a file sitting on disk that the entire codebase has moved past.
Example:
src/
payment/
stripe.js # Nobody imports this
paypal.js # Everything uses this
If stripe.js was replaced by paypal.js but never removed, it’s Category 1 dead. The file still exists, it might even compile, but nothing’s calling it. Your tests don’t test it. Your CI doesn’t check it. It’s a phantom limb.
The danger: Someone might wonder if it’s still needed and spend 30 minutes investigating before concluding it’s dead. Multiply that across a large team and you’ve got wasted time. Plus, it clutters your mental model of the codebase.
Category 2: The Imported-But-Unused Module
This one’s devious. Your module is imported, passes the first smell test, but the actual code execution never reaches it. Maybe it’s imported at the top of a file but only used in a code path that never executes in production. Maybe it’s imported inside a comment or a dead conditional. Maybe it was refactored to be unnecessary but someone forgot to remove the import statement.
// app.js
if (DEBUG_MODE) {
// Some code that doesn't actually use legacyProcessor
}
The import looks active. Tests might even pass. But in production? Dead weight. And here’s the trap: an automated import checker sees the import and thinks it’s fine. But the module never executes because the code path is unreachable or because the import statement itself is conditional.
The danger: You ship this code to production. Somewhere down the line, during a refactoring, someone realizes the import exists and wastes cycles investigating before discovering the module is never called.
Category 3: The Flag-Wrapped Module
A module is there, used, but wrapped in a feature flag that’s permanently disabled. Or guarded by a version check that will never be true. This code is actively preventing execution. It’s not just orphaned—it’s actively locked away.
if (FEATURE_FLAG_NEW_ARCHITECTURE) {
// Module is only loaded here
const newSystem = require("./new-system.js");
newSystem.initialize();
}
// FEATURE_FLAG_NEW_ARCHITECTURE is hardcoded to false
The module looks alive—it’s imported, tested, maybe even documented. But the flag says “don’t run me.” Ever. This is surprisingly common. A team starts rolling out a new system incrementally. The flag is initially set to “false” for everyone. Then something goes wrong—performance issues, or a blocking bug. The flag never goes back on. The module sits there, tested, documented, completely bypassed.
The danger: Someone spent weeks building this feature. The code is solid. But it’s forever off. And because the feature flag exists, someone might consider re-enabling it instead of rebuilding from scratch. That’s wasted effort.
Category 4: The Circular-But-Broken Dependency
A module depends on itself indirectly or creates a dependency chain that’s theoretically possible but never actually traversed in real execution. This creates the illusion of interconnectedness while nothing actually flows through it. It’s the codebase equivalent of a road that exists but has no on-ramps.
// A imports B, B imports C, C imports A (circular)
// But the actual execution path never enters A from C
These are especially dangerous because they can cause bundlers to bloat, create false coverage metrics, and break in unpredictable ways when refactoring. Bundlers hate circular dependencies. They slow down your build. They might not break immediately, but they’re ticking time bombs.
The danger: During a dependency upgrade or refactoring, the circular dependency manifests as a strange error that takes hours to track down. You’ll spend time debugging why module A won’t load, only to discover a circular import chain that nobody realized was there.
Phase 1: Surface-Level Analysis with Claude Code
Let’s start with what Claude Code does naturally: exploring your codebase to find the obvious candidates. This is the reconnaissance phase.
The first prompt you should run:
Find all .js modules in src/ that are never imported by any other file.
Return as a list with paths and brief explanation of what each module does.
Claude Code will:
- Scan your directory structure to enumerate all files
- Use Grep to find all imports across files
- Compare module existence against import references
- Surface discrepancies with evidence
Here’s what that looks like in practice. Let’s say you have a Node.js application:
# Get all modules
find src/ -name "*.js" -type f
# For each module, check if it's imported anywhere
grep -r "from.*module-name\|require.*module-name" src/
# Get a list of actual imports across codebase
grep -rh "from ['\"]\|require(['\"]\|import\s*\{" src/ | sort | uniq
Claude Code automates this detective work. You prompt it:
Analyze src/services/
List every .js file that exists but is never referenced by any import statement
in any other file in the project. Show the filepath and first 5 lines of each.
The result? A ranked list of candidates. Some will be legitimate (utility files, re-exports, entry points). Most will be suspicious. This is your hunting ground.
Why this matters: You’ve just identified modules that are structurally orphaned. Nothing is reaching for them. That’s a high-confidence signal that they’re either dead or need to exist for reasons you haven’t documented (external APIs calling them, for example). And unlike a human doing this manually, Claude Code has checked every single file simultaneously. Yeah, automation beats manual work every time.
Phase 2: Tracing Actual Execution Paths
Now we level up. An import existing doesn’t mean code executes. We need to trace execution paths. This is where the investigation becomes sophisticated and truly reveals the hidden dead code.
Here’s a more sophisticated query for Claude Code:
For each module in src/core/, show:
1. Every file that imports it
2. Which functions/exports from the module are actually used
3. Whether those usage sites are themselves reachable from main entry points
Flag any imports where the module is referenced but none of its exports are called.
This requires Claude Code to do semantic analysis across your entire codebase:
- Parse the import statements (what’s actually imported?)
- Match those against what’s exported (do the names exist?)
- Trace calls to those exports (is the code path reachable?)
For a JavaScript/Node project, this looks like:
# Find what a module exports
grep -E "^export|^module.exports" src/mymodule.js
# Find where it's imported
grep -r "import.*mymodule\|require.*mymodule" src/
# For each import location, check if the imports are actually used
grep -A 20 "import.*mymodule" src/somefile.js | grep -E "mymoduleExport|functionName"
Claude Code strings this together automatically and does the analysis across hundreds of files in seconds. You get a report like:
src/controllers/user.js
Imports: UserService.create, UserService.delete
Actually uses: UserService.create only
Status: PARTIALLY_USED
src/middleware/logging.js
Imports: UserService.validateToken
Actually uses: ❌ Never called (imported but not referenced)
Status: DEAD_IMPORT
This is powerful. It catches the “imported at the top of the file but only used in dead code paths” problem. A linter might catch unused variables, but it won’t tell you that an entire imported module is never actually called. Claude Code’s semantic understanding bridges that gap.
Why this matters: You’ve just identified a second tier: code that looks imported but isn’t actually called. This catches the cases where someone did import { fn } from 'module' but then never uses fn anywhere in the file, or uses it only in commented-out code or unreachable branches.
Phase 3: Feature Flag Analysis (The Sneaky Ones)
Feature flags are powerful for gradual rollouts, but they’re also where a lot of dead code hides. A flag can be set to false and nobody touches it for years while the guarded code rots. This is where the truly hidden dead code lives—code that compiles, has tests, is documented, but will never run.
This query gets Claude Code to hunt them:
Find all feature flag references in src/
For each flag:
1. Where is it defined? (config file, env var, hardcoded)
2. What code does it guard?
3. What is its current value?
4. When was it last changed?
Flag any guards where the condition is permanently false or the flag is undefined.
In practice, this means:
# Find all flag references
grep -rn "if.*FLAG\|if.*FEATURE\|if.*DEBUG\|if.*ENABLED" src/
# For each flag, get context
grep -B 2 -A 10 "FLAG_NAME" src/somefile.js
# Check config files
cat config.js | grep FLAG
cat .env | grep FLAG
cat .env.example | grep FLAG
Claude Code automates the matching and flagging. It correlates where flags are defined, where they’re used, and what their current state is. You get a report:
FLAG_NEW_PAYMENT_SYSTEM
Defined in: src/config.js
Current value: false (PERMANENT - unchanged since 2022)
Guards: src/payment/new-system.js (entire module)
Recommendation: Dead code - consider archiving
FEATURE_EXPERIMENTAL_CACHING
Defined in: environment variable
Current value: undefined (defaults to false)
Guards: src/cache/redis-experimental.js
Recommendation: Investigate - undefined flags are risky
This is critical information. A flag that’s been false for three years is a sign that the code behind it will never run. It’s actively held back. This is where dead code feels most alive but is completely unreachable.
Why this matters: You’ve now found the category of dead code that looks active but is genuinely unreachable. It’ll never run unless someone explicitly enables it, which hasn’t happened. This is massive cleanup potential. And critically, you can recommend to your team: either enable this feature (decision required) or remove it (straightforward cleanup).
Phase 4: Dependency Scanning and Build Verification
Here’s where things get interesting. Even if code looks dead, you need to verify that removing it won’t break anything. This is the safety gate before deletion.
This query puts Claude Code into verification mode:
For the following modules marked as dead:
1. Check if they're listed in package.json dependencies
2. Run the build process with them removed (safely, in a test)
3. Check if any tests explicitly import them
4. Check if any external API contracts reference them
List any blockers that would prevent safe removal.
Practically speaking:
# Check if a module is a direct dependency
grep "module-name" package.json
# Check if it's imported by tests
grep -r "module-name" __tests__/ test/
# List what depends on it (advanced)
grep -r "from.*module-name\|require.*module-name" . --include="*.js" | wc -l
# See if it has CI configuration
cat .github/workflows/ci.yml | grep -i "module-name"
Claude Code connects these dots rapidly and comprehensively. You get clarity on whether a module:
- Is actively tested (signs of genuine life)
- Has external dependencies (removing it might cascade failures)
- Is part of the build contract (CI might explicitly check for it)
- Is embedded in configuration or deployment scripts
Why this matters: You can now answer “Is it safe to delete?” with high confidence. No surprised regressions. No “we deleted it and production broke” moments. This is the critical gate before cleanup that prevents chaos.
Phase 5: The Removal Checklist and Verification
Once you’ve identified dead modules and verified they’re truly unreachable, removal follows a pattern. Claude Code helps here too by automating the verification steps.
Before removing a dead module, verify:
# 1. No imports anywhere
grep -r "from.*module-name\|require.*module-name" . --include="*.js" && echo "FAIL: Still imported" || echo "PASS: No imports"
# 2. No test references
grep -r "module-name" __tests__/ test/ && echo "FAIL: Tests reference it" || echo "PASS: No test refs"
# 3. No documentation references
grep -r "module-name" docs/ README.md && echo "FAIL: Documented" || echo "PASS: Not documented"
# 4. No CI/build pipeline references
grep -r "module-name" .github/ .gitlab-ci.yml .travis.yml && echo "FAIL: CI references it" || echo "PASS: Not in CI"
# 5. Build passes without it
rm -rf src/module-name && npm run build && echo "PASS: Build succeeds" || echo "FAIL: Build broken"
# 6. Tests pass without it
npm test && echo "PASS: Tests pass" || echo "FAIL: Tests fail"
Use Claude Code to run these checks systematically:
Before I delete src/legacy-processor/, verify:
1. It's not imported anywhere
2. Tests don't reference it
3. Build still passes
4. Test suite still passes
5. Show me the command outputs proving each point
Only say "safe to delete" if all checks pass.
Claude Code will run the checks, show you the evidence line by line, and give you a thumbs-up or identify blockers. This is not hypothetical—you get actual command outputs proving each assertion.
Why this matters: You move from theory to evidence. No surprises. No “oops, that was used” moments at 2 AM when something breaks. You have concrete proof that removal is safe before you commit.
Real-World Scenario: The Monorepo Hunt
Let’s walk through a realistic example. You’ve got a Node.js monorepo with multiple services. You suspect dead modules but don’t know where to start. Here’s how Claude Code transforms this from “I have no idea where to begin” to “here’s exactly what’s dead.”
Step 1: Get the lay of the land
Analyze the src/ directory structure.
For each subdirectory (services, controllers, utils, middleware):
1. Count total .js files
2. List the 5 largest files
3. List any files modified >2 years ago
Show me where the oldest, largest code clusters are (dead code tends to live there).
Claude Code scans and reports something like:
src/services/
Total files: 23
Largest: analytics-aggregator.js (2,100 lines)
Oldest: legacy-auth.js (modified 2022-03-15)
src/utils/
Total files: 41
Largest: date-formatter.js (850 lines)
Oldest: xml-parser.js (modified 2021-11-03)
src/middleware/
Total files: 8
Largest: request-logger.js (500 lines)
Oldest: deprecated-cors.js (modified 2020-08-12)
Suspicious areas light up immediately: legacy-auth, xml-parser, deprecated-cors. These are hunting grounds. You now have data-driven intuition for where to focus.
Step 2: Deep dive on suspicious modules
For src/utils/xml-parser.js:
1. Show me the full file
2. List every import of it across the codebase
3. For each import, show the context (5 lines before/after)
4. Does anything actually call the exported functions?
You might discover:
src/utils/xml-parser.js is imported by:
- src/middleware/request-logger.js (line 3)
Context: import xmlParser from './xml-parser'
Usage: Never called
- src/services/legacy-edi.js (line 2)
Context: import { parseXML } from '../utils/xml-parser'
Usage: Called in processEDIFile() - which itself is flag-wrapped and never executed
Now you have specificity. The module is imported but not used. And it’s only “used” in flag-wrapped code that never runs. That’s Category 2 + Category 3 dead code combined.
Step 3: Verify removal safety
Verify that src/utils/xml-parser.js can be safely deleted:
1. Run grep to confirm no other references exist
2. Run npm test and show that all tests pass
3. Run npm run build and show that build succeeds
4. List any dependencies xml-parser.js has (so we know what we're freeing)
Claude Code shows the evidence. You now know the true status with confidence. You can see the test output, the build output, everything. You’re not guessing—you have proof.
Building Your Dead Code Report
Once you’ve systematically hunted, consolidate findings into a report. Claude Code can help format this and ensure nothing falls through the cracks:
DEAD CODE AUDIT - [Date]
CATEGORY 1: Unreferenced Modules (Safe to delete immediately)
- src/legacy-stripe-integration.js
- src/utils/old-date-formatter.js
Estimated impact: Remove 2,400 lines, free 2 dependencies
CATEGORY 2: Imported but Unused (Verify then delete)
- src/cache/memory-cache.js (imported by request-logger, never called)
- src/validators/email-legacy.js (imported by registration, replaced by new-validator)
Estimated impact: Remove 800 lines, reduces test burden
CATEGORY 3: Flag-Wrapped (Disable flag, then clean)
- src/features/experimental-search (guarded by FEATURE_NEW_SEARCH = false)
- src/systems/kafka-queue (guarded by FEATURE_QUEUE_V2 = false)
Estimated impact: Simplify conditional logic, remove 3,200 lines
CATEGORY 4: Risky/Uncertain (Investigate manually)
- src/middleware/custom-cors (has external dependency, might be used by external clients)
- src/services/payment-gateway (circular dependency with controllers)
ACTION PLAN:
Week 1: Verify Category 1, delete if tests pass
Week 2: Audit Category 2, delete with removal of imports
Week 3: Evaluate feature flags, plan migration path
Month 2: Deep dive on Category 4 with team review
This becomes your cleanup roadmap. You’ve gone from “something feels off” to “here’s exactly what to do.” You have evidence for each finding and a clear path forward.
The Business Impact of Dead Code
Before we wrap up, it’s worth understanding the true cost of leaving dead modules in your codebase. It’s not just about cleanliness or code review complexity. There’s real business impact.
Compliance and security audits treat dead code as a risk. If you have deprecated authentication code lying around, even if it’s not being called, an auditor flags it as a vulnerability. You’re maintaining code that could theoretically be exploited. That’s a finding you have to remediate, which means time, effort, and potentially regulatory consequences.
Onboarding friction is real. A new developer joins your team. They’re trying to understand the authentication system. They find three different auth modules. Are they all active? Do they all work? Which one should I use? That’s 30 minutes of confusion that could have been prevented with cleanup. Multiply that across ten new hires a year, and you’ve lost 5 hours of productivity.
Refactoring friction compounds over time. You’re planning to upgrade your database layer. You need to touch all database-dependent code. But you’ve got 40 dead modules that claim to use the database. Do they? Can you remove them? That uncertainty creates caution. You refactor conservatively instead of boldly. Your migration takes three weeks instead of two because you’re second-guessing yourself about what’s actually in use.
Testing burden is often invisible. You run your full test suite. It takes 45 minutes. But 8 minutes of that is testing dead modules. Nobody realizes it because the tests run in the background. But 8 minutes × 20 developers × 5 test runs per day = 1,600 minutes of wasted CPU time daily. Over a year, that’s 600+ hours of computer time (or human waiting time) spent testing code that doesn’t matter.
Dependency overhead accumulates. A dead module imports an old library. That library has a vulnerability. So you have to keep that library updated, even though nothing is using it. You’re maintaining something that provides zero value.
The cleanup we’ve described using Claude Code directly addresses all of these. It’s not just nice-to-have. It’s a business optimization.
Building a Continuous Dead Code Detection Process
The real leverage comes from making this a continuous process, not a one-time audit. Here’s how mature teams approach it:
Automated nightly scans: Your CI pipeline runs a dead code detector every night. It flags any modules that are:
- Unreferenced by anything else
- Behind disabled feature flags
- Haven’t been modified in 6+ months
- Imported but not used
Weekly reports: On Monday morning, the team gets an email: “12 potential dead modules found this week. 3 are ready for immediate removal.” This keeps the issue visible.
Quarterly deep dives: Every three months, the team blocks a day to investigate and remove flagged modules. It’s a scheduled, predictable maintenance task instead of something that never gets done.
Incentive alignment: Some teams make dead code removal part of their definition of done. “If you’re refactoring authentication, you’re also responsible for removing any dead authentication modules.” This distributes the cleanup work across many small PRs instead of requiring a huge refactoring project.
Wrapping Up
Dead code is the architectural equivalent of leaving dishes in the sink. It’s not catastrophic, but it adds up. Every developer who scrolls past that dead module pays a tiny cognitive tax. Every test suite takes 100 milliseconds longer. Every CI job runs 2% slower. Every deployment feels slightly more risky because you’re not sure if something depends on the code you’re changing. It compounds.
Claude Code changes the game here because it does something humans struggle with: holding the entire codebase structure in mind simultaneously and spotting the patterns that signal death. A module with no inbound imports. An export that’s never called. A flag that’s permanently off. A feature that’s imported but unreachable.
The strategy is simple:
- Surface: Find structurally orphaned modules using static analysis
- Trace: Follow execution paths to verify usage patterns
- Flag: Identify permanent kill-switches and dead conditions
- Verify: Test that removal is safe with comprehensive checks
- Clean: Remove with confidence and measure the impact
Use Claude Code for steps 1-3. Combine with your own testing and judgment for steps 4-5. You’re not automating judgment; you’re automating investigation.
Your codebase will be cleaner, faster, and easier to reason about. Your CI pipelines will be simpler. Your team will spend less time wondering “what does this do?” and more time building. Code reviews will be faster because there’s less code to review. Onboarding will be easier because new developers won’t have to wonder about mysterious modules.
Start small. Pick one suspicious module. Use Claude Code to trace it. Verify removal safety. Delete it. Feel the relief. Then scale the pattern.
Your future self—the one reviewing this code in 6 months—will thank you.
-iNet