advanced

XSS, SQL injection, and NoSQL injection

Prevent script and query injection through contextual output encoding, parameterized queries, schema validation, escaping discipline, and safe templating.

Injection attacks smuggle executable syntax into interpreters: HTML/JS (XSS), SQL, shell, LDAP, or MongoDB query operators.

SQL defense: parameterized queries only — never string-concatenate user input.

					// Safe
await db.query('SELECT * FROM users WHERE email = $1', [email]);

// Unsafe
await db.query(`SELECT * FROM users WHERE email = '${email}'`);
				

XSS defense: contextual output encoding in templates, CSP, sanitize rich HTML with vetted libraries if unavoidable. Stored XSS persists in DB; reflected XSS echoes input; DOM XSS mutates client-side sinks.

NoSQL injection: validate types — reject objects where strings expected; avoid passing raw user objects into query builders.

On interviews: explain prepared statements vs escaping; why `innerHTML` is risky; ORM does not eliminate SQLi if raw queries exist.

Common pitfalls: LIKE clauses with unescaped `%`; logging user input into HTML emails; `$where` in legacy Mongo APIs.

The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.

Checklist:

  • Parameterize all SQL; validate shapes for NoSQL.
  • Encode output per sink (HTML, attr, URL, JS).
  • CSP and sanitize untrusted HTML deliberately.
  • Audit raw query and template escape paths.