SmartCodingTips

🚫 Avoiding XSS & eval() in JavaScript

Cross-Site Scripting (XSS) and unsafe usage of eval() are two of the most common JavaScript security issues. Let’s explore what they are and how to prevent them.

πŸ” What is XSS?

XSS occurs when an attacker injects malicious JavaScript into a webpage that gets executed in the user's browser. This can steal cookies, log keystrokes, or hijack sessions.

❌ Bad Example (XSS Vulnerable)

// User input directly added to innerHTML
const input = "<script>alert('XSS')</script>";
document.getElementById("output").innerHTML = input;

βœ… Good Example (Safe)

// Use textContent to escape HTML
const input = "<script>alert('XSS')</script>";
document.getElementById("output").textContent = input;

🧨 Why eval() is Dangerous

eval() executes strings as code, which can be exploited to run malicious scripts if user input is passed into it.

❌ Avoid This

const userCode = prompt("Enter JS:");
eval(userCode); // πŸ‘ˆ Extremely dangerous!

βœ… Use Safe Alternatives

  • For math: use Function() only with caution or better yet, a math parser.
  • Use JSON.parse() instead of eval() to handle JSON safely.
  • Avoid dynamic code generation altogether β€” it's rarely necessary.

πŸ›‘οΈ Best Practices

  • Always sanitize and validate input.
  • Escape output that goes into the DOM.
  • Use libraries like DOMPurify to sanitize rich text safely.
  • Set a strong Content Security Policy (CSP).
πŸ’‘ Pro Tip: Never trust user input β€” always treat it as unsafe until properly validated and sanitized.