JAVASCRIPT

Prevent Cross-Site Scripting (XSS) with Output Encoding

Learn to prevent Cross-Site Scripting (XSS) vulnerabilities by properly encoding user-generated content before rendering it in HTML, safeguarding your web application.

function escapeHTML(str) {
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

// Example of potentially malicious user input
const userInput = "<script>alert('XSS Attack!');</script>Hello, <b>User</b>!";

// Simulate rendering user input directly (VULNERABLE!)
// const vulnerableElement = document.getElementById('vulnerable-output');
// if (vulnerableElement) {
//   vulnerableElement.innerHTML = userInput; // DANGER! This would execute the script
// }
// console.log("Vulnerable output (if rendered):", userInput);


// Correctly escape user input before rendering
const safeOutput = escapeHTML(userInput);
console.log("Safe output:", safeOutput); // Output: &lt;script&gt;alert('XSS Attack!');&lt;/script&gt;Hello, &lt;b&gt;User&lt;/b&gt;!

// Simulate rendering safe output
const safeElement = document.getElementById('safe-output');
if (safeElement) {
  safeElement.innerHTML = safeOutput; // Safe to render
}

/* HTML context for the example:
<div id="vulnerable-output"></div>
<div id="safe-output"></div>
*/
How it works: This snippet provides a simple JavaScript function, `escapeHTML`, to prevent Cross-Site Scripting (XSS) by encoding potentially malicious user input. XSS attacks occur when an attacker injects client-side scripts into web pages viewed by other users. The `escapeHTML` function works by creating a temporary DOM element, appending the raw string as a text node, and then retrieving its `innerHTML`. This process automatically escapes HTML special characters (like `<`, `>`, `'`, `"`, `&`), rendering them as harmless HTML entities (e.g., `&lt;`, `&gt;`), which prevents browsers from interpreting them as executable code. Always encode user-generated content before rendering it.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs