Square CloudSquare Cloud

What is XSS (cross-site scripting) and how to prevent it

XSS (cross-site scripting) is a flaw where a site inserts an attacker's script into a page and the victim's browser runs it. The main defense is escaping each value for the spot where it lands in the HTML, with sanitization for user HTML and CSP as a second layer.

Updated 6 min read

Learning objectives

After reading this article you will be able to:

  • Recognize the three types of XSS: reflected, stored and DOM-based
  • Escape data by context and swap innerHTML for textContent
  • Use sanitization, CSP and HttpOnly cookies as extra layers
On this page

A comment box, a search page that repeats what you typed, the username at the top of the page: every place your site shows something that came from outside is a place where HTML can get in. If that HTML carries JavaScript, it runs in the browser of whoever opens the page, with the same access as your own code.

That is what makes XSS serious. The browser cannot tell the attacker's script from yours: it reads what the page shows, sends requests with the victim's session and can swap the screen for a fake login form.

What is XSS?#

Cross-site scripting (XSS) is the injection of code, almost always JavaScript, into a page of a trusted site, which another user's browser then runs. What defines XSS is untrusted data turning into code inside your origin: the same mistake as SQL injection, only in the browser.

Running on your origin, the script can:

  • read the page's content and send it to an attacker's server;
  • call your API with the victim's cookies, which the browser attaches on its own;
  • read localStorage, where many SPAs keep tokens;
  • change the page to ask for a password or payment details.

What are the types of XSS?#

OWASP splits XSS into three types, based on where the script comes from:

Type Where the script comes from Example
Reflected The request itself, sent straight back A search page that repeats ?q= in the page
Stored The database, saved earlier A comment, a profile name, a chat message
DOM-based The page's JavaScript, without the server building the HTML A URL fragment written with innerHTML

Stored XSS is the most severe, because it hits everyone who opens the page, no tricky link needed (MDN also calls it persistent XSS). Reflected XSS depends on the victim clicking a crafted link. DOM-based XSS may not even show up in server logs, because the payload can travel in the URL fragment (the part after #), which the browser does not send.

A reflected XSS in Express:

js
import express from "express";

const app = express();

// VULNERABLE: the search term goes into the HTML raw
app.get("/search", (req, res) => {
  res.send(`<h1>Results for ${req.query.q}</h1>`);
});

app.listen(process.env.PORT ?? 3000);

A link to /search?q=<img src=x onerror=alert(document.domain)> makes the page run the alert. There is no <script> tag: the image fails to load and the onerror attribute fires. That is why filtering the word script does not protect you.

How do you prevent XSS with context-aware escaping?#

Escaping (or output encoding) means replacing characters with special meaning by harmless equivalents before inserting the data. In the HTML body, < becomes &lt;, and the browser shows the symbol instead of opening a tag. OWASP lists the five characters to encode in that context: &, <, >, " and '.

js
function escapeHtml(text) {
  return String(text)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#x27;");
}

app.get("/search", (req, res) => {
  res.send(`<h1>Results for ${escapeHtml(req.query.q ?? "")}</h1>`);
});

In practice, few people write that function. Django templates, Flask templates (Jinja with autoescaping on .html files) and React's JSX escape by default. The risk is in the outputs that turn escaping off: |safe and Markup in Flask, |safe in Django, dangerouslySetInnerHTML in React and v-html in Vue, whose own docs say never to use it on user-provided content.

The right escaping depends on where the data lands:

  • HTML body: entity encoding, as above.
  • Attribute: always quote the value and encode it. MDN shows that an unquoted class={{ value }} accepts x onmouseover=alert(1) and becomes an event attribute.
  • URL: encodeURIComponent() on each parameter value. In an href built from user data, accept only http: and https:, which blocks javascript:.
  • Inside <script> or CSS: avoid putting untrusted data there. OWASP advises against interpolating into those contexts.

Why is textContent safer than innerHTML?#

DOM-based XSS starts in the site's own JavaScript:

js
// the URL ends with #name=Ana
const name = new URLSearchParams(location.hash.slice(1)).get("name") ?? "guest";

// VULNERABLE: the value is parsed as HTML
document.querySelector("#greeting").innerHTML = `Hello, ${name}`;

// SAFE: textContent treats the value as plain text
document.querySelector("#greeting").textContent = `Hello, ${name}`;

MDN explains that innerHTML parses its value as HTML. It does not run a <script> tag inserted this way, but it does run an image's onerror, so that protection is an illusion. When the value is text, use textContent, createTextNode, value or setAttribute with a fixed, safe attribute name, which OWASP calls safe sinks. The dangerous ones either parse HTML (besides innerHTML, outerHTML, insertAdjacentHTML and document.write) or run text as code (eval, and setTimeout with a string).

What if users need to send HTML?#

In a rich text editor or a description with bold and links, escaping would break the formatting. The answer is sanitization: removing from the HTML everything that can run code (scripts, event attributes, javascript: URLs) and keeping the rest. MDN advises a reputable library over homemade regular expressions, and OWASP recommends DOMPurify.

js
import DOMPurify from "dompurify";

const clean = DOMPurify.sanitize('<b>hi</b><img src=x onerror="alert(1)">');
// result: <b>hi</b><img src="x">
document.querySelector("#description").innerHTML = clean;

Sanitize close to the output and do not modify the HTML afterward: OWASP warns that changing the result can reopen the hole. Keep the library up to date. On the server, DOMPurify runs together with jsdom.

How do CSP and HttpOnly cookies limit the damage?#

Content Security Policy (CSP) is an HTTP header that tells the browser where the page may load and run scripts from. According to MDN, a policy with script-src (or default-src) and without 'unsafe-inline' blocks inline scripts and event attributes, like the onerror in the example, even when the injection happens. MDN recommends a strict, nonce-based CSP:

http
Content-Security-Policy: script-src 'nonce-{RANDOM}'; object-src 'none'; base-uri 'none'

The server generates a new, unpredictable nonce for every response and repeats it on your own <script nonce="..."> tags. To roll it out without breaking the site, start with Content-Security-Policy-Report-Only, which only reports violations. The full setup, along with HSTS and the other headers, is in HTTP security headers.

The HttpOnly attribute stops JavaScript from reading the cookie through document.cookie, so an XSS cannot copy the session ID. The script can still send requests from the page with the victim's session, because the browser attaches the cookie: HttpOnly limits theft, not the attack. That is also why OWASP advises against keeping session identifiers in localStorage, which any script can read (see JWT vs sessions).

Both are extra layers. MDN is direct: CSP is not an alternative to sanitizing input; a site should sanitize and set a CSP. A WAF may also block common payloads, but OWASP warns it cannot reliably stop every XSS or fix the code, and DOM-based XSS through the URL fragment never even reaches it. Close XSS first, because it also defeats CSRF defenses: the script runs on your origin and reads the token from the page.

How to do this on Square Cloud#

Escaping, sanitization and textContent live in your code, on any host. What the platform decides is the path responses take to the browser.

On Square Cloud, the headers your application sends, such as Content-Security-Policy and HSTS, pass through the proxy intact. You set the CSP on your own server (in an Express middleware, for example) and it reaches the browser exactly as it left. Every published web application gets a *.squareweb.app subdomain with HTTPS, so the session cookie can carry Secure on top of HttpOnly.

Every plan also includes a WAF, a generic layer at the edge that does not replace escaping in your code or guarantee that an XSS gets blocked. See the details of the Square Cloud network.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

DDoS-protected network

FAQs

Does React prevent XSS?

Mostly. React escapes any text you put in JSX, but `dangerouslySetInnerHTML` turns that protection off, and a link built from a user's URL should only accept http and https. Vue's `v-html` carries the same risk.

What is the difference between XSS and CSRF?

With XSS, the attacker's code runs inside your site, in the victim's browser. With CSRF, another site makes the victim's browser send an authenticated request to yours. XSS defeats CSRF defenses, because the script is already on your origin.

Do HttpOnly cookies prevent XSS?

They do not stop the attack, but they stop the script from reading the session cookie through `document.cookie`. The script can still send requests with the victim's session while they are on the page.

Is CSP alone enough against XSS?

No. MDN and OWASP treat CSP as defense in depth: it blocks inline scripts and scripts from unapproved sources, but it does not fix the injection. Escaping and sanitization are still required.

Does stripping script tags fix XSS?

No. An attribute like `onerror` on an image runs code without any `<script>` tag. Use a maintained sanitizer such as DOMPurify instead of homemade filters.

Next articleWhat is CSRF and how to protect your forms and APIsCSRF is when another site makes the victim's browser send an authenticated request to yours. See how SameSite, tokens and Origin checks stop the attack.

More in Security

See all 24 articles