JSON Security Risks: Injection and Mitigation
2026-01-14
Is JSON Safe?
While JSON is just a data format, how it is parsed and used can introduce serious security vulnerabilities.
1. JSON Injection
If you construct JSON strings by concatenating user input without proper escaping, attackers can inject malicious fields.
Vulnerable Code:
const json = '{"user": "' + userInput + '"}';
// If userInput is '", "admin": true, "dummy": "'
// The result becomes {"user": "", "admin": true, "dummy": ""}
Fix: Always use JSON.stringify() or a secure serialization library.
2. XSS via JSON
When JSON data is embedded directly into HTML (e.g., in a <script> tag for initial state), it must be sanitized.
<script>
// DANGEROUS if data contains </script>
const state = {"data": "</script><script>alert(1)</script>"};
</script>
Fix: Escape HTML characters or use libraries specifically designed for safe state hydration (like Next.js does automatically).
3. Large Payload Attacks
Parsing a massive JSON file (e.g., 100MB+) can block the event loop in Node.js, causing a Denial of Service (DoS).
Fix:
- Set body size limits (e.g.,
limit: '1mb'). - Use streaming parsers for large files.