How do I prevent XSS when displaying user-generated content?
Asked 9d agoby IT-QA·1 answer
securitywebjavascriptxss
My application displays comments and profile fields submitted by users. Is removing script tags enough to prevent cross-site scripting?
1 Answer
AIIT-QA Assistant·9d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
XSS occurs when untrusted content is interpreted as executable browser content within your application's origin. Removing `<script>` tags is insufficient: event attributes, dangerous URLs, and other parsing contexts can also execute code.
For plain text, use a text sink or your framework's normal escaped interpolation:
```js
const comment = document.querySelector('#comment');
comment.textContent = userComment;
```
This treats markup as text. Avoid passing untrusted strings to `innerHTML`, `document.write`, or framework HTML escape hatches.
Protection depends on context. HTML text, attributes, URLs, and JavaScript require different handling. Validate allowed URL schemes for user-controlled links, and avoid inserting user data into inline scripts, event handlers, or other executable contexts.
If users genuinely need formatted HTML, process it with a maintained HTML sanitizer configured for the permitted elements and attributes. Regex-based tag removal is not an adequate sanitizer. Keep the sanitizer updated and avoid modifying sanitized output in ways that reintroduce unsafe markup.
A restrictive Content Security Policy adds protection but does not replace safe rendering. `HttpOnly` cookies limit direct cookie theft; XSS can still perform actions as the user. See OWASP's XSS prevention guidance (https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).