> ## 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.

# Input Validation

> Explains importance of input validation, common vulnerabilities, and concrete mitigations for Express.js apps including rate limiting, size limits, parameterized queries, and security headers

Authentication and authorization control who can enter a system. Input validation controls what they (or automated bots) can send once inside: usernames, passwords, file uploads, query parameters, and other request data. This article explains why input validation is critical, what to check, and concrete mitigations you can apply to an Express.js demo application.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/Xs8Ruv7b0QCZf7iM/images/Claude-Code-for-Beginners/Security-Auditing-with-Claude-Code/Input-Validation/input-validation-demo-slide-kodekloud.jpg?fit=max&auto=format&n=Xs8Ruv7b0QCZf7iM&q=85&s=16df463ccd8d1f732a048e268d03086c" alt="A presentation slide showing the title &#x22;Input Validation&#x22; on a light background with a dark curved area on the right containing the word &#x22;Demo&#x22; in blue. A small &#x22;© Copyright KodeKloud&#x22; appears in the bottom-left corner." width="1920" height="1080" data-path="images/Claude-Code-for-Beginners/Security-Auditing-with-Claude-Code/Input-Validation/input-validation-demo-slide-kodekloud.jpg" />
</Frame>

## Why input validation matters

* Inputs are the attack surface for many high-impact issues: SQL/NoSQL injection, command injection, XSS, XXE, path traversal, and resource exhaustion via oversized requests.
* Automated attacks (bots) are common — apply rate limiting and sensible request limits to reduce automated abuse.
* Proper validation is multi-layered:
  * Enforce size/type checks and required-field validation.
  * Parameterize database queries; never interpolate raw user input into SQL.
  * Encode/escape output by context (HTML, JS, URL, CSS).
  * Disable or restrict dangerous parser features (e.g., XML external entities).

A classic example that illustrates the risk of unsanitized inputs is the “Little Bobby Tables” SQL injection joke: if your app concatenates unescaped user input into SQL (e.g., a username like `Robert'); DROP TABLE students; --`), an attacker can execute arbitrary SQL. The correct approach is to use parameterized queries or ORM query binding.

Useful reference: [OWASP SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection)

## Running an automated audit (example)

In this lesson we used an automated assistant from the project directory to review input validation for an Express.js demo app:

```bash theme={null}
jeremy@MACSTUDIO Express-login-demo % claude
* Welcome to Claude Code!
/help for help, /status for your current setup
cwd: /Users/jeremy/Repos/Claude Code Course/Express-login-demo

> Try "fix typecheck errors"
? for shortcuts
```

We provided a checklist prompt that covered common input validation classes. The assistant used that checklist to generate an endpoint-by-endpoint validation matrix and prioritized remediation guidance.

### Example checklist (condensed)

| Category | What to check |
| - | - |
| SQL Injection | Raw SQL queries without parameterization, dynamic query building, stored procedure usage |
| NoSQL Injection | Unvalidated query operators (e.g., `$where`, `$ne`, `$gt`), JavaScript execution in queries |
| Command Injection | Child process spawning, shell command construction with user input |
| XSS Prevention | Input sanitization, output encoding, appropriate Content-Type headers |
| XXE (XML External Entity) | XML parser configuration, file upload handling |
| Path Traversal | File system operations, directory traversal prevention |
| Request Validation | Body size limits, parameter pollution, type checking, required fields |

## Typical findings and prioritized fixes

Automated reports often surface similar gaps across small demos:

* Missing or weak rate limiting on authentication endpoints — enables brute-force attacks.
* No request body size limits — opens the app to memory/CPU exhaustion.
* Weak or default JWT secrets — risk of token forgery.
* Incomplete sanitation of user-supplied content or missing security headers.
* Verify any raw SQL strings even when the app generally uses parameterized queries.

Suggested prioritization:

| Issue | Risk | Quick remediation |
| - | - | - |
| Missing rate limiting on login | Critical | Add express-rate-limit to login route |
| No request size limits | Critical | Limit body parser size with `express.json({ limit })` |
| Weak JWT secret | High | Use secure, environment-managed secrets; rotate regularly |
| Missing security headers | Medium | Use Helmet and CSP where appropriate |

## Example exploit (illustrative only) — brute-force

Do not run these commands against third-party systems. This is an illustrative brute-force loop for testing in a controlled environment you own:

```bash theme={null}
# Brute force example (illustrative only; run only against systems you own)
for i in {1..1000}; do
  curl -s -X POST http://localhost:3000/api/auth/login \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"test@example.com\",\"password\":\"attempt$i\"}" >/dev/null &
done
```

Mitigation: apply rate limiting middleware to authentication endpoints:

```javascript theme={null}
// server.js (or whichever file configures your Express app)
const rateLimit = require('express-rate-limit');

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // limit each IP to 5 login attempts per windowMs
  message: { error: 'Too many login attempts, please try again later' },
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

// Attach limiter to the login route only
app.use('/api/auth/login', loginLimiter);
```

## Limit request body size to prevent resource exhaustion

Tune body-parsing middleware to restrict payload sizes:

```javascript theme={null}
// server.js - body parsing with size limit
app.use(express.json({ limit: '100kb' })); // tune to an appropriate limit for your app
app.use(express.urlencoded({ extended: true, limit: '100kb' }));
```

### Large-body test (illustrative only)

This curl command sends a very large payload. Only use in a local, controlled environment you own:

```bash theme={null}
# Danger: only for local testing in a controlled environment
curl -X POST http://localhost:3000/api/some-endpoint \
  -H "Content-Type: text/plain" \
  --data-binary "$(printf 'A%.0s' {1..10000000})"
```

<Callout icon="warning" color="#FF6B6B">
  Do not run DoS or resource-exhaustion tests against systems you do not own or explicitly have permission to test. Always perform tests in a controlled environment.
</Callout>

## Other concrete checks and fixes

* SQL / NoSQL injection
  * Use parameterized queries or ORM binding APIs.
  * For MongoDB, never accept raw query operators from clients; whitelist fields and operators instead.
* Command injection
  * Avoid building shell commands using user input. Use child process APIs with explicit argument arrays and strict validation.
* XSS
  * Apply contextual output encoding, sanitize HTML inputs or disallow rich HTML, and implement a Content Security Policy (CSP).
* XXE
  * Disable external entity resolution in XML parsers or prefer JSON parsing where possible.
* Path traversal
  * Resolve and sanitize file paths, disallow `..` sequences, and restrict file operations to an allowed base directory.
* Parameter pollution and type validation
  * Use validation middleware like express-validator, Joi, or Zod to coerce and validate types.
* Security headers
  * Use Helmet and configure headers (HSTS, X-Content-Type-Options, Referrer-Policy) appropriately.

## Example consolidated audit summary (sample)

```markdown theme={null}
**Application:** Express Login Demo  
**Audit Date:** 2025-08-20  
**Auditor:** Automated Assistant / Claude Code  
**Overall Risk Score:** 6/10 (Medium-High)

## Executive Summary
The application demonstrates good foundational practices (parameterized queries, basic input validation) but has high-impact gaps: missing rate limiting, no request size limits, and weak JWT secret configuration. These issues should be addressed immediately.

## Key Findings
- ✅ SQL Injection protection implemented (parameterized queries)
- ❌ Missing rate limiting on login endpoints (Critical)
- ❌ No request body size limits (Critical)
- ❌ Weak or default JWT secret (High)
- ❌ Missing or incomplete security headers (Medium)
```

## Where to get the prompts

If you want the same prompts used to drive the automated audit, see the example prompt repository:

* [https://github.com/JeremyMorgan/Claude-Code-Reviewing-Prompts](https://github.com/JeremyMorgan/Claude-Code-Reviewing-Prompts)

## Next steps

Input validation ties closely to database access patterns and authentication flows. After fixing the highest-risk items (rate limiting, request sizes, secrets), review database interactions and permissions (stored procedures, ORM usage, least-privilege accounts). Repeat automated scans and follow up with targeted manual review of any remaining high-risk endpoints.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/claude-code-for-beginners/module/eaf75a67-f28f-4217-a3f9-92d411403129/lesson/7bcf3c94-a44f-46e4-b3f2-449f2e1c0526" />
</CardGroup>


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