Security
Sanitizing User Input
Master user input sanitization in JavaScript. Learn to validate inputs, parse data schemas using Zod, and use DOMPurify to strip HTML payloads.
1. Introduction
Input Sanitization is the process of cleaning user input to ensure it is safe to process, store, or render. It is often combined with Input Validation, which verifies that inputs match specific data structures or schemas.
2. Why It Matters
All user input should be treated as untrusted. Malicious inputs can trigger XSS attacks, SQL injections, or crash the application by passing unexpected data formats. Validating and sanitizing inputs at the application boundary protects your code from these issues.
3. Real-World Analogy
Think of a Warehouse Shipping Receiving Dock (Security gate):
- No Security: Trucks pull up and drop off any package. An attacker drops off a crate of toxic materials. Symmetrically, the warehouse staff processes the crate, causing a hazard.
- Validation (Manifest inspection): The gate guard checks the paperwork manifest. If the document says "50 boxes of coffee cups" (schema matching), the truck is let in. If the manifest has invalid or missing fields, the truck is turned away.
- Sanitization (Disinfection chamber): The packages are sprayed down or opened to strip out packing peanuts and contaminants (sanitized) before they are sent to the warehouse shelves. Only safe, cleaned goods enter the facility.
4. Schema Validation with Zod
Zod is a popular schema validation library. It allows you to define a schema and parse inputs, throwing validation errors if the input does not match the schema:
5. HTML Sanitization with DOMPurify
If your application must support rich text input (like an HTML markdown editor), use DOMPurify to sanitize the HTML strings, stripping out script tags and malicious attributes:
6. Practical Example
This script demonstrates combining schema validation and HTML sanitization inside an API request controller:
7. Common Mistakes
- Validating input only on the client side: Client-side validation is a user experience feature (providing immediate feedback). Attackers can bypass client-side validation easily by sending requests directly using tools like curl or Postman. Always perform validation and sanitization on the server side.
8. Quick Quiz
Q1: What is the primary difference between input validation and input sanitization?
A) Validation cleans inputs while sanitization throws errors
B) Validation checks if data matches a schema structure, while sanitization strips out unsafe characters or scripts
Answer: B — Validation checks data structures and boundaries, while sanitization cleans inputs to make them safe to render or process.
9. Scenario-Based Challenge
The Safe Feedback Form Input Schema:
A feedback form accepts a name, rating (1-5), and a comment. You want to enforce schema validation using Zod and sanitize the comment text to strip out script tags. Design this schema validation block.
10. Debugging Exercise
Explain why this validation block is vulnerable to security bypasses:
// Client-side signup code function checkForm() { const email = document.getElementById('email').value; if (!email.includes('@')) { alert('Invalid Email'); return false; } return true; }
// Express backend route app.post('/register', (req, res) => { // Bug: saving directly to database without server-side validation! db.saveUser(req.body); res.send('Registered'); });
View Solution
Diagnosis: The validation is performed only on the client side. An attacker can bypass the form validation completely by submitting requests directly to the /register API endpoint using curl, injecting invalid email payloads or script injections into the database.
Fix: Re-run validation checks on the server side before writing to the database:
app.post('/register', (req, res) => {
const { email } = req.body;
if (!email || !email.includes('@')) {
return res.status(400).send('Invalid Email'); // Validate on server!
}
db.saveUser(req.body);
res.send('Registered');
});
11. Interview Questions
🟢 Q1: Why is it critical to validate inputs on the server side even if client-side validation is active?
Answer: Client-side validation is a user experience feature designed to provide immediate feedback. It is easily bypassed by attackers who can use API clients (like Postman or curl) to submit requests directly to your backend.
Server-side validation is your application's security boundary. It ensures that no invalid or malicious data enters your database or application logic, protecting your backend services from injection attacks and crashes.
12. Production Considerations
- • Sanitize on Output: It is often best to validate data format on input, store the raw data, and sanitize HTML markup when rendering it to users. This preserves the original data structure in your database while protecting users from XSS attacks when displaying content.