π« 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 ofeval()
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.