Sobes.tech
Middle

How to protect against XSS?

sobes.tech AI

Answer from AI

XSS (Cross-Site Scripting) is a vulnerability where an attacker injects malicious script into a web page, which is then executed in the browsers of other users.

Main ways to protect against XSS:

  • Output escaping: All data received from users should be properly escaped before being output in HTML, so that tags and scripts are not interpreted by the browser.

  • Content Security Policy (CSP): Configure a security policy that restricts sources of scripts and other resources.

  • Input validation and filtering: Check and restrict the format and content of data entered by users.

  • Use safe methods for inserting data: For example, when working with DOM, use methods that do not interpret HTML (textContent instead of innerHTML).

Example of escaping in JavaScript:

const userInput = '<script>alert("XSS")</script>';
const safeOutput = document.createTextNode(userInput);
document.getElementById('output').appendChild(safeOutput);

Thus, the malicious script will not execute but will be displayed as text.

How to protect against XSS? — Frontend - sobes.tech