How to Fix XSS: Reflected and Stored Fixes
To fix XSS (cross-site scripting), encode untrusted data for the exact place it is written into the page, and use safe APIs and template features that do this for you. Input filtering and a Content Security Policy help, but output encoding is the actual fix.
This post is for developers and site owners whose scanner or pentest report flagged XSS and who need the fix, not the definition. You will get a fix table by output context, safe versus unsafe code in JavaScript, Java and C#, the extra steps stored XSS needs, and a checklist to confirm the fix with a retest.
What XSS is, in one paragraph
XSS happens when your site puts someone else's text into a page and the browser treats it as code. An attacker's script then runs inside your visitor's session. In reflected XSS, the bad text arrives in the request (a search term in the URL, for example) and your page echoes it back. In stored XSS, the bad text is saved first (a comment, a profile name, a support ticket) and runs for everyone who views it later. A third kind, DOM XSS, happens entirely in browser JavaScript. The same fix idea covers all three: treat data as data.
The fix table: pick your output context
The right encoding depends on where the data lands. HTML encoding in the wrong place does not protect you. This table follows the OWASP XSS Prevention Cheat Sheet.
| Output context | Example | Fix | Never do |
|---|---|---|---|
| HTML body | <p>USER</p> | HTML-encode & < > " ', or use textContent | innerHTML, Html.Raw, unescaped template tags |
| HTML attribute | <input value="USER"> | Always quote the attribute, then attribute-encode | Unquoted attributes, user data inside onclick= or other on...= handlers |
| JavaScript | <script>var n = "USER"</script> | Avoid it. Use a data- attribute, or a <script type="application/json"> block with < escaped as \u003c, read with JSON.parse | eval, new Function, string concatenation into scripts, setTimeout("...") |
| URL | <a href="USER"> | Allow only http:, https:, mailto:, then attribute-encode. Use encodeURIComponent for parameter values | Printing user input straight into href or src (javascript: URLs run code) |
| Rich HTML (user can format text) | Comment editor | Sanitize with a maintained library such as DOMPurify | Writing your own regex filter |
If your report names a page and a parameter, find where that value is written out and match it to a row.
Fix XSS in JavaScript: safe versus unsafe
The most common bug is writing user data with innerHTML.
// UNSAFE: the browser parses the text as HTML
const q = new URLSearchParams(location.search).get("q");
results.innerHTML = "You searched for " + q;
// SAFE: the browser treats it as plain text
results.textContent = "You searched for " + q;
On the server side with Node and Express, the same mistake looks like this:
// UNSAFE: reflected XSS
app.get("/search", (req, res) => {
res.send("<h1>Results for " + req.query.q + "</h1>");
});
The fix is a template engine that escapes by default. In EJS, <%= q %> escapes the value, while <%- q %> does not. In React, {value} is escaped, but dangerouslySetInnerHTML is not. In Vue, {{ value }} is escaped, but v-html is not. In Angular, {{ value }} is escaped and [innerHTML] is sanitized, but calls like bypassSecurityTrustHtml turn that protection off.
If you must allow formatting, sanitize first:
el.innerHTML = DOMPurify.sanitize(userHtml);
For links, check the scheme before using a user-supplied address:
function safeUrl(input) {
try {
const u = new URL(input, window.location.origin);
return ["http:", "https:", "mailto:"].includes(u.protocol) ? u.href : "#";
} catch {
return "#";
}
}
For the browser-side variant, see the OWASP DOM based XSS Prevention Cheat Sheet.
Passing server data to scripts
Do not build a script by pasting values into it. Put the value in an encoded data- attribute and read it with JavaScript:
<div id="app" data-user-name="{{ name }}"></div>
<script src="/app.js"></script>
const name = document.getElementById("app").dataset.userName;
Fix XSS in Java
Plain string concatenation in a servlet is the classic reflected XSS.
// UNSAFE
out.println("<p>Hello " + request.getParameter("name") + "</p>");
// SAFE: OWASP Java Encoder
import org.owasp.encoder.Encode;
String name = request.getParameter("name");
out.println("<p>Hello " + Encode.forHtml(name) + "</p>");
The OWASP Java Encoder has one method per context: Encode.forHtml, Encode.forHtmlAttribute, Encode.forJavaScript and Encode.forUriComponent. Use the one that matches the table above.
In templates, use the escaping form. In JSP, <c:out value="${name}"/> escapes, while a bare ${name} does not by default. In Thymeleaf, th:text escapes and th:utext does not.
Fix XSS in C#
Razor encodes output automatically, so the bugs usually come from opting out.
// UNSAFE: Razor view
@Html.Raw(Model.Comment)
// SAFE: encoded by default
@Model.Comment
In controller or minimal API code that builds HTML by hand:
// UNSAFE
return Content("<p>" + name + "</p>", "text/html");
// SAFE
using System.Text.Encodings.Web;
return Content("<p>" + HtmlEncoder.Default.Encode(name) + "</p>", "text/html");
JavaScriptEncoder.Default and UrlEncoder.Default cover the other contexts. Microsoft's guide to preventing XSS in ASP.NET Core explains the rules in detail.
Stored XSS: how to fix it properly
Stored XSS needs the same output fix, plus a bit more work, because the bad data is already in your database and shows up in more places than you expect.
- Find every place the field is displayed. That includes the public page, the admin dashboard, email templates, PDF exports, CSV downloads and search results. Admin panels are a favorite spot to miss, and they are the most valuable target.
- Encode on output in each of those places. Do not rely on one cleaned-up page.
- Sanitize rich text. If users can format content, run it through an HTML sanitizer such as DOMPurify (JavaScript) or the OWASP Java HTML Sanitizer. Allow only the tags you need.
- Validate input as a second layer. Check length and format (a name field does not need
<characters). This reduces risk but never replaces output encoding. - Clean existing data. Search the affected columns for
<and for patterns likeon[a-z]+=andjavascript:, review the matches, then remove or encode them. Treat this as a spot check, not proof the data is clean. Fixing the code does not remove old malicious entries.
For reflected XSS, the same output fix applies. Also check error pages, 404 pages and redirect parameters, which often echo the URL back.
Add defense in depth (but do not stop there)
These settings limit the damage if an encoding mistake slips through. They do not fix the bug.
- Content Security Policy (CSP), a browser rule about which scripts may run. A restrictive starting point is
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'. This blocks inline scripts, so test it before you deploy it. Theframe-ancestors 'none'part stops your pages being embedded in iframes, so test that too. See the OWASP CSP Cheat Sheet. You can check your current headers with the security headers tool. - Cookie flags. Set session cookies with
HttpOnly; Secure; SameSite=Lax.HttpOnlystops scripts from reading the cookie, so a stolen session is harder to pull off. HttpOnly does not stop an attacker's script acting inside the logged-in session, so it does not replace the fix. - Correct content types. Return JSON as
application/json, nottext/html.
Confirm the fix: a retest checklist
Do not close the ticket just because the original payload stopped working. Run through this list:
- [ ] The exact payload from the report no longer runs.
- [ ] Send a harmless probe like
xss"'<>testto the same field. View the page source (not the rendered page). The characters should appear as HTML entities (such as<and>, with quotes as",",'or'), or be rejected. - [ ] Test the same data in every context from the table: HTML, attribute, script and URL.
- [ ] For stored XSS, check every page, admin view, email and export that shows the field.
- [ ] Check for other parameters and pages that use the same helper or template. One bug usually means a pattern.
- [ ] Search your code for risky sinks:
innerHTML,outerHTML,document.write,eval,dangerouslySetInnerHTML,v-html,Html.Raw,th:utext,<%-. - [ ] Confirm the CSP header and cookie flags are live in production, not just on staging.
- [ ] Ask whoever found it to retest, or run a fresh test. Automated scanners often miss XSS that needs a logged-in session or a multi-step flow, as covered in manual vs automated penetration testing.
Use test data you own, on sites you own or have permission to test.
Common mistakes that bring XSS back
- Blocklists. Stripping the word
scriptis easy to bypass. Encode instead. - Encoding once, too early. Data encoded for HTML is still wrong inside a script or URL. Encode at the moment of output, for that context.
- Double work in the wrong place. Do not store HTML-encoded text in the database. Store the raw value and encode when displaying it.
- Trusting the framework blindly. React, Razor and others are safe until someone uses the escape hatch.
If you are unsure whether other weak spots exist, the guide to whether your website is hackable covers what else attackers check.
Key takeaways
- Fix XSS by encoding output for its exact context (HTML, attribute, JavaScript or URL), not by filtering input alone.
- Prefer safe defaults:
textContent, auto-escaping templates, and the OWASP Java Encoder or .NETHtmlEncoder. AvoidinnerHTML,Html.Raw,v-htmlandeval. - For stored XSS, fix every place the data is displayed, sanitize rich text, and clean the bad data already saved.
- Add a CSP and
HttpOnlycookies as a safety net, then retest with the original payload and a source-view check.
Want a human to check your fix?
A scanner can tell you the XSS is gone from one URL. It cannot tell you whether the same mistake lives on five other pages. A Bug Circuit audit is a manual test by a real person, ending in a written report with evidence, severity and fix steps. The Essential plan is $49 one-time and includes 3 audits to request within a month. Every audit after the first on a website also retests the previous report, so you can confirm your fixes held. Bug Circuit reports problems and explains the fix. If you want us to do the fixing, we quote a price per issue first, and you pay only if you agree. It is a small-site audit, not a compliance certification or a multi-week enterprise pentest.
A real human security engineer audits your whole site by hand and sends a full report: every issue, its severity, and the exact fix. From $49, with a 14-day money-back guarantee.