> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Duplication Detection

> Audit of an Express login demo identifying code duplication patterns and providing refactors, utilities, and centralized config examples to reduce repetition and improve error handling.

We audited an Express Login demo to identify duplicated code patterns and suggest practical refactors. This lesson digs deeper into exact duplicates, near-duplicates, structural repetition, and repeated data/constants — and gives concrete code you can drop into the repo to reduce duplication and centralize behavior.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/Xs8Ruv7b0QCZf7iM/images/Claude-Code-for-Beginners/Code-Review-with-Claude-Code/Code-Duplication-Detection/code-duplication-detection-demo-slide.jpg?fit=max&auto=format&n=Xs8Ruv7b0QCZf7iM&q=85&s=708822c85901c8e2b168723170e6fdbd" alt="A presentation slide titled &#x22;Code Duplication Detection&#x22; with a large dark curved shape on the right displaying the word &#x22;Demo.&#x22; The slide also shows a small &#x22;© Copyright KodeKloud&#x22; notice in the bottom-left." width="1920" height="1080" data-path="images/Claude-Code-for-Beginners/Code-Review-with-Claude-Code/Code-Duplication-Detection/code-duplication-detection-demo-slide.jpg" />
</Frame>

The audit begins by prompting Claude Code for Beginners to scan the repository and produce a structured report. Example of the interactive prompt and initial output:

```text theme={null}
* Welcome to Claude Code!

/help for help, /status for your current setup

cwd: /Users/jeremy/Repos/Claude Code Course/Express-login-demo

> [Pasted text #1 +47 lines]
```

Claude enumerates files and reads content:

```text theme={null}
• Read(config/database.js)
└ Read 19 lines (ctrl+r to expand)

• Read(package.json)
└ Read 25 lines (ctrl+r to expand)

• Read(schema.sql)
└ Read 22 lines (ctrl+r to expand)

• List(~/Repos/Claude Code Course/Express-login-demo)
└ Listed 32 paths (ctrl+r to expand)

• Read(examples.md)
└ Read 3 lines (ctrl+r to expand)

• Write(audits/CODE_DUPLICATION_ANALYSIS.md)
└ Wrote 276 lines to audits/CODE_DUPLICATION_ANALYSIS.md
```

Below is a cleaned, consolidated Code Duplication Analysis Report with key findings, recommended remediation, and copy-paste-ready code examples to centralize shared logic and configuration.

## Executive summary

This analysis targets duplication across the small Express.js app. Overall the codebase follows DRY principles, but several low- to medium-effort improvements will pay off as the project grows:

* Centralize environment-derived configuration (high priority)
* Consolidate error response formatting (medium)
* Abstract database error mapping/handling (medium)
* Extract constants for consistency (low)

Estimated refactor time: \~3–4 hours.

## Scope & methodology

Files inspected:

* `server.js`
* `routes/auth.js`
* `config/database.js`
* `package.json`
* `schema.sql`
* Additional small files in the repo

Approach:

* Identify exact and near-duplicates
* Look for repeated data (env variables, constants)
* Propose utility modules and constants to centralize logic

## Findings at a glance

| Duplication Type | Severity | Location | Example Pattern | Recommended Remediation | Effort |
| - | - | - | - | - | - |
| Exact duplicates | 1/10 | — | No exact file copies | N/A — keep monitoring | Very low |
| Near duplicates | 3/10 | `routes/auth.js` | Repeated `res.status(...).json({ error: '...' })` | `utils/createErrorResponse` | Low (\~30 min) |
| DB error handling duplicates | 3/10 | `routes/auth.js` | Repeated switch/if handling DB error codes | `utils/handleDatabaseError` + `DB_ERROR_MAP` | Medium (\~1 hr) |
| Structural duplicates | 2/10 | Routers/DB connections | Repeated router or connection boilerplate | Router factory / connection factory (future) | Low–Medium |
| Data duplication (env) | 4/10 | Scattered across files | `process.env.*` repeated | `config/index.js` central config | Low–Medium (\~45 min) |

## Detailed findings & remediation

### 1) Exact duplicates

Severity: 1/10 — none found. Great.

### 2) Near duplicates — repeated error responses

Location: `routes/auth.js` (multiple endpoints)

Common duplicated pattern:

```javascript theme={null}
// Pattern repeated multiple times with small variations
return res.status(STATUS_CODE).json({
  error: 'MESSAGE'
});
```

Remediation: centralize error responses in a small utility so all routes return the same structure and can optionally include `details`.

Suggested implementation:

```javascript theme={null}
// utils/index.js
function createErrorResponse(res, statusCode, message, details = null) {
  const response = { error: message };
  if (details) response.details = details;
  return res.status(statusCode).json(response);
}

// Usage in a route
createErrorResponse(res, 401, 'Invalid credentials');
createErrorResponse(res, 400, 'Validation failed', errors.array());
```

Effort: Low (≈30 minutes)

### 3) Database error handling pattern

Location: `routes/auth.js` (error handlers after DB calls)

Pattern: repeated switch/case or if/else blocks mapping DB error codes to responses.

Remediation: create a DB error map and a handler function that delegates to `createErrorResponse`.

Example:

```javascript theme={null}
// utils/index.js (excerpt)
const DB_ERROR_MAP = {
  'ECONNREFUSED': { status: 503, message: 'Database connection failed' },
  '28P01': { status: 503, message: 'Database authentication failed' },
  '3D000': { status: 503, message: 'Database does not exist' }
};

function handleDatabaseError(error, res) {
  const errorInfo = DB_ERROR_MAP[error.code];
  if (errorInfo) {
    return createErrorResponse(res, errorInfo.status, errorInfo.message);
  }
  return createErrorResponse(res, 500, 'Database error occurred');
}
```

Effort: Medium (≈1 hour). Extensible: add additional DB vendor codes or map SQLState codes for more granularity.

### 4) Structural duplicates

Severity: 2/10 — router and connection setup patterns are repeated but consistent.

Remediation: when the codebase grows, consider:

* Router factory functions to reduce boilerplate across many routes.
* Database connection factory to manage multiple connection pools.

### 5) Data duplication — environment variables and config values

Severity: 4/10 — `process.env.*` scattered in multiple files.

Remediation: centralize env and derived configuration into `config/index.js`. This makes it easy to add validation (e.g., using `envalid` or `joi`) and to mock in tests.

Suggested file:

```javascript theme={null}
// config/index.js
module.exports = {
  server: {
    port: process.env.PORT || 3000
  },
  database: {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    name: process.env.DB_NAME,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD
  },
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: process.env.JWT_EXPIRES_IN || '24h'
  }
};
```

Effort: Low–Medium (≈45 minutes)

## Recommended utilities and constants

Add the following core files to centralize behavior and make refactors low-risk.

1. utils/index.js — central error and validation handlers

```javascript theme={null}
// utils/index.js
const { HTTP_STATUS } = require('../constants'); // adjust path as needed

function createErrorResponse(res, statusCode, message, details = null) {
  const response = { error: message };
  if (details) response.details = details;
  return res.status(statusCode).json(response);
}

const DB_ERROR_MAP = {
  'ECONNREFUSED': { status: HTTP_STATUS.SERVICE_UNAVAILABLE, message: 'Database connection failed' },
  '28P01': { status: HTTP_STATUS.SERVICE_UNAVAILABLE, message: 'Database authentication failed' },
  '3D000': { status: HTTP_STATUS.SERVICE_UNAVAILABLE, message: 'Database does not exist' }
};

function handleDatabaseError(error, res) {
  const errorInfo = DB_ERROR_MAP[error.code];
  if (errorInfo) {
    return createErrorResponse(res, errorInfo.status, errorInfo.message);
  }
  return createErrorResponse(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Database error occurred');
}

function handleValidationErrors(errors, res) {
  if (!errors.isEmpty()) {
    return createErrorResponse(res, HTTP_STATUS.BAD_REQUEST, 'Validation failed', errors.array());
  }
  return null;
}

module.exports = {
  createErrorResponse,
  handleDatabaseError,
  handleValidationErrors
};
```

2. constants/index.js — central constants

```javascript theme={null}
// constants/index.js
const HTTP_STATUS = {
  OK: 200,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  INTERNAL_SERVER_ERROR: 500,
  SERVICE_UNAVAILABLE: 503
};

module.exports = {
  HTTP_STATUS
};
```

3. config/index.js — central configuration (already shown above)

## Implementation priority

| Priority | Item | Rationale |
| - | - | - |
| High | Centralize environment variables → `config/index.js` | Prevents env spread, simplifies testing and secrets management |
| Medium | Create error response utilities → `utils/index.js` | Unifies response format and reduces repetitive code |
| Medium | Create DB error handler + map → `utils/index.js` | Centralizes DB error-to-response mapping |
| Low | Extract constants → `constants/index.js` | Improves consistency and avoids magic numbers |

## Summary & estimates

* Overall Duplication Score: 2.5/10 — Very Low
* Total Estimated Refactoring Effort: \~3–4 hours
* Files to update: `routes/auth.js`, `config/database.js`, `server.js`
* New files: `utils/index.js`, `constants/index.js`, `config/index.js`

These changes will make the codebase easier to maintain, reduce future duplication, and provide consistent behavior across routes and error handling.

<Callout icon="lightbulb" color="#1CB2FE">
  Centralizing configuration and error handling reduces future duplication and makes updates (like changing response formats or adding DB error mappings) quick and low-risk.
</Callout>

<Callout icon="warning" color="#FF6B6B">
  Do not commit secrets to source control. Keep `JWT_SECRET`, DB passwords, and other sensitive values in environment variables, a secrets manager, or secure CI/CD variables.
</Callout>

***

After addressing duplication, focus on consistent naming conventions and readability — these help humans (and AI tools) reason about and maintain the code.

Links and references

* [Claude Code for Beginners](https://learn.kodekloud.com/user/courses/claude-code-for-beginners)
* [Node.js Best Practices — Error Handling](https://nodejs.dev/en/learn/error-handling-best-practices/)
* [Twelve-Factor App — Config](https://12factor.net/config)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/claude-code-for-beginners/module/dd033355-c556-4619-993c-ac717c0f5741/lesson/240b403c-8c15-4ced-a27a-89217a63da9f" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.